-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreport_client.html
More file actions
2655 lines (2653 loc) · 217 KB
/
Copy pathreport_client.html
File metadata and controls
2655 lines (2653 loc) · 217 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ERD swarm reports</title>
<style>
:root { color-scheme: light; --bg:#ffffff; --panel:#f8f9fa; --text:#1a1a1b; --dim:#787c7e; --green:#6aaa64; --green-complete:#9fc09f; --blue:#5f89c2; --completed-bg:#eaf2fc; --yellow:#c9b458; --gray:#787c7e; --border:#d3d6da; --sweep-empty:#d3d6da; --red:#d14b4b; --amber:#b59f3b; --hover-tint:#edf5ec; --popover-shadow:0 5px 16px rgba(0,0,0,.14); --header-bg:rgba(255,255,255,.97); --status-amber-bg:#fff9e8; --status-amber-text:#6f5a13; --status-red-bg:#fff1f1; --card-historical-bg:#f3f4f6; --tile-blank-outline:#878a8c; --chip-exact-text:#3e7c3a; --chip-cut-text:#7d6812; --chip-loss-text:#a32c2c; --flash-improved-bg:#e8f4e7; --flash-changed-bg:#fff0f0; }
/* The OS/browser's own color-scheme preference drives the palette live --
no toggle, no stored setting. Every color elsewhere in this file reads
one of these custom properties rather than a literal, so flipping the
preference repaints the whole report without a reload. */
@media (prefers-color-scheme: dark) {
:root {
color-scheme: dark;
--bg:#121213; --panel:#1c1c1e; --text:#e4e6eb; --dim:#9aa0a6;
--green:#538d4e; --green-complete:#3f6b3c; --blue:#6f9ed7; --completed-bg:#1d3048; --yellow:#b59f3b; --gray:#3a3a3c;
--border:#3a3a3c; --sweep-empty:#3a3a3c; --red:#e0575a; --amber:#d4bb55;
--hover-tint:#1f2e1d; --popover-shadow:0 5px 16px rgba(0,0,0,.55);
--header-bg:rgba(18,18,19,.97); --status-amber-bg:#3a3016; --status-amber-text:#e8cf7a;
--status-red-bg:#3a1e1e; --card-historical-bg:#232326; --tile-blank-outline:#565758;
--chip-exact-text:#7fc47a; --chip-cut-text:#d9c069; --chip-loss-text:#e07a7a;
--flash-improved-bg:#22371f; --flash-changed-bg:#3a1e1e;
}
}
* { box-sizing:border-box; }
html, body { margin:0; min-width:0; background:var(--bg); color:var(--text); font:13px/1.4 ui-monospace,SFMono-Regular,Consolas,monospace; }
body { overflow-x:hidden; }
button, input, select { min-height:30px; border:1px solid var(--border); border-radius:5px; background:var(--bg); color:var(--text); font:inherit; padding:.25rem .5rem; }
button { cursor:pointer; }
/* A button naming a word draws it as tiles, like the word is drawn
everywhere else, so the label and the spine above it read alike. */
.word-button { display:inline-flex; align-items:center; gap:.35rem; }
button:disabled { cursor:default; opacity:.45; }
button:hover, button[aria-current="page"], button[aria-pressed="true"] { border-color:var(--green); background:var(--hover-tint); }
.layout-toggle { display:inline-flex; align-items:center; gap:.35rem; margin-left:.25rem; padding-left:.6rem; border-left:1px solid var(--border); }
.layout-toggle[hidden] { display:none; }
.layout-toggle .cap { color:var(--dim); font-size:.8rem; white-space:nowrap; }
.layout-toggle .seg { display:inline-flex; }
.layout-toggle .seg button { border-radius:0; }
.layout-toggle .seg button:first-child { border-radius:5px 0 0 5px; }
.layout-toggle .seg button:last-child { border-radius:0 5px 5px 0; margin-left:-1px; }
input[type="checkbox"] { min-height:auto; accent-color:var(--green); }
header { position:sticky; top:0; z-index:5; background:var(--header-bg); border-bottom:1px solid var(--border); padding:.4rem clamp(.5rem,1.5vw,1rem); }
.nav, .branch-target, .metrics, .chips, .row-actions { display:flex; flex-wrap:wrap; gap:.35rem; align-items:center; }
.branch-target { margin-top:.35rem; flex-wrap:nowrap; }
#branch-target-input { flex:1 1 8rem; min-width:6rem; }
details.root-progress-panel { border:1px solid var(--border); border-radius:6px; background:var(--panel); padding:.4rem .5rem; margin:.5rem 0; }
details.root-progress-panel > summary { cursor:pointer; font-weight:bold; }
/* The table is wider than a phone and longer than a screen; it scrolls
inside this box on both axes so the page body never does. */
.root-progress-scroll { overflow:auto; max-height:60vh; overscroll-behavior:contain; margin-top:.4rem; }
table.root-progress { border-collapse:collapse; white-space:nowrap; }
table.root-progress th, table.root-progress td { padding:.15rem .5rem; text-align:right; }
table.root-progress td { border-bottom:1px solid var(--border); }
/* A collapsed border does not travel with a sticky header, so the rule
under the header row is drawn as an inset shadow. */
table.root-progress thead th { position:sticky; top:0; z-index:1; background:var(--panel); box-shadow:inset 0 -1px 0 var(--border); }
table.root-progress th:first-child, table.root-progress td:first-child { text-align:left; }
/* The tiles name the row, so they stay put while the measurements scroll
under them. An opaque background is required, not decoration: without
it the scrolled cells show through. The header's own sticky rule wins
on the top-left cell, so it carries the higher z-index. */
table.root-progress th:first-child, table.root-progress td:first-child {
position:sticky; left:0; background:var(--panel); z-index:1;
box-shadow:inset -1px 0 0 var(--border); }
table.root-progress thead th:first-child { z-index:2; }
/* The payer column holds a word rather than a measurement, and takes two
forms -- tiles, or the text "self". Centring the whole column keeps
them on one axis; the numeric right-alignment would strand "self" at
the edge while the tiles sat wherever their own rule put them. */
table.root-progress th:last-child, table.root-progress td:last-child { text-align:center; }
/* How many guesses that opener needed to reach this branch. Without it a
bare opener reads as having isolated the branch with its first guess. */
.payer-depth { margin-left:.25rem; color:var(--dim); font-size:.85em; }
table.root-progress tr.dim td { color:var(--dim); }
table.root-progress td.state-solved { color:var(--green); }
table.root-progress td.state-loss { color:var(--red); }
table.root-progress td.state-waiting { color:var(--dim); }
table.root-progress td.state-inherited { color:var(--accent, var(--green)); }
table.root-progress td.state-trivial { color:var(--dim); }
details.root-progress-legend-panel { margin-top:.4rem; }
details.root-progress-legend-panel > summary { cursor:pointer; color:var(--dim); font-size:.9em; }
dl.root-progress-legend { margin:.4rem 0 0; display:grid; grid-template-columns:max-content 1fr; gap:.15rem .6rem; font-size:.9em; }
dl.root-progress-legend dt { font-weight:bold; }
dl.root-progress-legend dd { margin:0; color:var(--dim); }
@media (max-width:560px) { dl.root-progress-legend { grid-template-columns:1fr; }
dl.root-progress-legend dd { margin:0 0 .35rem; } }
.work-distribution-scroll { overflow-x:auto; margin-top:.4rem; }
table.work-distribution { border-collapse:collapse; white-space:nowrap; }
table.work-distribution th, table.work-distribution td { padding:.15rem .5rem; text-align:right; }
table.work-distribution td { border-bottom:1px solid var(--border); }
table.work-distribution thead th { background:var(--panel); box-shadow:inset 0 -1px 0 var(--border); }
table.work-distribution th:first-child, table.work-distribution td:first-child { text-align:left; }
/* The ratio is the column the report exists for, so an imbalanced band is
coloured rather than left for the reader to find among the numbers. */
table.work-distribution td.ratio-heavy { color:var(--red); }
table.work-distribution td.ratio-light { color:var(--dim); }
p.work-distribution-legend { margin:.4rem 0 0; color:var(--dim); font-size:.9em; }
.work-distribution-refresh { display:flex; align-items:center; gap:.5rem; flex-wrap:wrap; margin:.4rem 0; font-size:.9em; }
details.filters { margin-top:.35rem; color:var(--dim); }
details.filters > summary { cursor:pointer; padding:.1rem 0; }
.control-group { border:1px solid var(--border); border-radius:6px; background:var(--panel); padding:.4rem .5rem; margin-top:.4rem; }
.control-group[hidden] { display:none; }
.group-head { display:flex; align-items:baseline; gap:.5rem; }
.group-head .gname { font-weight:700; color:var(--text); }
.group-head .ghint { color:var(--dim); font-size:.82rem; }
/* Fields size to their content and wrap; a numeric input is capped to its
magnitude rather than stretched to a shared column width. */
.field-flow { display:flex; flex-wrap:wrap; gap:.4rem .85rem; align-items:end; margin-top:.35rem; }
.field-flow input[type="number"] { width:4.2rem; text-align:right; padding-left:.35rem; padding-right:.35rem; }
.field-flow input.narrow { width:2.9rem; } .field-flow input.medium { width:3.4rem; }
.field { display:grid; gap:.1rem; color:var(--dim); }
.field[hidden] { display:none; }
.fieldlabel { display:flex; align-items:baseline; gap:.3rem; }
.status-line { display:flex; flex-wrap:wrap; gap:.4rem; align-items:baseline; padding:.15rem 0; }
.status-line[hidden] { display:none; }
.status-line > .label { color:var(--dim); }
.statuses { display:flex; flex-wrap:wrap; gap:.5rem; align-items:baseline; }
.statuses label { display:inline-flex; gap:.25rem; align-items:center; white-space:nowrap; }
.statuses label[hidden] { display:none; }
.statuses label.inert { opacity:.45; }
.conn-wrap { position:relative; margin-left:auto; }
#connection { color:var(--green); padding:.1rem .3rem; white-space:nowrap; cursor:pointer; border-radius:4px; user-select:none; }
#connection.disconnected { color:#ffffff; background:var(--red); border-radius:4px; }
#connection:focus-visible { outline:2px solid var(--green); outline-offset:1px; }
.conn-wrap.open #connection:not(.disconnected) { background:var(--hover-tint); }
.refresh-pop { position:absolute; top:100%; right:0; z-index:20; margin-top:.2rem; padding:.35rem .5rem; background:var(--bg); border:1px solid var(--border); border-radius:6px; box-shadow:var(--popover-shadow); display:flex; align-items:center; gap:.4rem; white-space:nowrap; color:var(--text); opacity:0; visibility:hidden; transform:translateY(-3px); transition:opacity .12s ease, transform .12s ease, visibility .12s; }
.refresh-pop .cap { color:var(--dim); font-size:.8rem; }
.refresh-pop input { width:4.5rem; text-align:right; }
.conn-wrap.open .refresh-pop { opacity:1; visibility:visible; transform:none; }
.report-status { margin:.35rem 0 0; padding:.25rem .45rem; border-left:3px solid var(--amber); background:var(--status-amber-bg); color:var(--status-amber-text); }
.report-status[hidden] { display:none; }
/* Where the pointer can hover, opening on hover is layered on top of the
tap-toggle; a transparent bridge spans the gap so crossing to the panel
does not dismiss it. */
@media (hover:hover) and (pointer:fine) {
.refresh-pop::before { content:""; position:absolute; left:0; right:0; top:-.4rem; height:.4rem; }
.conn-wrap:hover #connection:not(.disconnected) { background:var(--hover-tint); }
.conn-wrap:hover .refresh-pop, .refresh-pop:hover { opacity:1; visibility:visible; transform:none; }
}
main { width:min(1200px,100%); margin:auto; padding:.5rem clamp(.5rem,1.5vw,1rem) 2rem; }
main:has(.grid.leaderboard) { width:min(1600px,100%); }
.report-meta { display:flex; flex-wrap:wrap; gap:.2rem .6rem; align-items:baseline; margin:.2rem 0 .35rem; }
h1,h2,h3 { margin:.4rem 0 .25rem; }
h1 { font-size:1rem; display:inline; }
h2 { font-size:.95rem; }
h3 { font-size:.9rem; margin:0; }
.dim, .empty { color:var(--dim); }
.error { border-left:4px solid var(--red); padding:.4rem .6rem; background:var(--status-red-bg); }
.source-error-banner { margin-bottom:.35rem; }
.metrics { margin:.3rem 0; gap:.15rem 1rem; }
.metric { display:inline-flex; gap:.35rem; align-items:baseline; min-width:0; flex:0 1 auto; }
.metric strong { overflow-wrap:anywhere; }
.grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(min(100%,15rem),1fr)); gap:.4rem; }
.grid.workers { grid-template-columns:repeat(auto-fill,minmax(min(100%,12.5rem),1fr)); }
.grid.leaderboard { grid-template-columns:minmax(0,1fr); gap:.65rem; }
.card, .section { min-width:0; background:var(--panel); border:1px solid var(--border); border-radius:6px; padding:.4rem .55rem; overflow-wrap:anywhere; }
.section { margin:.45rem 0; }
/* Two sections that each use little horizontal space, shown side by
side at every width, phones included. Both halves stretch to the
taller one's height, so the row has one top and one bottom edge
rather than a ragged pair. A spine too wide for its half stacks its
guesses into a column (layoutSpines) rather than overflowing. */
.section-pair { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:0 .45rem; }
.card.active, .card.filtered { border-color:var(--green); }
.card.filtered { background:var(--hover-tint); }
.card.recently-completed { border:3px solid var(--blue); background:var(--completed-bg); }
.card.finalizing, .stale { border-color:var(--amber); }
.card.transitioning { border-color:var(--dim); }
.dead { border-color:var(--red); }
.card-title { display:flex; flex-wrap:wrap; gap:.35rem; align-items:baseline; }
.worker .card-title { gap:.2rem; }
/* Each item (name, state chip, candidate tiles) wraps to its own line as a
whole when the row doesn't fit -- never clipped, never split. overflow-wrap
normally lets a nowrap span break mid-word to avoid overflow; .card sets it
to "anywhere" for long unrelated content, so it must be countered here or
that inherited rule breaks these items internally instead of wrapping the row. */
.worker .card-title > * { flex:0 0 auto; white-space:nowrap; overflow-wrap:normal; }
.chip { display:inline-block; border:1px solid var(--border); border-radius:999px; padding:.05rem .4rem; color:var(--dim); font-size:.85em; }
.chip.exact, .outcome-exact { border-color:var(--green); color:var(--chip-exact-text); }
.chip.cut, .outcome-cut { border-color:var(--amber); color:var(--chip-cut-text); }
.chip.loss, .outcome-loss { border-color:var(--red); color:var(--chip-loss-text); }
.chip.historical { border-color:var(--dim); color:var(--dim); background:var(--bg); }
.card.historical { border-style:dashed; background:var(--card-historical-bg); }
/* A spine is one row of guesses or a column of them, never a ragged mix:
it lays out on a single row, and layoutSpines drops the whole spine to a
column when that row will not fit. Guesses are separated by well more
than the gap between letters, so a row reads as distinct words. */
.tiles { display:flex; flex-wrap:nowrap; overflow:hidden; gap:.3rem 1rem; align-items:center; margin:.2rem 0; }
.tiles.stacked { flex-direction:column; align-items:flex-start; overflow:visible; }
.step-group { display:inline-flex; gap:.3rem; align-items:center; white-space:nowrap; }
/* A set of words rather than a spine: their order carries no meaning, so
the row wraps into as many lines as it needs instead of dropping to a
column whole the way a spine does. Its entries are punctuated as a list
-- a gap alone is how a spine separates its guesses, and a set of
unrelated words must not read as a line of play. Aligned on the
baseline the tiles carry, so the punctuation sits on the letters' line
rather than centred against the tile boxes. */
.word-list { display:flex; flex-wrap:wrap; gap:.3rem .6rem; align-items:baseline; }
/* A guess is drawn as its five letters over the colors of its response:
one square tile per letter, no corner radius, gap and letter size both
proportional to the tile. Sizes are held on whole pixels -- a fractional
tile height puts the centered line box on a fraction and the glyph then
snaps up to a pixel off center. */
:root { --tile-base:15px; --tile-gap-ratio:.07; --tile-font-ratio:.62; --tile-outline-ratio:.023; --tile-notch-ratio:.38; }
.word-sm { --tile:var(--tile-base); }
.word-md { --tile:20px; --tile:round(calc(var(--tile-base) * 1.3),1px); }
.word-lg { --tile:27px; --tile:round(calc(var(--tile-base) * 1.8),1px); }
/* Nothing inside a word is a flex or grid item: those are blockified, and a
block serializes with a line break, which would make a copied word arrive
as one letter per line. font-size:0 on the row keeps any whitespace
between tiles from opening a gap of its own. */
.word { display:inline-block; white-space:nowrap; font-size:0; --tile-notch-inset:max(1px,calc(var(--tile) * .07)); }
/* No vertical-align: the tile's single line box fills its height, so the
letters carry a real text baseline and the row inherits it. Default
baseline alignment then seats the tile letters on the baseline of the
text beside them at every scale. padding-top carries the centering
correction measured in centerLetters -- it moves the glyph without
moving the tile behind it. */
.word > .letter { position:relative; display:inline-block; text-align:center; width:var(--tile); height:var(--tile); line-height:var(--tile); padding-top:var(--letter-shift,0px); margin-right:calc(var(--tile) * var(--tile-gap-ratio)); font-family:"Helvetica Neue",Helvetica,Arial,sans-serif; font-size:calc(var(--tile) * var(--tile-font-ratio)); font-weight:700; color:#ffffff; background:var(--gray); text-transform:uppercase; }
.word > .letter:nth-child(5) { margin-right:0; }
.word > .letter.g { background:var(--green); } .word > .letter.y { background:var(--yellow); }
/* A guess with no response is the unplayed tile: page-background fill, gray
outline, page-foreground letters. The outline is inset so the tile keeps
the same outer box as a colored one and rows of both sit on a shared grid. */
.word > .letter.blank { background:var(--bg); color:var(--text); box-shadow:inset 0 0 0 max(1px,calc(var(--tile) * var(--tile-outline-ratio))) var(--tile-blank-outline); }
.tile-button { border:0; padding:0; background:transparent; line-height:0; }
.tile-button:focus-visible { outline:2px solid var(--blue); outline-offset:2px; }
/* A guess that is itself a possible answer is notched at the corner of its
last tile. currentColor is already the tile's letter color, so one rule
covers every tone. The notch is held off the corner: flush to the edge,
a white notch on a colored tile merges with the page behind it and reads
as a bite out of the tile rather than a mark on it. */
.word.is-answer > .letter:nth-child(5)::after { content:""; position:absolute; top:var(--tile-notch-inset); right:var(--tile-notch-inset); border-top:calc(var(--tile) * var(--tile-notch-ratio)) solid currentColor; border-left:calc(var(--tile) * var(--tile-notch-ratio)) solid transparent; }
/* A word and the ERD it earned are one unit: the tiles butt against the
slash, and the pair never breaks across a line. */
.word-erd { white-space:normal; }
.word-erd > .word-erd-pair { white-space:nowrap; }
/* No child of this card is ever meant to reach past its edge -- the same
guarantee body makes for the page as a whole above -- so this is a
standing invariant of the card, not insurance against one specific
piece of content. */
.leaderboard-card { padding:.65rem .75rem; overflow-x:hidden; }
.leaderboard-card .card-title { font-size:1.05rem; gap:.55rem; }
.leaderboard-rank { color:var(--dim); }
.response-visual-key { display:flex; flex-wrap:wrap; align-items:center; gap:.35rem .45rem; margin:.35rem 0 .45rem; font-size:.8rem; color:var(--dim); }
.response-color-gradient { flex:0 1 10rem; min-width:5rem; height:.55rem; border-radius:999px; background:linear-gradient(90deg,hsl(320 70% 42%),hsl(0 62% 43%),hsl(62 62% 43%),hsl(125 62% 43%),hsl(210 62% 43%)); }
.response-visual-label { margin:.4rem 0 .15rem; color:var(--dim); font-size:.8rem; }
.response-group-breakdown { margin:.5rem 0 1rem; }
.answer-strip { display:flex; width:100%; height:2.25rem; overflow:hidden; border:1px solid var(--border); border-radius:4px; background:var(--border); }
.answer-segment { display:flex; align-items:center; justify-content:center; min-width:0; overflow:hidden; color:#ffffff; font-size:.72rem; font-weight:700; text-shadow:0 1px 2px rgba(0,0,0,.65); box-shadow:inset -1px 0 rgba(255,255,255,.5); }
.answer-segment-label, .response-count-segment-label { display:block; text-align:center; line-height:.9rem; white-space:nowrap; }
.answer-segment:last-child { box-shadow:none; }
.answer-segment.solved-group { box-shadow:inset 0 0 0 2px #000000; }
.answer-strip[data-selectable] .answer-segment { cursor:pointer; }
.answer-strip[data-selectable] .answer-segment:hover { filter:brightness(1.2); }
.answer-segment:focus-visible { outline:2px solid var(--text); outline-offset:-2px; }
.group-menu { position:absolute; z-index:30; min-width:11rem; max-width:min(20rem,calc(100vw - 1rem)); padding:.4rem; background:var(--bg); border:1px solid var(--border); border-radius:6px; box-shadow:var(--popover-shadow); color:var(--text); }
.group-menu-title { display:flex; flex-wrap:wrap; align-items:center; gap:.35rem; padding:.1rem .15rem .35rem; border-bottom:1px solid var(--border); }
.group-menu-facts { color:var(--dim); font-size:.78rem; }
.group-menu button { display:block; width:100%; margin-top:.3rem; text-align:left; border:0; background:transparent; }
.group-menu button:hover, .group-menu button:focus-visible { background:var(--hover-tint); }
.response-group-bridge { position:relative; z-index:2; display:block; width:100%; height:3rem; margin-bottom:-8px; overflow:visible; pointer-events:none; }
.response-count-track { position:relative; z-index:1; display:flex; justify-content:center; width:100%; height:1.6rem; }
.response-count-fill { display:flex; height:100%; overflow:hidden; border:1px solid var(--border); border-radius:4px; }
.response-count-segment { display:flex; align-items:center; justify-content:center; min-width:0; overflow:hidden; color:#ffffff; font-size:.68rem; font-weight:700; text-shadow:0 1px 2px rgba(0,0,0,.65); box-shadow:inset -1px 0 rgba(255,255,255,.5); }
.response-count-segment-label { flex:0 0 auto; line-height:.62rem; }
.response-count-segment:last-child { box-shadow:none; }
/* Plain grid flow: every label stays in normal document flow, so none
can overlap another regardless of the card's width. */
.response-bucket-legend { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:.2rem .55rem; margin-top:.4rem; color:var(--dim); font-size:.72rem; }
.response-bucket-legend > span::before { content:""; display:inline-block; width:.55rem; height:.55rem; margin-right:.16rem; border-radius:1px; vertical-align:-.08rem; background:var(--bucket-color); }
.leaderboard-worst-case { margin-top:.15rem; font-size:.8rem; }
.progress-line { margin:.25rem 0; }
.progress { height:.3rem; border-radius:999px; background:var(--border); overflow:hidden; }
.progress > span { display:block; height:100%; background:var(--green); }
.source-group-progress { display:flex; }
.source-group-progress > span { flex:0 0 auto; }
.progress > span.no-work { background:var(--green-complete); }
.progress > span.work-boundary { border-right:1px solid var(--text); }
.source-word .stat-line > span:first-child { white-space:normal; min-width:0; overflow-wrap:anywhere; }
/* Facts pack onto a wrapping row separated by a drawn middot rather than
literal " · " text, at a smaller size than the panel's identity line.
Each fact is its own nowrap span, so a number never breaks mid-digit and
"best CRANE*" never splits from its value. */
.stat-line { display:flex; flex-wrap:wrap; font-size:.8rem; margin-top:.15rem; }
/* The same packing inline, where facts follow an identity on its own line
instead of starting a row of their own. The flex container is what
creates the break opportunities between facts: adjacent nowrap spans
with no text node between them are one unbreakable inline box. */
.inline-facts { display:inline-flex; flex-wrap:wrap; margin-left:.35rem; }
.stat-line > span, .inline-facts > span { white-space:nowrap; }
.stat-line > span:not(:last-child)::after, .inline-facts > span:not(:last-child)::after { content:"·"; color:var(--border); margin:0 .3em; }
.sweep { display:flex; gap:1px; height:1.25rem; margin:.3rem 0; position:relative; }
.progress-line .sweep { height:1rem; margin:0 0 .3rem; }
.sweep-cell { flex:1 1 0; min-width:2px; border-radius:1px; background:linear-gradient(to top,var(--green) var(--fill,0%),var(--sweep-empty) var(--fill,0%)); }
/* A fully-done cell is drawn desaturated so "completely full" reads as a
distinct state from a nearly-full cell rather than blending with it. */
.sweep-cell.complete { background:var(--green-complete); }
/* The digit is an SVG background image, not laid-out text: SVG
rasterization places the glyph geometrically, so the digit stays
centered at any sub-pixel cell position where HTML text layout would
snap the baseline to a whole pixel and drift up to a pixel off center.
min-width keeps a marker at least a digit wide when cells are only a few
pixels. The marker has no fill of its own — the digit carries a light
halo (drawn in the SVG) so it reads over both green and gray while the
cell's own fill stays visible straight through it. */
.sweep-marker { position:absolute; top:0; height:100%; min-width:.85rem; z-index:1; transition:left .4s ease, opacity .4s ease; }
/* The pointer says where the worker is and never moves off its candidate;
the digit says which worker it is and may slide to clear a neighbour, so
the two are separate boxes. --digit-shift is the only thing that moves. */
.sweep-digit { position:absolute; top:0; height:100%; width:.85rem; left:50%; transform:translateX(calc(-50% + var(--digit-shift,0px))); background-position:center; background-repeat:no-repeat; transition:transform .4s ease; }
/* A small solid pointer in the strip of white space under the ramp, apex
almost touching the worker's cell. It is part of the marker, so it
rides the same slide and fade as the digit. */
.sweep-marker::after { content:""; position:absolute; top:calc(100% + 1px); left:50%; transform:translateX(-50%); width:0; height:0; border-left:.2rem solid transparent; border-right:.2rem solid transparent; border-bottom:.26rem solid var(--text); }
/* A worker between bundles holds no claim to point at, so its position is
an area rather than a point: the pointer becomes a bar as wide as the
marker. The digit keeps full strength -- which worker it is was never
the uncertain part. Behind precise markers in the stack, so a worker
whose position is known is never hidden by one whose is not. */
.sweep-marker.last-reported { z-index:0; }
.sweep-marker.last-reported::after { left:0; transform:none; width:100%; height:.16rem; border:0; border-radius:1px; background:var(--dim); }
.labeled-facts { display:flex; flex-wrap:wrap; gap:.05rem .9rem; }
.labeled-facts .fact { display:inline-block; min-width:0; overflow-wrap:anywhere; }
.labeled-facts .fact-label { color:var(--dim); }
/* The base words sit flush at the page margin; a rail is drawn only where
it separates siblings from the guess they branch off. */
.tree { list-style:none; margin:0; padding:0; }
.tree ul { list-style:none; margin:.2rem 0 .2rem .5rem; padding-left:.6rem; border-left:1px solid var(--border); }
/* Response branches are siblings under their played word. They must align
with one another: an inset would falsely suggest one response follows
from the preceding response. */
.tree ul.patterns { margin:.2rem 0; padding:0; border-left:none; }
.tree summary { cursor:pointer; min-height:28px; padding:.15rem 0; }
.tree-pager { display:flex; flex-wrap:wrap; gap:.4rem; align-items:center; margin:.45rem 0; }
.clickable { cursor:pointer; }
.clickable:hover { border-color:var(--green); }
.badge { background:var(--red); color:white; border-radius:4px; padding:.1rem .35rem; }
.flash-added { animation:added 1.5s; } .flash-improved { animation:improved 1.5s; } .flash-changed { animation:changed 1.5s; }
@keyframes added { from { box-shadow:0 0 0 3px var(--green); } }
@keyframes improved { from { border-color:var(--green); background:var(--flash-improved-bg); } }
@keyframes changed { from { border-color:var(--red); background:var(--flash-changed-bg); } }
@media (max-width:600px), (hover:none) and (pointer:coarse) {
header { position:static; }
}
@media (max-width:600px) {
.answer-segment, .response-count-segment { font-size:0; }
.answer-segment[data-answer-count]::after { content:attr(data-answer-count); font-size:.66rem; }
.response-count-segment[data-response-group-count]::after { content:attr(data-response-group-count); font-size:.66rem; }
}
</style>
</head>
<body>
<header>
<div class="nav" id="report-nav">
<button data-kind="auto" data-overview="1">Overview</button><button data-kind="queue">Queue</button><button data-kind="workers">Workers</button><button data-kind="cache">Cache</button><button data-kind="hotspots">Hotspots</button><button data-kind="work_distribution">Distribution</button><button data-kind="leaderboard">Leaderboard</button><button data-kind="openers">Openers</button><span class="layout-toggle" id="layout-toggle" role="group" aria-label="View layout"><span class="cap">View as</span><span class="seg"><button id="layout-flat" aria-pressed="true">Flat</button><button id="layout-tree" aria-pressed="false">Tree</button></span></span>
<span class="conn-wrap">
<span id="connection" aria-label="Poll status; opens refresh interval">●</span>
<div class="refresh-pop">
<span class="cap">Refresh every</span>
<input id="poll" type="number" min="200" aria-label="Refresh interval (ms)">
<span class="cap">ms</span>
</div>
</span>
</div>
<div class="branch-target">
<input id="branch-target-input" placeholder="Spine or @branch" aria-label="Spine or @branch" autocomplete="off" spellcheck="false">
<button id="apply">Go</button><button id="back">Back</button>
</div>
<details class="filters"><summary>Filters & view</summary>
<div class="control-group" id="filters-group">
<div class="group-head"><span class="gname">Filters:</span><span class="ghint">narrow what's listed — applied as you change them</span></div>
<div class="status-line" id="opener-state-filters"><span class="label">Opener state</span><span class="statuses" id="source-states"></span></div>
<div id="branch-filters">
<div id="branch-status-filters">
<div class="status-line"><span class="label">Branch status</span><span class="statuses" id="branch-statuses"></span></div>
<div class="status-line"><span class="label">Branch worker</span><span class="statuses" id="branch-worker-statuses"></span></div>
<div class="dim lifecycle-legend">Status: unqueued → queued → evaluating → finalizing → done. Worker: active or waiting (evaluating/finalizing only).</div>
</div>
<div class="field-flow">
<label class="field">Min answers<input id="minimum-answer-count" type="number"></label>
<label class="field">Max answers<input id="maximum-answer-count" type="number"></label>
<label class="field" id="budget-field">Budget<input id="budget" class="narrow" type="number"></label>
<label class="field" id="priority-field">Priority<input id="priority" class="medium" type="number"></label>
</div>
</div>
</div>
<div class="control-group" id="view-group">
<div class="group-head"><span class="gname">View</span><span class="ghint">order & scope what's shown</span></div>
<div class="field-flow">
<label class="field" id="sort-field"><span class="fieldlabel">Sort</span><select id="sort"></select></label>
<label class="field" id="group-by-field"><span class="fieldlabel">Group by</span><select id="group-by"></select></label>
<label class="field" id="limit-field"><span id="limit-label">Branches shown</span><input id="limit" type="number" min="1"></label>
<label class="field" id="by-field"><span class="fieldlabel">Hotspot field</span><select id="by"><option value="">nodes</option><option>age</option><option>size</option><option>workers</option><option>priority</option><option>slowest</option><option>evaluated-candidates</option><option>one-level-erd-prunes</option><option>two-level-erd-prunes</option><option>cut-reuse</option><option>coordination</option></select></label>
<label class="field" id="epoch-field">Epoch<input id="epoch" class="narrow" type="number"></label>
<label class="field" id="since-seconds-field"><span class="fieldlabel">Stats window (s)</span><input id="since-seconds" type="number" min="1" title="time window for hotspot aggregation"></label>
</div>
</div>
</details>
<p id="report-status" class="report-status" role="status" aria-live="polite" hidden></p>
</header>
<main id="report"><p class="empty">Loading report…</p></main>
<script>
(() => {
"use strict";
const SCHEMA_VERSION=3, DEFAULT_POLL=2000, STUCK_REQUEST_MILLIS=60000;
const branchStatusNames=["unqueued","queued","evaluating","finalizing","done"];
const branchWorkerStatusNames=["active","waiting"];
// The overview answers what the swarm is doing right now, so it offers
// and opens on the two stages a branch is worked in. Both carry a worker
// status, so neither filter can hide what the other selects.
const overviewBranchStatusNames=["evaluating","finalizing"];
const overviewBranchWorkerStatusNames=["active"];
// A source word's lifecycle, which is not a branch's: queued until a
// worker picks one of its requests up, complete once every request is.
const sourceStateNames=["queued","active","complete"];
// iOS Safari's native <select> picker ignores the "hidden" attribute on
// <option> elements, so context-dependent choices are rebuilt into the
// DOM rather than toggled — an absent option can't appear in any picker.
const SORT_OPTIONS_DEFAULT=[["","worked first, then priority (default)"],["age","age"],["size","# of answers"],["workers","workers"],["priority","priority"],["nodes","nodes"],["slowest","slowest"]];
// A held completion is added after the server has ordered its rows, so it
// carries no place in that order. These are the primary key of each server
// sort, and the sort below is stable: rows the server ordered keep its order
// within a tie, and only the held rows move into place among them.
const OVERVIEW_SORT_KEYS={age:row=>row.created_at??0,size:row=>-(row.answer_count??-Infinity),workers:row=>-(row.worker_count??-Infinity),priority:row=>-(row.priority??-Infinity),nodes:row=>-(row.search_node_count??-Infinity),slowest:row=>-(row.search_node_count??-Infinity)};
const overviewSorted=(rows,sort)=>{const key=OVERVIEW_SORT_KEYS[sort];return key?[...rows].sort((first,second)=>key(first)-key(second)):rows;};
const SORT_OPTIONS_OVERVIEW=[["","unsorted (default)"],["age","age"],["size","# of answers"],["workers","workers"],["priority","priority"],["nodes","nodes"],["slowest","slowest"]];
const SORT_OPTIONS_WORD=[["size","# of answers (default)"],["workers","workers"],["priority","priority"]];
const SORT_OPTIONS_OPENERS=[["completed","most recently completed"],["erd","ERD (lowest first)"],["elapsed","elapsed time (longest first)"],["worker_time","total worker time (longest first)"],["priority","priority (highest to lowest)"],["requested","date requested (newest to oldest)"],["age","age since request (oldest first)"],["word","word (alphabetical)"],["branches","# of branches (highest to lowest)"],["open","# of open branches (highest to lowest)"],["done","# of completed branches (highest to lowest)"],["workers","# of workers (highest to lowest)"]];
const OPENER_ONLY_SORT_VALUES=new Set(SORT_OPTIONS_OPENERS.map(([value])=>value).filter(value=>value&&!SORT_OPTIONS_DEFAULT.some(([defaultValue])=>defaultValue===value)));
const GROUP_BY_OPTIONS_WORD=[["","none"],["status","status"],["answer_count","answer count"],["cache_state","cache state"],["worker_presence","worker"],["priority","priority"]];
const GROUP_BY_OPTIONS_OPENERS=[["state","state (default)"],["completed","completion date"],["elapsed","elapsed time"],["worker_time","total worker time"],["requested","time since request"],["worker_presence","worker"],["priority","priority"],["none","none"]];
const explicitKinds=new Set(["queue","workers","cache","hotspots","work_distribution","leaderboard","openers"]);
const treelessKinds=new Set(["cache","hotspots","work_distribution","leaderboard","openers"]);
const populationNames={current_queue_branches:"current queue branches",recent_branch_finalizations:"recent branch finalizations",recent_cut_reuse_misses:"recent cut-reuse misses",recent_claim_coordination_buckets:"recent claim coordination buckets",recent_claims_by_branch:"recent claims by branch"};
const collapsedNodes=new Set(), initializedNodes=new Set(), collapsedWordGroups=new Set(), initializedWordGroups=new Set(), collapsedResponseGroups=new Set(), stickyOrders=new Map(), packedOrders=new Map(), gridColumnCounts=new Map(), treePageHistory=new Map(), treeGroupPages=new Map();
const COMPLETED_BRANCH_HOLD_MILLIS=5000;
const recentOverviewCompletionRows=new Map();
let completionExpiryTimer=null;
let currentState, lastReport=null, lastContext=null, displayedState=null, failureCount=0, lastSuccess=null, pollTimer=null, comparisonAvailable=false,requestGeneration=0,activeRequestController=null,activeRequestStartedAt=0,shownBranchTarget=null,rootProgressOpen=true,rootProgressSort="tree_nodes",leaderboardReportWidth=null;
// The root-progress scan takes seconds, so a result is held per target and
// reused across the poll cycle's re-renders; refreshing is explicit.
const rootProgressCache=new Map(), rootProgressGeneration=new Map(), rootProgressPending=new Set(), rootProgressScroll=new Map(), rootProgressFailure=new Map();
const byId=id=>document.getElementById(id);
const element=(tag,className,text)=>{const node=document.createElement(tag);if(className)node.className=className;if(text!==undefined)node.textContent=String(text);return node;};
const formatInteger=value=>value===null||value===undefined?"—":Number(value).toLocaleString("en-US");
const valueOrDash=value=>{if(value===null||value===undefined||value==="")return "—";if(typeof value==="number"&&Number.isInteger(value))return formatInteger(value);return String(value);};
const numText=formatInteger;
const boundFields=new Set(["best_erd","erd","ceiling","bound_erd","available_bound","wanted_ceiling"]);
const ERD_LATTICE_NOISE_MARGIN=1e-6, CEILING_EPS=1e-9;
const fixed=(value,digits=3)=>value===null||value===undefined?null:Number(value).toFixed(digits);
const erdValue=(value,answerCount,{ceiling=false}={})=>{
const decimal=fixed(value);if(decimal===null||!Number.isFinite(Number(value))||!Number.isInteger(answerCount)||answerCount<=0)return decimal;
const scaled=Number(value)*answerCount,numerator=Math.round(scaled),allowance=ERD_LATTICE_NOISE_MARGIN+(ceiling?answerCount*CEILING_EPS:0);
return Math.abs(scaled-numerator)<allowance?decimal+" "+numText(numerator)+"/"+numText(answerCount):decimal;
};
const displayValue=(key,value)=>boundFields.has(key)&&typeof value==="number"?fixed(value):value;
const relativeAge=(seconds,now)=>{if(seconds===null||seconds===undefined)return null;const delta=Math.max(0,Math.round(now-seconds));if(delta<60)return delta+"s ago";if(delta<3600)return Math.floor(delta/60)+"m ago";if(delta<86400)return Math.floor(delta/3600)+"h ago";return Math.floor(delta/86400)+"d ago";};
const absoluteTime=seconds=>seconds===null||seconds===undefined?"unknown time":new Date(seconds*1000).toLocaleString("en-GB",{dateStyle:"medium",timeStyle:"medium"});
const displayTimedValue=(key,value,now)=>key.endsWith("_at")&&typeof value==="number"?relativeAge(value,now):displayValue(key,value);
const statLine=parts=>{const node=element("div","dim stat-line");for(const part of parts){if(!part)continue;const cell=element("span","");if(part instanceof Node)cell.append(part);else cell.textContent=String(part);node.append(cell);}return node;};
const label=key=>String(key).replaceAll("_"," ").replace(/\berd\b/gi,"ERD");
const timeLabel=key=>key.endsWith("_at")?label(String(key).slice(0,-3)):label(key);
const shortReference=reference=>String(reference).slice(0,8);
// Copying a selection that touches a word yields the spine language the
// branch target box parses, so a word or a run of them can be pasted
// straight back in. Without this the tiles copy as their bare letters --
// the response is carried by color, which no selection can reach -- and a
// spine arrives one guess per line, since each guess is a block.
function spineTextFromSelection(range){
const fragment=range.cloneContents();
const words=[...fragment.querySelectorAll("[data-spine]")];
if(!words.length){
// A selection inside one word still yields that whole word: the spine
// language cannot express half a guess.
const container=range.commonAncestorContainer;
const host=container.nodeType===1?container:container.parentElement;
const enclosing=host&&host.closest("[data-spine]");
return enclosing?enclosing.dataset.spine:null;
}
// Whether two words abut is decided before any replacement: replacing a
// word turns it into a text node, which would hide it from the next
// word's sibling check and run the two tokens together.
// Anything selected besides the words themselves is prose, and prose has
// structure -- line breaks from block layout, middots from generated
// content -- that textContent cannot carry. Leave those to the browser.
const probe=fragment.cloneNode(true);
for(const word of probe.querySelectorAll("[data-spine]"))word.remove();
if(probe.textContent.trim()!=="")return null;
const plans=words.map(word=>{
const previous=word.previousSibling;
return [word,!!previous&&previous.nodeType===1&&previous.hasAttribute("data-spine")];
});
for(const [word,abuts] of plans)word.replaceWith(document.createTextNode((abuts?" ":"")+word.dataset.spine));
return fragment.textContent.replace(/\s+/g," ").trim();
}
function installSpineCopy(){
document.addEventListener("copy",event=>{
const selection=getSelection();
if(!selection||!selection.rangeCount||selection.isCollapsed)return;
const text=spineTextFromSelection(selection.getRangeAt(0));
// A selection touching no word copies natively, untouched.
if(text===null||!event.clipboardData)return;
event.clipboardData.setData("text/plain",text);
event.preventDefault();
});
}
function copyText(text){
const fallback=()=>{const area=document.createElement("textarea");area.value=text;area.setAttribute("readonly","");area.style.cssText="position:fixed;left:-9999px;top:0;opacity:0";document.body.append(area);area.select();area.setSelectionRange(0,area.value.length);const copied=document.execCommand("copy");area.remove();return copied;};
if(!navigator.clipboard?.writeText)return Promise.resolve(fallback());
return navigator.clipboard.writeText(text).then(()=>true,()=>fallback());
}
const workerName=worker=>{const number=String(worker.worker_number??String(worker.worker_id).split("-").pop());return /^[0-9]+$/.test(number)?"w"+number:String(worker.worker_id);};
const bool=value=>value==="1"||value==="true";
const intOrNull=value=>{if(value===null||value===""||value===undefined)return null;const parsed=Number.parseInt(value,10);return Number.isFinite(parsed)?parsed:null;};
// A completed branch is held to explain why it left, so the hold applies
// to any overview filter that was showing branches able to finish under
// it: a stage a worker works in, and a worker filter a worked branch meets.
const overviewHoldsCompletions=state=>(!state.branch_status.length||state.branch_status.some(value=>overviewBranchStatusNames.includes(value)))&&(!state.branch_worker_status.length||state.branch_worker_status.includes("active"));
const branchValues=(value,allowed)=>value===undefined?undefined:[...(value||[])].filter(item=>allowed.includes(item));
// A branch target naming a word: an odd number of spine tokens ends in a
// guess with no response, and a reference never names a word.
const isWordTarget=branchTarget=>String(branchTarget||"").trim().split(/\s+/).filter(Boolean).length%2===1&&!String(branchTarget||"").startsWith("@");
const isInferredWordState=(kind,branchTarget)=>kind==="auto"&&isWordTarget(branchTarget);
const isOverviewState=(kind,branchTarget,tree)=>kind==="auto"&&String(branchTarget||"").trim()===""&&!tree;
function normalizeState(state){
const normalized={kind:explicitKinds.has(state.kind)?state.kind:"auto",branch_target:(state.branch_target||"").trim(),tree:!!state.tree,branch_status:branchValues(state.branch_status,branchStatusNames),branch_worker_status:branchValues(state.branch_worker_status,branchWorkerStatusNames),opener_state:branchValues(state.opener_state,sourceStateNames)||[],opener_offset:intOrNull(state.opener_offset),branch_row_offset:intOrNull(state.branch_row_offset),minimum_answer_count:intOrNull(state.minimum_answer_count),maximum_answer_count:intOrNull(state.maximum_answer_count),budget:intOrNull(state.budget),priority:intOrNull(state.priority),sort:state.sort||"",group_by:state.group_by||"",limit:intOrNull(state.limit),by:state.by||"",epoch:intOrNull(state.epoch),since_seconds:intOrNull(state.since_seconds),sample_size:intOrNull(state.sample_size),poll:Math.max(200,intOrNull(state.poll)||DEFAULT_POLL),answers:!!state.answers,claims:!!state.claims,worker_id:state.worker_id||null,finalization_cursor:String(state.finalization_cursor||""),tree_cursor:state.tree_cursor||null};
const overviewState=normalized.kind==="auto"&&normalized.branch_target===""&&!normalized.tree;
if(normalized.branch_status===undefined)normalized.branch_status=overviewState?[...overviewBranchStatusNames]:[];
if(normalized.branch_worker_status===undefined)normalized.branch_worker_status=overviewState?[...overviewBranchWorkerStatusNames]:[];
if(overviewState)normalized.branch_status=normalized.branch_status.filter(value=>overviewBranchStatusNames.includes(value));
if(normalized.opener_state===undefined)normalized.opener_state=[];
if(normalized.kind!=="openers")normalized.opener_state=[];
if(normalized.kind!=="openers"&&OPENER_ONLY_SORT_VALUES.has(normalized.sort))normalized.sort="";
// Paging is meaningless without a page size, and only this report pages.
if(normalized.kind!=="openers"||normalized.limit===null||!normalized.opener_offset)normalized.opener_offset=null;
if(normalized.kind!=="openers"||normalized.limit===null||!normalized.branch_row_offset)normalized.branch_row_offset=null;
if(treelessKinds.has(normalized.kind))normalized.tree=false;
if(normalized.tree&&normalized.limit!==null&&![10,25,50,100].includes(normalized.limit))normalized.limit=10;
if(normalized.kind==="cache"){normalized.branch_status=[];normalized.branch_worker_status=[];normalized.minimum_answer_count=null;normalized.maximum_answer_count=null;normalized.priority=null;normalized.sort="";}
if(normalized.kind==="leaderboard"){normalized.branch_status=[];normalized.branch_worker_status=[];normalized.branch_target="";normalized.claims=false;normalized.answers=false;}
// The sources report reads only the source word and the row limit; every
// branch filter is meaningless against a membership row. A target that
// names no word is dropped, and one that reaches a word through a spine
// keeps only that word: the report reads the trailing word alone, so a
// displayed spine prefix would promise a narrower answer than it gives.
if(normalized.kind==="openers"){normalized.branch_status=[];normalized.branch_worker_status=[];normalized.minimum_answer_count=null;normalized.maximum_answer_count=null;normalized.budget=null;normalized.priority=null;normalized.claims=false;normalized.answers=false;
if(!SORT_OPTIONS_OPENERS.some(([value])=>value===normalized.sort))normalized.sort="";
// Grouped by state unless asked otherwise: the states partition the
// words into what is running, what is waiting, and what is finished,
// which is the first cut an operator makes by eye anyway. "none" is
// an explicit choice rather than the absence of one.
if(!GROUP_BY_OPTIONS_OPENERS.some(([value])=>value===normalized.group_by))normalized.group_by="state";normalized.branch_target=isWordTarget(normalized.branch_target)?normalized.branch_target.split(/\s+/).filter(Boolean).pop():"";}
if(normalized.kind!=="hotspots")normalized.by="";
if(normalized.kind!=="hotspots"&&normalized.kind!=="work_distribution"){normalized.epoch=null;normalized.since_seconds=null;normalized.sample_size=null;}
// The distribution describes a whole sampled population; a filter
// narrowing it to something else is cleared here rather than sent
// and refused. The answer-count range survives because the report
// applies it, scoping the bands to one size region.
if(normalized.kind==="work_distribution"){normalized.branch_status=[];normalized.branch_worker_status=[];normalized.branch_target="";normalized.budget=null;normalized.priority=null;normalized.sort="";normalized.limit=null;normalized.answers=false;normalized.claims=false;normalized.sample_size=null;normalized.finalization_cursor="";}
if(normalized.kind==="hotspots"&&["evaluated-candidates","bulk-completed-candidates","one-level-erd-prunes","two-level-erd-prunes","cut-reuse","coordination"].includes(normalized.by)){normalized.branch_status=[];normalized.branch_worker_status=[];}
if(normalized.kind==="hotspots"&&normalized.by==="coordination")normalized.branch_target="";
if(normalized.tree){normalized.claims=false;normalized.answers=false;}
else normalized.tree_cursor=null;
if(normalized.kind==="queue"||normalized.kind==="workers"){normalized.claims=false;normalized.answers=false;}
if(normalized.kind!=="workers")normalized.worker_id=null;
if(normalized.kind==="auto"&&normalized.branch_target===""){normalized.answers=false;normalized.claims=false;}
const inferredWord=isInferredWordState(normalized.kind,normalized.branch_target);
// Only a word report derives branches from the answer list; every other
// report reads them from the queue, which holds no unqueued branch.
if(!(inferredWord&&!normalized.tree))normalized.branch_status=normalized.branch_status.filter(value=>value!=="unqueued");
if(inferredWord&&!['size','workers','priority'].includes(normalized.sort))normalized.sort="size";
if(inferredWord&&!GROUP_BY_OPTIONS_WORD.some(([value])=>value===normalized.group_by))normalized.group_by="";
if(!inferredWord&&normalized.kind!=="openers")normalized.group_by="";
return normalized;
}
function parsePageState(locationObject){
const query=new URLSearchParams(locationObject.search||"");
const parseFilter=name=>query.has(name)?(query.get(name)==="all"?[]:query.get(name).split(",")):undefined;
return normalizeState({kind:query.get("kind")||"auto",branch_target:query.get("branch_target")||"",tree:bool(query.get("tree")),branch_status:parseFilter("branch_status"),branch_worker_status:parseFilter("branch_worker_status"),opener_state:parseFilter("opener_state"),opener_offset:query.get("opener_offset"),branch_row_offset:query.get("branch_row_offset"),minimum_answer_count:query.get("minimum_answer_count"),maximum_answer_count:query.get("maximum_answer_count"),budget:query.get("budget"),priority:query.get("priority"),sort:query.get("sort"),group_by:query.get("group_by"),limit:query.get("limit"),by:query.get("by"),epoch:query.get("epoch"),since_seconds:query.get("since_seconds"),sample_size:query.get("sample_size"),poll:query.get("poll"),answers:bool(query.get("answers")),claims:bool(query.get("claims")),worker_id:query.get("worker"),finalization_cursor:query.get("finalization_cursor"),tree_cursor:query.get("tree_cursor")});
}
function stateQuery(state,includeClient=true){
const query=new URLSearchParams();
if(state.branch_target)query.set("branch_target",state.branch_target); if(state.kind!=="auto")query.set("kind",state.kind);
for(const name of ["tree","answers","claims"])if(state[name])query.set(name,"1");
const overviewState=state.kind==="auto"&&state.branch_target===""&&!state.tree;
const defaultStatuses=overviewState?overviewBranchStatusNames:[];
const defaultWorkerStatuses=overviewState?overviewBranchWorkerStatusNames:[];
const addBranchFilter=(name,values,defaults)=>{if(JSON.stringify(values)===JSON.stringify(defaults))return;query.set(name,values.length?values.join(","):"all");};
addBranchFilter("branch_status",state.branch_status,defaultStatuses);
addBranchFilter("branch_worker_status",state.branch_worker_status,defaultWorkerStatuses);
addBranchFilter("opener_state",state.opener_state,[]);
for(const name of ["minimum_answer_count","maximum_answer_count","budget","priority","sort","group_by","limit","opener_offset","branch_row_offset","by","epoch","since_seconds","sample_size"])if(state[name]!==null&&state[name]!=="")query.set(name,String(state[name]));
if(state.worker_id)query.set("worker",state.worker_id);
if(state.finalization_cursor)query.set("finalization_cursor",state.finalization_cursor);
if(state.tree_cursor)query.set("tree_cursor",state.tree_cursor);
if(includeClient&&state.poll!==DEFAULT_POLL)query.set("poll",String(state.poll));
return query;
}
function buildAPIURL(state){
// Report kinds are snake_case; their routes are hyphenated, the same
// spelling root-progress already uses.
const endpoint=state.kind==="auto"?"/api/view":"/api/view/"+state.kind.replaceAll("_","-");
const query=stateQuery(state,false); query.delete("kind");
return endpoint+(query.size?"?"+query.toString():"");
}
function contextKey(state){return buildAPIURL(state);}
function abortActiveRequest(){if(activeRequestController){activeRequestController.abort();activeRequestController=null;}}
function groupByLabel(state){const options=state.kind==="openers"?GROUP_BY_OPTIONS_OPENERS:GROUP_BY_OPTIONS_WORD;return options.find(([value])=>value===state.group_by)?.[1]||"none";}
function setReportStatus(message){const status=byId("report-status");status.hidden=!message;status.textContent=message||"";}
function pendingReportStatus(state){
if(displayedState?.kind==="openers"&&state.kind==="openers"&&displayedState.group_by!==state.group_by)return "Showing groups by "+groupByLabel(displayedState)+" while regrouping by "+groupByLabel(state)+"…";
return "Computing "+(state.kind==="openers"?"openers report":state.kind==="leaderboard"?"leaderboard":"report")+"…";
}
function setState(next,push=true){
abortActiveRequest();
const previousGroupBy=currentState?.group_by;
currentState=normalizeState(next); const query=stateQuery(currentState,true).toString();
if(currentState.group_by!==previousGroupBy)collapsedResponseGroups.clear();
const url=location.pathname+(query?"?"+query:"");
if(push)history.pushState(null,"",url);else history.replaceState(null,"",url);
syncControls(); fetchReport(); schedulePoll();
}
function syncControls(){
// Repaint the branch_target box only when the committed branch_target changed, so a
// filter commit never overwrites a spine typed but not yet sent with Go.
if(currentState.branch_target!==shownBranchTarget){byId("branch-target-input").value=currentState.branch_target;shownBranchTarget=currentState.branch_target;}
byId("poll").value=currentState.poll;
byId("layout-toggle").hidden=treelessKinds.has(currentState.kind);
byId("layout-flat").setAttribute("aria-pressed",currentState.tree?"false":"true");
byId("layout-tree").setAttribute("aria-pressed",currentState.tree?"true":"false");
for(const name of ["minimum-answer-count","maximum-answer-count","budget","priority","limit","epoch","since-seconds"]){const key=name.replaceAll("-","_");byId(name).value=currentState[key]??"";}
const kind=currentState.kind, isHotspots=kind==="hotspots", isDistribution=kind==="work_distribution", isSources=kind==="openers";
const wordReport=isInferredWordState(kind,currentState.branch_target);
const overviewReportState=isOverviewState(kind,currentState.branch_target,currentState.tree);
const sortSelect=byId("sort"),sortMode=isSources?"openers":wordReport?"word":overviewReportState?"overview":"default";
const sortOptions=isSources?SORT_OPTIONS_OPENERS:wordReport?SORT_OPTIONS_WORD:overviewReportState?SORT_OPTIONS_OVERVIEW:SORT_OPTIONS_DEFAULT;
if(sortSelect.dataset.mode!==sortMode){
sortSelect.replaceChildren(...sortOptions.map(([value,text])=>{const option=element("option","",text);option.value=value;return option;}));
sortSelect.dataset.mode=sortMode;
}
// Same rebuild for group-by: its strategies differ per report, and a
// hidden <option> still shows in iOS Safari's picker.
const groupSelect=byId("group-by"),groupMode=isSources?"openers":"word";
if(groupSelect.dataset.mode!==groupMode){
groupSelect.replaceChildren(...(isSources?GROUP_BY_OPTIONS_OPENERS:GROUP_BY_OPTIONS_WORD).map(([value,text])=>{const option=element("option","",text);option.value=value;return option;}));
groupSelect.dataset.mode=groupMode;
}
sortSelect.value=currentState.sort||(isSources?"completed":"");byId("by").value=currentState.by;groupSelect.value=currentState.group_by;
const isOverview=currentState.kind==="auto"&¤tState.branch_target===""&&!currentState.tree;
document.querySelectorAll("[data-kind]").forEach(button=>button.setAttribute("aria-current",(button.dataset.overview?isOverview:button.dataset.kind===currentState.kind)?"page":"false"));
document.querySelectorAll("[data-branch-status]").forEach(input=>{input.checked=currentState.branch_status.includes(input.value);input.parentElement.hidden=input.value==="unqueued"?!wordReport||currentState.tree:isOverview&&!overviewBranchStatusNames.includes(input.value);});
// Worker presence distinguishes only evaluating and finalizing branches,
// so a status filter selecting neither leaves these nothing to narrow.
const workerStatusApplies=!currentState.branch_status.length||currentState.branch_status.some(value=>value==="evaluating"||value==="finalizing");
document.querySelectorAll("[data-branch-worker-status]").forEach(input=>{input.checked=currentState.branch_worker_status.includes(input.value);input.disabled=!workerStatusApplies;input.parentElement.classList.toggle("inert",!workerStatusApplies);input.parentElement.title=workerStatusApplies?"":"Applies only to evaluating or finalizing branches";});
document.querySelectorAll("[data-source-state]").forEach(input=>input.checked=currentState.opener_state.includes(input.value));
const historicalHotspot=isHotspots&&["evaluated-candidates","bulk-completed-candidates","one-level-erd-prunes","two-level-erd-prunes","cut-reuse","coordination"].includes(currentState.by);
byId("filters-group").hidden=kind==="cache"||historicalHotspot;
byId("branch-filters").hidden=isSources;
// The distribution applies an answer-count range and nothing else here,
// so the filters it cannot honor are withdrawn rather than left to be
// set and silently refused.
byId("branch-status-filters").hidden=isDistribution;
byId("budget-field").hidden=byId("priority-field").hidden=isDistribution;
// A source word is filtered by its own state, never by branch status,
// worker status, answer count, budget or priority -- those describe one branch.
byId("opener-state-filters").hidden=!isSources;
byId("sort-field").hidden=kind==="cache"||isHotspots||isDistribution;
byId("group-by-field").hidden=!wordReport&&!isSources;
byId("by-field").hidden=!isHotspots;
byId("epoch-field").hidden=byId("since-seconds-field").hidden=!isHotspots&&!isDistribution;
byId("limit-label").textContent=currentState.tree?"Items per page":isSources?"Words per page":kind==="auto"?"Branches shown":"Rows shown";
byId("limit-field").hidden=currentState.tree||isDistribution;
}
function readControls(){return {...currentState,branch_target:byId("branch-target-input").value,branch_status:[...document.querySelectorAll("[data-branch-status]:checked")].map(input=>input.value),branch_worker_status:[...document.querySelectorAll("[data-branch-worker-status]:checked")].map(input=>input.value),opener_state:[...document.querySelectorAll("[data-source-state]:checked")].map(input=>input.value),minimum_answer_count:byId("minimum-answer-count").value,maximum_answer_count:byId("maximum-answer-count").value,budget:byId("budget").value,priority:byId("priority").value,sort:byId("sort").value,group_by:byId("group-by").value,limit:currentState.tree?currentState.limit:byId("limit").value,opener_offset:null,branch_row_offset:null,by:byId("by").value,epoch:byId("epoch").value,since_seconds:byId("since-seconds").value,poll:byId("poll").value,finalization_cursor:"",tree_cursor:null};}
function ordered(rows,identityName,orderName,state){
const key=contextKey(state)+"|"+orderName, incoming=rows.map(row=>String(row[identityName]));
const previous=stickyOrders.get(key)||[], present=new Set(incoming), result=previous.filter(identity=>present.has(identity));
for(const identity of incoming)if(!result.includes(identity))result.push(identity);stickyOrders.set(key,result);
const indexed=new Map(rows.map(row=>[String(row[identityName]),row]));return result.map(identity=>indexed.get(identity));
}
// Overview branches carry no meaningful order, so their grid is packed by
// column rather than flowed like words in a paragraph. A card holds its
// column, and a departure is absorbed by the cards below it in that column
// sliding straight up; only when a column would otherwise leave the grid
// taller than it needs to be does a card cross columns, moving diagonally
// into the shorter one. Row count is always the minimum the cards fit in.
function packedRows(rows,identityName,orderName,state){
const key=contextKey(state)+"|"+orderName;
const columnCount=Math.max(1,gridColumnCounts.get(key)||1);
const present=new Map(rows.map(row=>[String(row[identityName]),row]));
const stored=packedOrders.get(key);
let columns;
if(stored&&stored.columnCount===columnCount)columns=stored.columns.map(column=>column.filter(identity=>present.has(identity)));
else{
// No history, or the viewport changed how many columns fit: rebuild the
// columns from the arrangement currently on screen, which is the order
// the cards are read in.
columns=Array.from({length:columnCount},()=>[]);
const showing=stored?rowMajor(stored.columns,stored.columnCount):[];
showing.filter(identity=>present.has(identity)).forEach((identity,index)=>columns[index%columnCount].push(identity));
}
const placed=new Set(columns.flat());
const arrivals=rows.map(row=>String(row[identityName])).filter(identity=>!placed.has(identity));
const total=placed.size+arrivals.length;
// Column sizes that pack every card into the fewest rows, longest column
// first so the only empty cells fall at the end of the last row.
const target=index=>Math.floor(total/columnCount)+(index<total%columnCount?1:0);
const room=index=>target(index)-columns[index].length;
const surplus=[];
columns.forEach((column,index)=>{while(column.length>target(index))surplus.push({identity:column.pop(),from:index});});
for(const card of surplus){
let best=-1;
for(let index=0;index<columnCount;index++)if(room(index)>0&&(best<0||Math.abs(index-card.from)<Math.abs(best-card.from)))best=index;
columns[best].push(card.identity);
}
// Arrivals go to the shortest column that still has room, which fills a
// batch of them left to right, in reading order.
for(const identity of arrivals){
let best=-1;
for(let index=0;index<columnCount;index++)if(room(index)>0&&(best<0||columns[index].length<columns[best].length))best=index;
columns[best].push(identity);
}
packedOrders.set(key,{columnCount,columns});
return rowMajor(columns,columnCount).map(identity=>present.get(identity));
}
function rowMajor(columns,columnCount){
const result=[],rowCount=Math.max(0,...columns.map(column=>column.length));
for(let row=0;row<rowCount;row++)
for(let index=0;index<columnCount;index++)
if(columns[index]&&columns[index][row]!==undefined)result.push(columns[index][row]);
return result;
}
// Grids are matched across a refresh by this key, never by their position
// among the report's grids. A word report emits one grid per response group
// and a branch report's grids are each conditional, so the same position can
// hold a different grid from one refresh to the next; pairing by position
// would then compare a grid against a stranger, and every card in it would
// read as having both left and arrived. The key is the name the grid's rows
// are already ordered or packed under.
function gridElement(key,variant){
const grid=element("div","grid"+(variant?" "+variant:""));
grid.dataset.gridKey=key;
return grid;
}
// The packing needs to know how many columns the grid actually has, which
// only the laid-out page can say. Each render records it for the next one;
// a first render, or one straight after a viewport change, packs on the
// previous count and corrects itself on the following refresh.
function recordGridColumnCounts(root,state){
for(const grid of root.querySelectorAll(".grid[data-grid-key]"))
gridColumnCounts.set(contextKey(state)+"|"+grid.dataset.gridKey,
getComputedStyle(grid).gridTemplateColumns.split(" ").filter(Boolean).length);
}
function previousBy(report,collection,identity){return new Map((((report||{}).data||{})[collection]||[]).map(row=>[String(row[identity]),row]));}
function completedOverviewBranch(row){
return row.branch_status==="finalizing"||
(row.candidate_count>0&&row.completed_candidate_count>=row.candidate_count);
}
function scheduleCompletedBranchExpiry(){
clearTimeout(completionExpiryTimer);
const now=Date.now(),nextExpiry=Math.min(...[...recentOverviewCompletionRows.values()].map(entry=>entry.expires_at));
if(!Number.isFinite(nextExpiry))return;
completionExpiryTimer=setTimeout(()=>{
if(lastReport&¤tState)applyReport(lastReport,lastReport,currentState);
},Math.max(0,nextExpiry-now));
}
function overviewWithRecentCompletions(report,previous,state){
if(report.report_kind!=="overview"||!overviewHoldsCompletions(state))return report;
const now=Date.now(),context=contextKey(state),rows=report.data.branches||[],present=new Set(rows.map(row=>String(row.branch_key_hex)));
for(const [key,entry] of recentOverviewCompletionRows)if(entry.expires_at<=now||entry.context!==context||present.has(entry.identity))recentOverviewCompletionRows.delete(key);
for(const row of report.data.recently_completed_branches||[]){
const identity=String(row.branch_key_hex),key=context+"|"+identity;
if(present.has(identity))continue;
const finalizedAt=Number(row.finalized_at),generatedAt=Number(report.generated_at);
const remainingMillis=Number.isFinite(finalizedAt)&&Number.isFinite(generatedAt)
?Math.max(0,((finalizedAt+COMPLETED_BRANCH_HOLD_MILLIS/1000)-generatedAt)*1000)
:COMPLETED_BRANCH_HOLD_MILLIS;
recentOverviewCompletionRows.set(key,{context,identity,expires_at:now+remainingMillis,row});
}
for(const row of (previous?.data?.branches||[])){
const identity=String(row.branch_key_hex),key=context+"|"+identity;
if(!present.has(identity)&&completedOverviewBranch(row)&&!recentOverviewCompletionRows.has(key)){
recentOverviewCompletionRows.set(key,{context,identity,expires_at:now+COMPLETED_BRANCH_HOLD_MILLIS,row:{...row,branch_status:"done",branch_worker_status:null,recently_completed:true}});
}
}
const completedRows=[...recentOverviewCompletionRows.values()].filter(entry=>entry.context===context).map(entry=>entry.row);
scheduleCompletedBranchExpiry();
return completedRows.length?{...report,data:{...report.data,branches:[...rows,...completedRows]}}:report;
}
function semanticProjection(value){
if(Array.isArray(value))return value.map(semanticProjection);
if(value&&typeof value==="object"){const result={};for(const [key,item] of Object.entries(value))if(!["generated_at","updated_at"].includes(key))result[key]=semanticProjection(item);return result;}
return value;
}
function changeClass(row,previous){
if(!previous)return comparisonAvailable?"flash-added":"";
if((row.completed_candidate_count??0)>(previous.completed_candidate_count??0))return "flash-improved";
if(row.best_erd!==null&&row.best_erd!==undefined&&(previous.best_erd===null||previous.best_erd===undefined||row.best_erd<previous.best_erd))return "flash-improved";
if(row.cache_state==="exact"&&previous.cache_state!=="exact")return "flash-improved";
return JSON.stringify(semanticProjection(row))!==JSON.stringify(semanticProjection(previous))?"flash-changed":"";
}
function workerProjection(worker){return {worker_id:worker.worker_id,is_live:worker.is_live,branch_key_hex:worker.branch_key_hex??null,current_candidate:worker.current_candidate??null,candidate_index:worker.candidate_index??null,work_position:worker.work_position??null};}
function workerChangeClass(worker,previous){
if(!previous)return comparisonAvailable?"flash-added":"";
// Red is reserved for a worker that just went not-live — the only worker
// transition worth alarm. A branch reassignment or candidate advance is
// routine forward motion and flashes green.
if(previous.is_live&&!worker.is_live)return "flash-changed";
const current=workerProjection(worker),before=workerProjection(previous);
return JSON.stringify(current)!==JSON.stringify(before)?"flash-improved":"";
}
function metric(labelText,value){const node=element("div","metric");node.append(element("strong","",valueOrDash(value)),element("span","dim",labelText));return node;}
function formatBytes(value){if(value===null||value===undefined)return "—";for(const [size,suffix] of [[2**30,"G"],[2**20,"M"],[2**10,"K"]])if(value>=size)return (value/size).toLocaleString(undefined,{maximumFractionDigits:value/size>=100?0:1})+suffix;return value+"B";}
// A wrapping row of "label value" facts -- the labeled counterpart to
// statLine. A value may be a node as well as a string, so a fact can carry
// a rendered object rather than only text.
function labeledFacts(values){const node=element("div","labeled-facts");for(const [key,value] of values){if(value===null||value===undefined||value==="")continue;const fact=element("span","fact"),cell=element("span","");if(value instanceof Node)cell.append(value);else cell.textContent=valueOrDash(value);fact.append(element("span","fact-label",key)," ",cell);node.append(fact);}return node;}
function progress(done,total){const node=element("div","progress"),bar=element("span");bar.style.width=total?Math.min(100,100*done/total)+"%":"0";node.append(bar);return node;}
function sourceGroupProgress(row,summary){
if(!summary||!summary.response_group_count)return null;
const total=summary.response_group_count,workCount=Math.min(total,row.direct_branch_count||0);
const noWork=total-workCount,resolved=Math.min(workCount,row.direct_done_branch_count||0);
const node=element("div","progress source-group-progress");
node.title=numText(noWork)+" response groups need no work; "+numText(resolved)+" of "+numText(workCount)+" work groups completed";
if(noWork){const noWorkBar=element("span","no-work work-boundary");noWorkBar.style.width=100*noWork/total+"%";node.append(noWorkBar);}
if(resolved){const doneBar=element("span","");doneBar.style.width=100*resolved/total+"%";node.append(doneBar);}
return node;
}
// The canonical spine language, the same one the branch target box parses:
// a word, then its response, alternating, space separated. A word with no
// response contributes only itself, which is a legal trailing token.
const spineToken=(word,pattern)=>String(word||"").toUpperCase()+(pattern?" "+String(pattern).toLowerCase():"");
const spineText=steps=>(steps||[]).map(step=>spineToken(step.word,step.pattern)).join(" ");
// A guess and its response drawn as one object: the letters of the word
// over the colors of the pattern. With no pattern the tiles are blank --
// a word that was named but never played. data-spine carries the text the
// word copies as, so a selection can be pasted straight back into the
// branch target box.
function wordTiles(word,pattern,isAnswer,sizeClass="word-sm"){
const node=element("span","word "+sizeClass+(isAnswer?" is-answer":""));
node.dataset.spine=spineToken(word,pattern);
node.title=spineToken(word,pattern)+(isAnswer?" \u00b7 in the answer set":"");
const letters=String(word||"?????").toUpperCase().padEnd(5," ").slice(0,5);
const responses=pattern?String(pattern):null;
for(let index=0;index<letters.length;index++){
const character=responses?responses[index]:null;
const tone=character==="g"?"g":character==="y"?"y":responses?"":"blank";
node.append(element("span","letter "+tone,letters[index]===" "?"":letters[index]));
}
return node;
}
// The word/ERD pairing as one node: tiles for the word, text for the ERD it
// earned. The word never splits from the decimal it earned, but an ERD on
// the lattice trails a rational whose width grows with the answer count --
// "/3.131 1572/502" is wider than a card -- so that rational is allowed to
// wrap away from the pair rather than carry it off the edge.
function bestGuessCell(row,answerCount=row.answer_count,prefix=""){
if(!row.best_guess)return null;
const cell=element("span","word-erd");
if(prefix)cell.append(prefix);
const pair=element("span","word-erd-pair");
pair.append(wordTiles(row.best_guess,null,row.best_guess_is_answer));
let rational=null;
if(row.best_erd!==null&&row.best_erd!==undefined){
const [decimal,...lattice]=String(erdValue(row.best_erd,answerCount)).split(" ");
pair.append("/"+decimal);
if(lattice.length)rational=lattice.join(" ");
}
cell.append(pair);
if(rational)cell.append(" "+rational);
return cell;
}
// The browser rounds a font's ascent and descent to whole pixels and snaps
// the baseline it derives from them to a whole pixel, which can leave a
// capital up to a pixel off center in its tile -- worst at the smallest
// size. Rasterizing a few flat capitals large and scanning for their ink
// gives the baseline the tile actually wants; canvas reports its own text
// metrics rounded to whole pixels, which is far too coarse to center on.
function capitalInkRatio(fontWeight,fontFamily){
const size=600,box=1200,canvas=document.createElement("canvas");
canvas.width=canvas.height=box;
const context=canvas.getContext("2d",{willReadFrequently:true});
if(!context)return null;
context.fillStyle="#ffffff";context.fillRect(0,0,box,box);
context.fillStyle="#000000";
context.font=fontWeight+" "+size+"px "+fontFamily;
context.textBaseline="alphabetic";
const baseline=900;
context.fillText("HETIL",40,baseline);
const pixels=context.getImageData(0,0,box,box).data;
let top=null,bottom=null;
for(let y=0;y<box;y++){
let inked=false;
for(let x=0;x<box;x++)if(pixels[(y*box+x)*4]<128){inked=true;break;}
if(inked){if(top===null)top=y;bottom=y;}
}
if(top===null)return null;
return {ascent:(baseline-top)/size,descent:(bottom+1-baseline)/size};
}
let letterShiftApplied=false;
function centerLetters(){
if(letterShiftApplied)return;
const rules=[];
for(const name of ["word-sm","word-md","word-lg"]){
const sample=element("span","word "+name);sample.append(element("span","letter","H"));
sample.style.cssText="position:absolute;visibility:hidden";
document.body.append(sample);
const cell=sample.firstChild,style=getComputedStyle(cell);
const ink=capitalInkRatio(style.fontWeight,style.fontFamily);
// A canvas that reads back blank (privacy hardening) never becomes
// measurable, so the give-up latches rather than repeating the scan on
// every repaint.
if(!ink){sample.remove();letterShiftApplied=true;return;}
const tile=parseFloat(style.height),fontSize=parseFloat(style.fontSize);
const marker=element("span","");marker.style.cssText="display:inline-block;width:0;height:0";
cell.append(marker);
const currentBaseline=marker.getBoundingClientRect().top-cell.getBoundingClientRect().top;
sample.remove();
const wanted=(tile+(ink.ascent-ink.descent)*fontSize)/2;
rules.push("."+name+"{--letter-shift:"+(wanted-currentBaseline).toFixed(2)+"px}");
}
letterShiftApplied=true;
const sheet=document.createElement("style");sheet.textContent=rules.join("");
document.head.append(sheet);
}
// A spine is a single row of guesses when that row fits and a column of them
// when it does not, never some across and the rest wrapped onto a second
// row. Measured after insertion, so it re-decides on every repaint and
// whenever the viewport changes.
function layoutSpines(root){
for(const spine of root.querySelectorAll(".tiles")){
spine.classList.remove("stacked");
if(spine.scrollWidth>spine.clientWidth)spine.classList.add("stacked");
}
}
function renderSpine(spine,sizeClass="word-md"){const node=element("div","tiles");for(const step of spine||[]){node.append(wordTiles(step.word,step.pattern,step.word_is_answer,sizeClass));}return node;}
function spineFromText(text){const parts=String(text||"").trim().split(/\s+/).filter(Boolean);const steps=[];for(let i=0;i+1<parts.length;i+=2)steps.push({word:parts[i],pattern:parts[i+1]});return steps;}
// The target a report answered, drawn the way every other word in the
// report is drawn. Its steps come from the server's own parse rather than
// the text in the branch target box, so the header names what was actually
// asked for. A target that names no word -- a queue reference, or the
// root -- has nothing to draw and stays as the text it was asked as. A
// target carries no answer-set membership either, so these tiles take no
// notch; the report body draws that where it knows it.
function branchTargetLabel(report,state){
const target=report.branch_target;
const steps=[...(target&&target.steps||[])];
if(target&&target.trailing_word)steps.push({word:target.trailing_word,pattern:null});
return steps.length?renderSpine(steps,"word-sm"):element("span","dim",state.branch_target||"root");
}
function branchContextSummary(worker){
if(Array.isArray(worker.branch_context)&&worker.branch_context.length){
return renderSpine(worker.branch_context);
}
return element("span","dim",worker.branch_reference?"@"+shortReference(worker.branch_reference):"unknown branch");
}
function ownershipRow(labelText,workers,options={}){
const row=element("div","status-line");
row.append(element("span","label",labelText));
if(!workers?.length){
row.append(element("span","dim","None"));
return row;
}
const entries=element("span","statuses");
for(const worker of workers){
const entry=element("span","step-group");
const workerChip=element("button","",""+workerName(worker));
workerChip.addEventListener("click",()=>navigateWorker(worker));
entry.append(workerChip);
if(options.showBranch){
entry.append(element("span","dim","on"));
const branchNode=branchContextSummary(worker);
if(worker.branch_reference){
branchNode.classList.add("clickable");
branchNode.addEventListener("click",()=>navigateBranch(worker));
}
entry.append(branchNode);
}
entries.append(entry);
}
row.append(entries);
return row;
}
function branchClass(row){return row.is_live===false?"dead":row.branch_status==="finalizing"?"finalizing":row.branch_worker_status==="active"?"active":row.branch_status||"";}
function refreshTreeSnapshot(){
for(const details of byId("report").querySelectorAll("details[open]"))details.open=false;
treePageHistory.clear();treeGroupPages.clear();abortActiveRequest();fetchReport();
}
function activeSortLabel(state){
const wordReport=isInferredWordState(state.kind,state.branch_target);
const options=state.kind==="openers"?SORT_OPTIONS_OPENERS:wordReport?SORT_OPTIONS_WORD:isOverviewState(state.kind,state.branch_target,state.tree)?SORT_OPTIONS_OVERVIEW:SORT_OPTIONS_DEFAULT;
const value=state.sort||options[0]?.[0]||"";
return options.find(([optionValue])=>optionValue===value)?.[1]||value||"default";
}