magi-cli 0.19.0

Blind multi-agent implementation competition: N agents implement, M judges rank blind, deliberate, vote privately, winner survives double review + E2E gate
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
/* magi observation deck — the whole client.
 *
 * No framework and no build step, because magi ships as one Rust binary and
 * these three files are compiled into it with include_str!. A toolchain here
 * would mean a toolchain in `cargo install magi-cli`.
 *
 * Live updates come from the SSE stream at /api/events, which announces the
 * queue and run revisions. Timers are not the mechanism: the only interval in
 * this file re-reads /api/health, because a daemon that dies stops writing its
 * heartbeat and stops emitting revisions, so its death is only ever visible by
 * asking. Everything else reacts to `change`.
 *
 * All DOM is built with createElement and textContent. Nothing from the API is
 * ever interpolated into markup: a task instruction is arbitrary operator text
 * and a review finding is arbitrary agent text.
 */

/* ---- endpoints --------------------------------------------------------- *
 * Written out once so the frozen contract is checkable against one block. */
const API = {
  health: "/api/health",
  runs: (limit) => `/api/runs?limit=${limit}`,
  run: (id) => `/api/runs/${encodeURIComponent(id)}`,
  deleteRun: (id) => `/api/runs/${encodeURIComponent(id)}`,
  foldRun: (id) => `/api/runs/${encodeURIComponent(id)}/fold`,
  resumeRun: (id) => `/api/runs/${encodeURIComponent(id)}/resume`,
  report: (id) => `/api/runs/${encodeURIComponent(id)}/report`,
  queue: "/api/queue",
  deleteTask: (id) => `/api/queue/${encodeURIComponent(id)}`,
  hold: (id) => `/api/queue/${encodeURIComponent(id)}/hold`,
  release: (id) => `/api/queue/${encodeURIComponent(id)}/release`,
  priority: (id) => `/api/queue/${encodeURIComponent(id)}/priority`,
  editTask: (id) => `/api/queue/${encodeURIComponent(id)}/edit`,
  doneTask: (id) => `/api/queue/${encodeURIComponent(id)}/done`,
  questions: "/api/questions",
  answer: (id) => `/api/questions/${encodeURIComponent(id)}/answer`,
  questionSay: (id) => `/api/questions/${encodeURIComponent(id)}/say`,
  /* Agent-authored HTML, served by its own endpoint so it lands in a
     sandboxed frame of its own document rather than in this one. */
  /* Ends in a filename on purpose: a panel references its attachments by bare
     name, and a document served at `.../panel` would resolve `shot.png` to
     `.../shot.png`, which is not where the assets are. `base-uri 'none'`
     forbids fixing that from inside the frame, which is why it is fixed here. */
  panel: (id) => `/api/questions/${encodeURIComponent(id)}/panel/index.html`,
  talks: "/api/talks",
  talk: (id) => `/api/talks/${encodeURIComponent(id)}`,
  talkSay: (id) => `/api/talks/${encodeURIComponent(id)}/say`,
  talkPending: (id) => `/api/talks/${encodeURIComponent(id)}/pending`,
  talkPendingResume: (id) => `/api/talks/${encodeURIComponent(id)}/pending/resume`,
  talkPendingClear: (id) => `/api/talks/${encodeURIComponent(id)}/pending/clear`,
  talkPendingEdit: (id) => `/api/talks/${encodeURIComponent(id)}/pending/edit`,
  talkClose: (id) => `/api/talks/${encodeURIComponent(id)}/close`,
  talkReopen: (id) => `/api/talks/${encodeURIComponent(id)}/reopen`,
  talkDelete: (id) => `/api/talks/${encodeURIComponent(id)}`,
  /* One image, uploaded the moment it is picked/pasted/dropped - well before
     Send exists to tap - and referenced by the id this route hands back.
     `say` never carries bytes of its own. */
  talkAttachmentPost: (id) => `/api/talks/${encodeURIComponent(id)}/attachments`,
  talkAttachment: (id, att) => `/api/talks/${encodeURIComponent(id)}/attachments/${encodeURIComponent(att)}`,
  /* Local checkouts under `[repos] roots`, for the "start a conversation"
     repository picker. `?refresh=1` bypasses the server's cache regardless of
     its TTL. */
  repos: "/api/repos",
  reposRefresh: "/api/repos?refresh=1",
  /* The loop itself: GET reports it, POST {running} starts or stops the one
     inside this server. */
  loop: "/api/loop",
  upgrade: "/api/upgrade",
  events: "/api/events",
};

const RUN_LIMIT = 50;
/* The daemon's own file is refreshed every 5s and is treated as dead at 30s,
   so asking twice per staleness window is enough to never show a false
   "running" for long. */
const HEALTH_MS = 10000;
/* How long this page keeps saying "stopping" on the strength of its own
   request alone. A stop asked of an idle loop lands within one 5s poll and
   the next view reports it, so this only has to outlast that \u2014 and it
   must not be forever, or a request the server dropped would leave a strip
   promising a stop that is never coming and no control to retry with. */
const STOP_ASK_MS = 20000;
/* How long a specific announcement holds the live region against the generic
   "Updated." that follows a refresh. Long enough to cover the refresh a
   change of state triggers, short enough that the next real refresh is still
   announced. */
const QUIET_HOLD_MS = 4000;

/* Stages `health.upgrade.stage` can be while something is actually moving -
   everything between "the binary is being replaced" and "the address has
   been handed to the successor". Not `done` or `failed`: those are the two
   ways an upgrade stops moving. */
const UPGRADE_BUSY_STAGES = new Set(["downloading", "replaced", "parking", "restarting"]);
/* The ceiling on how long this page keeps quietly waiting for an upgrade to
   finish - by reconnecting on its own, or by rendering the busy stages above
   - before it says a human needs to look. A park waits for the run in flight
   to reach its next node boundary, which can take as long as
   `timeout_implement` (an hour, by default) for a run mid-implement, and that
   whole wait is meant to look like patience, not failure. The margin past an
   hour covers the download-and-replace step ahead of it and normal clock
   skew between this page and the deck. */
const UPGRADE_WAIT_LIMIT_MS = 70 * 60 * 1000;

/* ---- status vocabulary ------------------------------------------------- *
 * Every status carries a glyph as well as a colour. `stalled` additionally
 * gets a hatched, double-bordered chip in CSS: a panel that collapsed on
 * quota reached no verdict, and must never be skimmable as a `ready`. */
const PHASES = ["prep", "implementing", "judging", "deliberating", "voting", "reviewing", "gating"];

const RUN_STATUS = {
  prep:         { glyph: "\u25cc", tone: "ink" },
  implementing: { glyph: "\u25b8", tone: "blue", flight: true },
  judging:      { glyph: "\u25b8", tone: "blue", flight: true },
  deliberating: { glyph: "\u25b8", tone: "blue", flight: true },
  voting:       { glyph: "\u25b8", tone: "blue", flight: true },
  reviewing:    { glyph: "\u25b8", tone: "blue", flight: true },
  gating:       { glyph: "\u25b8", tone: "blue", flight: true },
  merged:       { glyph: "\u25c6", tone: "gold", note: "Winner merged." },
  ready:        { glyph: "\u25c7", tone: "teal", note: "Winner passed the gate. Merge was not requested." },
  /* Neither of these names a cause. A stall has several, and the run's own
     last line — shown for finished runs too — says which one it was; quota
     losses are counted separately above, from `losses`, so a note that
     assumed them contradicted the card it sat on. */
  stalled:      { glyph: "\u26a0", tone: "rust", note: "The judging panel never reached a quorum, so no verdict was recorded. The work is kept." },
  blocked:      { glyph: "\u2298", tone: "rust", note: "magi stopped short of merging." },
  failed:       { glyph: "\u2715", tone: "ink",  note: "The graph could not complete." },
  /* Derived from RunSummary.waiting rather than trusted from the status
     string: the run parked in some node and the summary still names it. */
  waiting:      { glyph: "?", tone: "wait", note: "An agent stopped to ask you something. Nothing in this run moves until it is answered." },
};

const TASK_STATUS = {
  queued:  { glyph: "\u25cc", tone: "ink" },
  running: { glyph: "\u25b8", tone: "blue", flight: true },
  done:    { glyph: "\u25c6", tone: "gold" },
  failed:  { glyph: "\u2715", tone: "rust" },
  held:    { glyph: "\u2016", tone: "rust", note: "Held. This task will not be claimed until it is released." },
};

/* An unanswered question is the only state in the product that a human, and
   only a human, can clear. `open` therefore borrows the same ringed gold as a
   waiting run, and `answered` reads as settled rather than successful \u2014 a
   decision is not a win. */
const QUESTION_STATUS = {
  open:      { glyph: "?", tone: "wait" },
  answered:  { glyph: "\u2713", tone: "teal" },
  abandoned: { glyph: "\u2296", tone: "ink" },
};

/* The standing chat only ever has two states - see `talk::TalkStatus` - so
   there is no third entry here for a filed or abandoned conversation. */
const TALK_STATUS = {
  open:   { glyph: "\u25cc", tone: "blue" },
  closed: { glyph: "\u2296", tone: "ink" },
};

/* The graph node the land loop asks its approval question from. Keyed on the
   node rather than on the summary text, and confirmed against the choice
   pair, because a routine question that happened to offer "merge" must not
   inherit the two-step guard and a real merge approval must never miss it. */
const MERGE_NODE = "land-approval";

/* Check state on the pull request the land loop is watching. `red` is
   deliberately not called a failure: the loop answers it with another fixer
   round, and the word for that is in landNote() below. Pending carries no
   glyph because CSS spins its ring \u2014 it is the one state that resolves
   without anybody doing anything. */
const CHECKS = {
  pending: { glyph: "",        word: "checks running" },
  green:   { glyph: "\u2713",  word: "checks green" },
  red:     { glyph: "\u2715",  word: "checks red" },
  unknown: { glyph: "\u2013",  word: "checks unknown" },
};

/* A pull request closed without merging is a problem; merged is the verdict
   colour; open is simply where it is. */
const PR_TONE = { open: "ink", merged: "gold", closed: "rust" };

/* Open first, then settled, newest first inside each group. The server sends
   this order already; it is applied again locally so an answer reflected
   before the next revision lands in the right place. */
const ASK_ORDER = { open: 0, answered: 1, abandoned: 2 };

const SEV_RANK = { blocker: 3, major: 2, minor: 1, nit: 0 };

/* ---- tiny DOM layer ---------------------------------------------------- */
const $ = (id) => document.getElementById(id);

function el(tag, props, ...kids) {
  const node = document.createElement(tag);
  if (props) {
    for (const [key, value] of Object.entries(props)) {
      if (value === null || value === undefined || value === false) continue;
      if (key === "class") node.className = value;
      else if (key === "text") node.textContent = value;
      else if (key.startsWith("on")) node.addEventListener(key.slice(2), value);
      else node.setAttribute(key, value === true ? "" : String(value));
    }
  }
  append(node, kids);
  return node;
}

function svg(tag, props, ...kids) {
  const node = document.createElementNS("http://www.w3.org/2000/svg", tag);
  if (props) {
    for (const [key, value] of Object.entries(props)) {
      if (value === null || value === undefined || value === false) continue;
      if (key === "text") node.textContent = value;
      else node.setAttribute(key, String(value));
    }
  }
  append(node, kids);
  return node;
}

function append(node, kids) {
  for (const kid of kids.flat(4)) {
    if (kid === null || kid === undefined || kid === false || kid === "") continue;
    node.append(kid);
  }
}

/* Writing only on change keeps an SSE refresh from invalidating layout for
   rows whose text is identical, which is what keeps the list from jumping. */
function setText(node, value) {
  const next = value === null || value === undefined ? "" : String(value);
  if (node.textContent !== next) node.textContent = next;
}

function setAttr(node, name, value) {
  if (value === null || value === undefined || value === false) {
    if (node.hasAttribute(name)) node.removeAttribute(name);
  } else if (node.getAttribute(name) !== String(value)) {
    node.setAttribute(name, String(value));
  }
}

function show(node, visible) {
  if (node.hidden === !visible) return;
  node.hidden = !visible;
}

function clear(node) {
  node.replaceChildren();
}

/* Marks every visible child but the last, so the CSS separator never leads a
   wrapped line or trails one on its own. */
function separate(container) {
  const visible = [...container.children].filter((child) => !child.hidden);
  visible.forEach((child, i) => setAttr(child, "data-sep", i < visible.length - 1 ? "1" : null));
}

/* A middot-separated row of small facts. Built here so no caller can forget
   the separators. */
function numbers(parts) {
  const row = el("div", { class: "cand-nums" }, parts.filter(Boolean).map((part) => el("span", { text: part })));
  separate(row);
  return row;
}

/* Keyed reconcile. Rows are reused by id and mutated in place, so an update
   arriving while the operator is reading does not reflow the page under their
   thumb or drop their scroll position. */
function syncList(parent, items, keyOf, create, update) {
  const existing = new Map();
  for (const child of parent.children) existing.set(child.dataset.key, child);

  let previous = null;
  for (const item of items) {
    const key = keyOf(item);
    let node = existing.get(key);
    if (node) {
      existing.delete(key);
    } else {
      node = create(item);
      node.dataset.key = key;
    }
    /* Applied to new and reused rows alike; a freshly created row is a blank
       shell until its fields are written. */
    update(node, item);
    const wanted = previous ? previous.nextSibling : parent.firstChild;
    if (node !== wanted) parent.insertBefore(node, wanted);
    previous = node;
  }
  for (const stale of existing.values()) stale.remove();
}

/* ---- formatting -------------------------------------------------------- */
const RELATIVE = new Intl.RelativeTimeFormat(undefined, { numeric: "auto" });
const ABSOLUTE = new Intl.DateTimeFormat(undefined, { dateStyle: "medium", timeStyle: "short" });
const CLOCK = new Intl.DateTimeFormat(undefined, { hour: "2-digit", minute: "2-digit", hour12: false });

function when(iso) {
  const at = Date.parse(iso);
  if (Number.isNaN(at)) return { text: "\u2014", title: "" };
  const seconds = (at - Date.now()) / 1000;
  const size = Math.abs(seconds);
  let text;
  if (size < 45) text = "just now";
  else if (size < 3600) text = RELATIVE.format(Math.round(seconds / 60), "minute");
  else if (size < 86400) text = RELATIVE.format(Math.round(seconds / 3600), "hour");
  else if (size < 6 * 86400) text = RELATIVE.format(Math.round(seconds / 86400), "day");
  else text = ABSOLUTE.format(at);
  return { text, title: ABSOLUTE.format(at) };
}

function clock(iso) {
  const at = Date.parse(iso);
  return Number.isNaN(at) ? "\u2014" : CLOCK.format(at);
}

/* Mirrors queue::short and run::short: the trailing segment of the id. */
const shortId = (id) => (typeof id === "string" && id.includes("-") ? id.split("-").pop() : id || "");

const plural = (n, one, many) => `${n} ${n === 1 ? one : many}`;

/* The one URL in this client that comes from the API rather than from this
   file. Everything else from a run record is rendered as text, which cannot
   execute; an href can, so a `javascript:` value in a run record would be a
   click away from running in the operator's session. Only the two schemes a
   forge actually serves are let through. */
function forgeUrl(value) {
  if (typeof value !== "string") return null;
  try {
    const url = new URL(value, location.origin);
    return url.protocol === "https:" || url.protocol === "http:" ? url.href : null;
  } catch {
    return null;   /* not a URL at all */
  }
}

const candTone = (index) => `var(--cand-${"abcde"[index % 5]})`;

function seconds(ms) {
  if (!ms) return null;
  return ms < 1000 ? `${ms}ms` : ms < 60000 ? `${(ms / 1000).toFixed(1)}s` : `${Math.round(ms / 60000)}m`;
}

/* ---- shared pieces ----------------------------------------------------- */
function chip(status, table) {
  const meta = table[status] || { glyph: "\u25cc", tone: "ink" };
  return el("span", {
    class: "chip",
    "data-status": status,
    "data-glyph": meta.glyph,
    "data-flight": meta.flight ? "1" : null,
    text: status,
  });
}

function toneOf(status, table) {
  return (table[status] || { tone: "ink" }).tone;
}

/* A question names the graph node it came from — `implement`, `review`,
   `gate` — while the rail is indexed by run status: `implementing`,
   `reviewing`, `gating`. The node name being the stem of its status is the
   only relationship the two vocabularies have, so it is matched as one. A
   table mapping them by hand would go stale the first time a node is added,
   and the failure would be silent: a parked run with no rail at all. */
function phaseOf(node) {
  if (!node) return null;
  return PHASES.find((phase) => phase === node || phase.startsWith(node)) || null;
}

/* Where an in-flight run has reached. The summary carries no progress field,
   so the position is derived from the status against the fixed node order.
   A parked run passes the node its question came from, so the rail still says
   how far the run got while marking that segment stopped instead of pulsing:
   the same rail cannot mean "working" and "halted" on colour alone.

   `note`, when given, is which seat(s) in the current phase have not answered
   yet — the answer to "is it agy again?" without opening the seats panel.
   It only ever touches the label: the rail's squares are one per *node*, not
   one per seat, so a seat that is still out changes what the current square
   means, not how many squares there are. */
function phaseRail(status, node, note) {
  const parked = phaseOf(node);
  const at = PHASES.indexOf(parked || status);
  if (at < 0) return null;
  const rail = el("div", {
    class: "phases",
    role: "img",
    "aria-label": parked
      ? `Stopped at phase ${at + 1} of ${PHASES.length}, ${parked}, waiting for your answer`
      : `Phase ${at + 1} of ${PHASES.length}: ${status}${note ? `  ${note}` : ""}`,
  });
  for (let i = 0; i < PHASES.length; i += 1) {
    const here = i === at;
    rail.append(el("span", {
      class: "phase",
      "data-on": parked ? (i < at ? "1" : null) : (i <= at ? "1" : null),
      "data-now": here && !parked ? "1" : null,
      "data-parked": here && parked ? "1" : null,
    }));
  }
  return rail;
}

/* How many land rounds the loop has spent of its budget. Same vocabulary as
   the phase rail, because it is the same idea: a fixed number of steps and
   the one it is on. */
function roundRail(pr) {
  const rounds = Number(pr.rounds) || 0;
  const round = Number(pr.round) || 0;
  if (rounds <= 0) return null;
  const settled = pr.state !== "open";
  const rail = el("div", {
    class: "phases",
    role: "img",
    "aria-label": `Land round ${round} of ${rounds}`,
  });
  for (let i = 1; i <= rounds; i += 1) {
    rail.append(el("span", {
      class: "phase",
      "data-round": i < round || (i === round && settled) ? "1" : null,
      "data-now": i === round && !settled ? "1" : null,
    }));
  }
  return rail;
}

/* Declared ahead of `state` below on purpose: `state`'s own initializer calls
   loadCollapsed(), which reads these — and a `const` used before its
   declaration line throws (temporal dead zone), even from inside a function,
   the moment that function actually runs. That would have been swallowed by
   loadCollapsed()'s own try/catch and silently read back `{}` every time,
   which is indistinguishable from "localStorage denied" and just as wrong. */
const RUNS_COLLAPSE_KEY = "magi-runs-sections";
const QUEUE_COLLAPSE_KEY = "magi-queue-sections";

/* ---- state ------------------------------------------------------------- */
const state = {
  route: { name: "runs", id: null },
  health: null,
  /* The last LoopView seen. Health carries one too; this is what a POST to
     /api/loop leaves behind, so the strip reflects a start or a stop before
     the next health tick. */
  loop: null,
  /* When this page's own stop request was accepted, in epoch millis, or 0.
     The server only reports `stopping` while a run is actually in flight: a
     loop asked to stop while idle answers "still running" and goes quiet a
     poll later, which without this looked like the tap had done nothing. */
  stopAskedAt: 0,
  runs: null,
  /* Which node of the Runs tree is narrowing the card list, or neither set
     when nothing is picked. Lives only in memory — reloading the page always
     starts from the unfiltered list, since a filter is a lens on what's on
     screen right now, not a saved view. */
  runsFilter: { section: null, repo: null },
  /* Which state chip is picked above the Runs list. Lives only in memory for
     the same reason runsFilter does — a reload always starts from "active"
     rather than remembering "done" was picked last, since the whole point is
     that a fresh look at the deck defaults to what still needs attention. */
  runsStateFilter: "active",
  /* Open/closed per Runs section, restored from localStorage so a collapse
     survives a reload; defaults to open (see isSectionOpen()). */
  runsCollapsed: loadCollapsed(RUNS_COLLAPSE_KEY),
  queue: null,
  /* Same idea for the Backlog's sections, kept separately since the two
     views don't share section keys or default open/closed state. */
  queueCollapsed: loadCollapsed(QUEUE_COLLAPSE_KEY),
  detail: { id: null, run: null, report: null },
  questions: null,
  /* Whether a question's panel endpoint actually answers. A sandboxed frame
     is opaque, so a 404 inside it is indistinguishable from a rendered
     panel; this is the answer to that, asked once per question. */
  panelOk: new Map(),
  talks: null,
  talkDetail: { id: null, talk: null },
  /* Images picked, pasted or dropped for the *next* `talk-say`, not yet part
     of any turn. Each item is `{ localId, previewUrl, name, status,
     serverId, mime, bytes }` with `status` one of `"uploading"` /
     `"done"` / `"error"` - see `renderTalkThumbs`. */
  talkAttachments: { id: null, items: [] },
  /* Turns in flight, keyed by conversation id. The server allows one turn
     per conversation, not one per browser surface: an entry must never stop
     an unrelated conversation from sending. `target` is the transcript
     length that proves this browser's own turn landed; reconstructed waits
     use null and are cleared after a later transcript refresh sees the
     server's claim released. */
  talkWaits: new Map(),
  talkWaitTimer: null,
  /* Whether the current view was entered via a route change to the standing
     chat. Cleared after the first scroll, so a subsequent renderTalk() with
     the same turn count does not re-scroll. */
  openingTalk: false,
  /* Turn count from the previous renderTalk() call, used to detect new turns
     arriving while the conversation is already on screen. */
  prevTalkTurnCount: 0,
  rev: { queue: null, runs: null, questions: null, talks: null, loop: null },
  streamOpen: false,
  wrap: false,
  /* The upgrade stage last rendered, so a transition into "done" can be told
     apart from just being on it already - the loop strip re-renders on every
     health poll, and only a transition is worth announcing. */
  lastUpgradeStage: null,
};

let fallbackTimer = null;
let nextTalkWaitGeneration = 1;

/* ---- transport --------------------------------------------------------- */
async function request(url, init) {
  const res = await fetch(url, init);
  if (!res.ok) {
    let message = `${res.status} ${res.statusText || "request failed"}`;
    try {
      const body = await res.json();
      if (body && typeof body.error === "string") message = body.error;
    } catch {
      /* an error body is not guaranteed to be JSON; the status stands in */
    }
    const error = new Error(message);
    error.status = res.status;
    throw error;
  }
  return res;
}

const getJson = (url) => request(url).then((r) => r.json());
const getText = (url) => request(url).then((r) => r.text());

const postJson = (url, body) =>
  request(url, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify(body === undefined ? {} : body),
  }).then((r) => r.json());

const deleteReq = (url) => request(url, { method: "DELETE" });

/* An attachment upload: the raw bytes as the body, never JSON, so a picture
   is not paid for twice over by base64. `filename` is separate from
   `file.name` because a pasted clipboard image usually has none. */
const postBytes = (url, file, filename) =>
  request(url, {
    method: "POST",
    headers: {
      "content-type": file.type || "application/octet-stream",
      "x-filename": filename || file.name || "attachment",
    },
    body: file,
  }).then((r) => r.json());

/* ---- alert ------------------------------------------------------------- */
function fail(message) {
  const box = $("alert");
  setText(box.querySelector(".alert-text"), message);
  show(box, true);
}

function ok() {
  show($("alert"), false);
}

/* When something specific was last announced. A refresh finishing says only
   "Updated.", and it was landing in the live region a fraction of a second
   after a sentence that mattered \u2014 "Loop stopped." \u2014 which for a
   screen reader means the sentence was never read at all. */
let saidAt = 0;

function announce(message) {
  saidAt = Date.now();
  setText($("live"), message);
}

/* A courtesy announcement: it is skipped rather than allowed to overwrite a
   specific one that is still being read. */
function announceQuietly(message) {
  if (Date.now() - saidAt < QUIET_HOLD_MS) return;
  setText($("live"), message);
}

/* ---- loop strip -------------------------------------------------------- *
 * The loop runs inside this server, so this strip is both the report and the
 * control. Before it was, a task filed from a phone sat in the queue until
 * somebody reached a keyboard and typed `magi serve`, and the strip's own
 * wording said so — which is the one place this product still sent its
 * operator to a terminal.
 *
 * Every branch below ends in a sentence about whether anything is going to
 * happen, because that is the question being asked, and the states differ in
 * what the answer costs: `waiting` needs a tap, `stopping` needs patience,
 * and a loop this page does not own needs neither. */

/* Tasks the loop could claim right now, or null while the queue has not
   answered yet. Counted from the queue this page already holds rather than
   from health, because "off, with two tasks waiting" is the state that has to
   be right the moment it becomes true. */
function runnableTasks() {
  if (state.queue === null) return null;
  return state.queue.filter((task) => (task.status_str || task.status) === "queued").length;
}

/* The run the loop is on, as a link when there is one to point at. `current`
   is a list — more than one entry when the loop's own concurrency (see
   `Config::daemon.max_concurrent_runs`) has more than one run going at once
   — and this always points at the first, which is what a caller wanting
   one representative run to link to means. */
function currentRunLink(daemon) {
  const id = daemon.current && daemon.current[0] && daemon.current[0].run;
  if (!id) return null;
  return el("a", {
    class: "daemon-run",
    href: `#/runs/${id}`,
    text: shortId(id),
    title: `run ${id}`,
  });
}

/* What starting the loop is about to do. Said in full next to the button
   rather than hidden behind a confirmation: starting is safe to repeat, but
   it opens an implementation competition, and an operator who did not know
   that would be surprised by the bill and not by the interface. */
function startCost(loop) {
  const mode = typeof loop.merge === "string" && loop.merge
    ? ` Merges as \u2018${loop.merge}\u2019.`
    : "";
  return `It claims the highest-priority task and runs an implementation competition, which spends agent calls.${mode}`;
}

/* Has `upgrade` been busy longer than this page is willing to wait quietly?
   See `UPGRADE_WAIT_LIMIT_MS` for why that ceiling is where it is. */
function upgradeOverdue(upgrade) {
  const startedAt = Date.parse(upgrade.started_at);
  return Number.isFinite(startedAt) && Date.now() - startedAt > UPGRADE_WAIT_LIMIT_MS;
}

/* The headline for a busy upgrade stage. Kept short: the sentence that
   actually says what is happening is `upgrade.waiting_on` or
   `upgradeStageDetail`, next to it. */
function upgradeStageLabel(stage) {
  switch (stage) {
    case "downloading": return "Replacing the binary.";
    case "replaced": return "Binary replaced.";
    case "parking": return "Parking before it restarts.";
    case "restarting": return "Restarting.";
    default: return "Upgrading.";
  }
}

/* A generic sentence for a busy stage, used when the server has nothing more
   specific to say - `upgrade.waiting_on` is preferred when it is set, which
   is only while `parking` names a run it is actually waiting on. */
function upgradeStageDetail(stage) {
  switch (stage) {
    case "downloading": return "Fetching and installing the new binary. This takes a few seconds.";
    case "replaced": return "About to hand the address to the successor.";
    case "parking": return "Nothing was in flight; handing the address to the successor next.";
    case "restarting": return "The address is released and the successor is starting. This page reconnects on its own.";
    default: return "";
  }
}

function renderLoop() {
  const box = $("daemon");
  const text = box.querySelector(".daemon-text");
  const why = $("loop-why");
  const button = $("loop-toggle");
  /* A past upgrade failure, folded into whatever note the loop's own state
     below already shows, rather than replacing it. `Stage::Failed` is
     terminal on the server and nothing clears it automatically, so taking
     the whole strip over for it - as the busy stages do, which is fine
     because those are transient - would leave start/stop/park unreachable
     from the phone until a fresh upgrade attempt happened to overwrite the
     record. Declared here, before `quiet`/`control` close over it, and
     assigned once the upgrade stage is known below. */
  let upgradeFailNote = "";

  const quiet = (note) => {
    const full = [note, upgradeFailNote].filter(Boolean).join(" ");
    setText(why, full);
    show(why, Boolean(full));
    show(button, false);
    button.onclick = null;
  };

  const park = $("loop-park");
  show(park, false);
  park.disabled = false;
  const upgradeBtn = $("loop-upgrade");
  show(upgradeBtn, false);

  /* The build answering, straight from /api/health - which is the only place
     that knows it, and until now the only place it could be read at all: an
     operator who tapped Update & restart had to curl the server to find out
     whether the new binary came back. Hidden rather than guessed while the
     first health tick is outstanding. */
  const versionChip = $("loop-version");
  const version = state.health && typeof state.health.version === "string"
    ? state.health.version.trim()
    : "";
  setText(versionChip, version ? `v${version}` : "");
  setAttr(versionChip, "title", version ? `magi ${version} is serving this page` : null);
  show(versionChip, Boolean(version));


  const control = (kind, label, note) => {
    setText(why, [note, upgradeFailNote].filter(Boolean).join(" "));
    show(why, true);
    setAttr(button, "data-kind", kind);
    setText(button, label);
    show(button, true);
    button.disabled = false;
    button.onclick = () => setLoop(kind === "start");
  };

  /* Offered only while a stop is waiting out a run, which is the moment the
     wait is actually felt. A park stops at the run's next node boundary: the
     work already recorded is kept and the run comes back as resumable, so the
     binary can be replaced without waiting out a competition and without
     throwing away an hour of paid agent calls. */
  const parkControl = (label, note) => {
    setText(park, label);
    setAttr(park, "title", note);
    show(park, true);
    park.onclick = () => setLoop(false, true);
  };

  if (!state.health) {
    setAttr(box, "data-state", null);
    setAttr(box, "data-owned", null);
    setText(text, "Connecting\u2026");
    setText(versionChip, "");
    show(versionChip, false);
    quiet(null);
    return;
  }

  /* An upgrade this deck set in motion, ahead of every other loop state:
     while the binary is being replaced or the deck is waiting to hand the
     address over, that is the one fact on screen worth reporting, and the
     states below either do not apply yet (the successor has not started, so
     `loop`/`daemon` here are still this process's own) or say nothing about
     why the deck went quiet. */
  /* Named `upgradeInfo` rather than `upgrade`: this scope also has to say
     `upgradeBtn.onclick = upgrade` further down, naming the function that
     posts `/api/upgrade` - a `const upgrade` here would shadow it for the
     rest of this function and silently turn that click handler into data. */
  const upgradeInfo = state.health.upgrade || null;
  const upgradeStage = upgradeInfo ? upgradeInfo.stage : null;

  if (upgradeStage && UPGRADE_BUSY_STAGES.has(upgradeStage)) {
    const overdue = upgradeOverdue(upgradeInfo);
    setAttr(box, "data-state", overdue ? "failed" : "upgrading");
    setAttr(box, "data-owned", null);
    clear(text);
    text.append(el("b", {
      text: overdue ? "The upgrade is taking longer than expected." : upgradeStageLabel(upgradeStage),
    }));
    quiet(overdue
      ? `Asked for ${upgradeInfo.to || "an update"} more than an hour ago and has not come back. Check on it by hand.`
      : (upgradeInfo.waiting_on || upgradeStageDetail(upgradeStage)));
    state.lastUpgradeStage = upgradeStage;
    return;
  }

  /* The transition into "done" or "failed" is what is worth announcing -
     being on either already (a fresh page load after the fact) is not news.
     `failed` does not take the strip over the way the busy stages above do:
     it is terminal on the server and nothing clears it on its own, so a
     takeover here would have permanently hidden start/stop/park behind an
     upgrade notice the operator has no way to dismiss. `upgradeFailNote`
     carries it into the loop's own note instead, below. */
  if (upgradeStage === "done" && UPGRADE_BUSY_STAGES.has(state.lastUpgradeStage)) {
    announce(`Updated to ${upgradeInfo.to || "the new build"} \u2014 back and running.`);
  }
  if (upgradeStage === "failed" && state.lastUpgradeStage !== "failed") {
    announce(`The upgrade to ${upgradeInfo.to || "a new release"} did not complete.${upgradeInfo.detail ? ` ${upgradeInfo.detail}` : ""} The loop itself is unaffected.`);
  }
  state.lastUpgradeStage = upgradeStage;
  setAttr(box, "data-upgrade-failed", upgradeStage === "failed" ? "yes" : null);
  if (upgradeStage === "failed") {
    upgradeFailNote = `The last upgrade to ${upgradeInfo.to || "a new release"} did not complete${upgradeInfo.detail ? ` (${upgradeInfo.detail})` : ""} \u2014 check on it by hand.`;
  }

  const loop = state.health.loop || state.loop || {};
  const daemon = loop.daemon || state.health.daemon || {};
  clear(text);

  /* `completed` is null until the loop has written a heartbeat, and "0 tasks
     done" is a different claim from "not reporting yet", so the count is
     omitted rather than guessed. */
  const done = Number(daemon.completed);
  const tail = Number.isFinite(done) ? ` \u00b7 ${plural(done, "task done", "tasks done")}` : "";
  /* Running at all, from either side: `loop.running` is this process's own
     flag and flips the instant a start is accepted, while `daemon.running`
     comes from the heartbeat file and lags it by up to a poll. Trusting only
     the file showed "Loop is off", with a Start button, for seconds after the
     operator had already started it. */
  const running = Boolean(loop.running) || Boolean(daemon.running);
  /* A loop somebody else's process owns. It is reported by the heartbeat
     (`daemon.running`) while this process's own flag stays false, which is
     also why `running` above is not enough to tell the two apart. */
  const foreign = Boolean(daemon.running) && loop.owned === false && !loop.running;
  setAttr(box, "data-owned", foreign ? "no" : null);

  /* Offered whenever this process owns the deck, running or not, *and* a
     newer release is actually known to exist: the binary can be replaced
     either way, and an operator with fixes waiting should not have to start
     the loop to install them. Hidden when the loop belongs to somebody else,
     because replacing this binary would leave that process running an old
     one against the same queue - and hidden with nothing to install, because
     restarting for an upgrade that would not happen used to park the run in
     flight and drop every connection for nothing. The version this deck is
     actually running is shown unconditionally, next to the strip, whether or
     not there is anything newer. */
  const update = state.health.update || { available: false, to: null };
  show(upgradeBtn, !foreign && update.available);
  if (!foreign && update.available && upgradeBtn.dataset.armed !== "yes") {
    setText(upgradeBtn, update.to ? `Update to ${update.to}` : "Update & restart");
    upgradeBtn.disabled = false;
    upgradeBtn.onclick = upgrade;
  }

  /* Asked to stop. Two shapes reach here, and both are checked before
     `running`, because the loop is still running while it winds down:

     `loop.stopping` is the server saying a run is in flight, which it will
     finish \u2014 killing the graph mid-node would leave worktrees, branches
     and agent sessions behind and throw away calls already paid for, so magi
     does not do it, and this can last tens of minutes.

     A stop asked of an idle loop never reports `stopping` at all: it answers
     "still running" and goes quiet within a poll. Without `stopAskedAt` that
     read as a button that did nothing, so this page remembers its own
     request \u2014 bounded, so a request that somehow did not take gives the
     control back instead of claiming forever that a stop is coming. */
  const asked = !foreign && state.stopAskedAt > 0 && Date.now() - state.stopAskedAt < STOP_ASK_MS;
  if (running && (loop.stopping || asked)) {
    setAttr(box, "data-state", "stopping");
    const link = loop.stopping ? currentRunLink(daemon) : null;
    text.append(
      el("b", { text: "Stopping." }),
      loop.stopping
        ? [link ? " It is finishing run " : " It is finishing the run it is on", link, " first, and will not abandon it."]
        : " It stops as soon as it finishes the poll it is on.",
    );
    quiet(loop.stopping
      ? `Nothing new will be claimed after it${tail}. You can start it again once it has stopped.`
      : `Nothing new will be claimed${tail}. This takes a few seconds when no run is in flight.`);
    if (loop.parking) {
      text.append(" Parking at the next step.");
    } else if (loop.stopping) {
      parkControl("Park at the next step",
        "Stops the run after the step it is on and leaves it resumable, instead of waiting for the whole competition. Use this when you want to replace the binary.");
    }
    return;
  }

  if (!running) {
    const waiting = runnableTasks();
    const error = typeof loop.last_error === "string" && loop.last_error.trim() ? loop.last_error : null;

    /* The loop died rather than being stopped. Kept until the next start
       clears it, and it is the only way somebody holding a phone learns the
       difference \u2014 so it is rendered as its own state, in the fault
       colour the two ordinary "off" states deliberately avoid. */
    if (error) {
      setAttr(box, "data-state", "failed");
      text.append(el("b", { text: "The loop stopped on an error." }), " ", error);
      control("start", "Start the loop again", `${waiting ? `${plural(waiting, "task", "tasks")} still waiting. ` : ""}Starting it clears this error. ${startCost(loop)}`);
      return;
    }

    if (waiting) {
      /* The state this strip exists for. Gold, not rust: the loop being off
         is not a fault, it is a tap away \u2014 and a fault colour here taught
         the operator to ignore the one band that needed them. */
      setAttr(box, "data-state", "waiting");
      text.append(
        el("b", { text: `${plural(waiting, "task", "tasks")} waiting.` }),
        " The loop is off, so nothing will be claimed until you start it.",
      );
      control("start", "Start the loop", startCost(loop));
      return;
    }
    setAttr(box, "data-state", "off");
    text.append(
      el("b", { text: "Loop is off." }),
      waiting === null
        ? " Nothing has been claimed."
        : " Nothing is queued, so nothing is waiting.",
    );
    control("start", "Start the loop", `${startCost(loop)} Until one is filed it just watches the queue.`);
    return;
  }

  if (daemon.current && daemon.current.length > 0) {
    setAttr(box, "data-state", "working");
    const first = daemon.current[0];
    const rest = daemon.current.length - 1;
    text.append(
      el("b", { text: "Working" }),
      " on ",
      currentRunLink(daemon),
      first.task
        ? el("span", { class: "daemon-run", text: ` \u2190 task ${shortId(first.task)}` })
        : null,
      rest > 0 ? ` (and ${plural(rest, "other run", "other runs")})` : null,
      tail,
    );
  } else if (daemon.idle) {
    setAttr(box, "data-state", "idle");
    text.append(el("b", { text: "Loop idle." }), ` Nothing runnable in the queue${tail}.`);
  } else if (daemon.running) {
    setAttr(box, "data-state", "working");
    text.append(el("b", { text: "Working." }), ` Claiming a task${tail}.`);
  } else {
    /* Started here, no heartbeat on disk yet. Said as its own sentence rather
       than borrowed from `idle`, because "nothing runnable in the queue" would
       be a claim about the queue that nothing has checked. */
    setAttr(box, "data-state", "working");
    text.append(el("b", { text: "Started." }), " Waiting for the loop\u2019s first heartbeat.");
  }

  /* Someone started the loop in another process. Both endpoints answer 409
     for a loop this one does not own, so no button is offered: a control that
     silently fails is worse than none. The queue is being drained either way,
     which is the part the operator actually needs to know. */
  if (foreign) {
    const pid = Number(daemon.pid);
    quiet(`${Number.isFinite(pid) && pid ? `Process ${pid} owns` : "Another process owns"} this loop, so this page can watch it but not stop it. The queue is being drained regardless \u2014 nothing is waiting on you.`);
    return;
  }

  /* Two different promises, because they are two different facts: with a run
     in flight the operator is being told they will wait for it, and with none
     they are being told there is nothing to wait for. */
  control("stop", "Stop the loop", daemon.current && daemon.current.length > 0
    ? "It finishes the run(s) it is on first, then stops claiming. Nothing in flight is abandoned."
    : "It stops claiming new tasks. Nothing is in flight, so nothing is interrupted.");
}

/* Start or stop the loop in this server. Neither direction is guarded by a
   second tap: starting is repeatable and stopping is not destructive.

   Neither direction is believed on request, either. A stop is accepted while
   the loop is still running \u2014 reported as `stopping` when a run is in
   flight, and as plain "running" when there is none and it will go quiet a
   poll later \u2014 so "stopped" is announced from a view where `running` has
   actually gone false, not from the tap. A 409 is followed by a refetch,
   which is what replaces a button this page cannot honour with the sentence
   explaining why. */
/* Replace the binary and come back on it.
 *
 * The one thing the deck could not do for itself: `cargo install` cannot
 * overwrite a running executable, so every fix waited for a competition to end
 * or went in with the deck stopped. `kaishin` renames the running image aside
 * instead, so only the restart needs arranging - and the run in flight is
 * parked at its next node boundary first, which is why this costs at most one
 * step rather than a whole competition.
 *
 * The server answers 202 and then exits, so there is nothing to await here
 * beyond that acknowledgement: the phone learns the deck is back the same way
 * it learns everything else, by reconnecting. */
/* The upgrade's own line under the strip. Kept out of `fail`'s alert: this is
   not an error, and it has to survive the change-stream refreshes that redraw
   the strip while the loop parks. */
function quietNote(text) {
  const why = $("loop-why");
  if (!why) return;
  setText(why, text);
  show(why, Boolean(text));
}

async function upgrade() {
  const btn = $("loop-upgrade");
  if (!confirmed(btn, "Replace the binary and restart?")) return;
  btn.disabled = true;
  setText(btn, "Upgrading\u2026");
  try {
    const out = await postJson(API.upgrade);
    ok();
    const detail = out.detail || "The deck is replacing itself and will come back.";
    announce(detail);
    /* Nothing newer to install: say so and give the button back, rather than
       leaving "Upgrading…" on a deck that did not move. */
    if (!out.to) {
      setText(btn, "Update & restart");
      btn.disabled = false;
      quietNote(detail);
      return;
    }
    /* A park waits for the node in flight, which can be an hour. Leaving the
       button reading "Upgrading…" for that long is the same mistake as an
       error rendered off screen: it looks wedged. The strip says what it is
       waiting for, and the phone finds out it is back by reconnecting. */
    setText(btn, "Parking, then restarting\u2026");
    quietNote(detail);
  } catch (error) {
    setText(btn, "Update & restart");
    btn.disabled = false;
    fail(`Could not upgrade: ${error.message}`);
  }
}

/* One tap arms, the second commits, and the label says which state it is in.
   Used for the upgrade because it ends the process the operator is talking
   to - and a mis-tap that restarts the deck mid-competition is the kind of
   thing a phone in a pocket does. */
function confirmed(btn, question) {
  if (btn.dataset.armed === "yes") {
    btn.dataset.armed = "";
    return true;
  }
  btn.dataset.armed = "yes";
  setText(btn, question);
  setTimeout(() => {
    if (btn.dataset.armed === "yes") {
      btn.dataset.armed = "";
      setText(btn, "Update & restart");
    }
  }, 6000);
  return false;
}

async function setLoop(running, park = false) {
  const button = $("loop-toggle");
  const parkBtn = $("loop-park");
  button.disabled = true;
  if (park) {
    parkBtn.disabled = true;
    setText(parkBtn, "Parking\u2026");
  } else {
    setText(button, running ? "Starting\u2026" : "Stopping\u2026");
  }
  try {
    const view = await postJson(API.loop, { running, park });
    /* Set before applyLoop, so the render that follows already knows this
       page asked \u2014 that is what puts an idle loop into `stopping`. */
    state.stopAskedAt = running ? 0 : Date.now();
    applyLoop(view);
    ok();
    announce(running
      ? "Loop started. It claims the highest-priority task next."
      : view.stopping
        ? "Loop asked to stop. It finishes the run it is on first."
        : "Loop asked to stop. It goes quiet within a few seconds.");
  } catch (error) {
    /* 409 is not a failure of this page: the loop is already running, or it
       belongs to another process. The server's own message names which, and
       the pid when there is one, so it is shown verbatim. */
    fail(error.status === 409
      ? `The loop did not change: ${error.message}`
      : `Could not ${running ? "start" : "stop"} the loop: ${error.message}`);
    await loadLoop();
  } finally {
    renderLoop();   /* restores the label, whichever way it went */
  }
}

/* One place where a LoopView lands, so /api/loop and the `loop` block inside
   /api/health cannot disagree about what is on screen. Also where a stop this
   page asked for is finally confirmed: the loop going quiet is the event, and
   it arrives on a later view rather than in the answer to the request. */
function applyLoop(view) {
  const stopped = state.stopAskedAt > 0 && view && !view.running && !view.stopping;
  state.loop = view;
  if (state.health) state.health.loop = view;
  if (stopped) {
    state.stopAskedAt = 0;
    announce("Loop stopped.");
  }
  renderLoop();
}

async function loadLoop() {
  try {
    applyLoop(await getJson(API.loop));
  } catch (error) {
    fail(`Could not read the loop: ${error.message}`);
  }
}

/* ---- runs list --------------------------------------------------------- */
function createRunCard() {
  const chipSlot = el("span");
  const whenSlot = el("time", { class: "card-when" });
  const title = el("h2", { class: "card-title" });
  const repo = el("span", { class: "repo" });
  const counts = el("span");
  const winner = el("span", { class: "win" });
  const reviews = el("span");
  const meta = el("div", { class: "card-meta" }, repo, counts, winner, reviews);
  const note = el("p", { class: "card-note" });
  /* Two attempts at one task are two cards with the same title, and the deck
     used to give no hint which was which - "why are there two of the same,
     one stalled and one blocked?" was the reasonable question. The older one
     now says what replaced it. Sits with the note rather than in the chip
     row: it explains the card's standing, and a chip would read as another
     status. */
  const superseded = el("p", { class: "card-note card-superseded" });
  const event = el("p", { class: "card-event" });
  const rail = el("div");

  const card = el("a", { class: "card" },
    el("div", { class: "card-top" }, chipSlot, whenSlot),
    title, meta, note, superseded, event, rail,
  );

  /* The card is one big anchor, which is the affordance the whole phone
     layout leans on, and an anchor may contain neither another anchor nor a
     button. The pull-request link and the Answer action therefore live in a
     sibling strip that CSS draws as the bottom of the same card. */
  const prLink = el("a", { class: "pr-link", target: "_blank", rel: "noopener noreferrer" });
  const checks = el("span");
  const prRound = el("span", { class: "pr-round" });
  const tailGo = el("a", { class: "btn btn-gold tail-go" });
  const tailNote = el("p", { class: "tail-note" });
  const tail = el("div", { class: "card-tail" }, prLink, checks, prRound, tailGo, tailNote);

  const row = el("li", {}, card, tail);
  row.refs = { card, chipSlot, whenSlot, title, repo, counts, winner, reviews, note, superseded,
               event, rail, tail, prLink, checks, prRound, tailGo, tailNote };
  return row;
}

function updateRunCard(row, run) {
  const r = row.refs;
  /* `waiting` is a field of its own on the summary precisely because the
     status string still names the node the run parked in. It wins: a run
     nobody is working on must not read as one that is being worked on. */
  const status = run.waiting ? "waiting" : String(run.status || "");
  const meta = RUN_STATUS[status] || {};
  const parked = isWaiting(run);
  const tone = toneOf(status, RUN_STATUS);

  r.card.setAttribute("href", `#/runs/${run.id}`);
  setAttr(r.card, "data-tone", tone);
  setAttr(row, "data-tone", tone);

  /* The chip is replaced rather than mutated: it is one element and its
     pseudo-element glyph is attribute-driven, so this cannot reflow siblings. */
  const next = chip(status, RUN_STATUS);
  if (r.chipSlot.firstChild) r.chipSlot.firstChild.replaceWith(next);
  else r.chipSlot.append(next);

  const at = when(run.updated_at || run.created_at);
  setText(r.whenSlot, at.text);
  setAttr(r.whenSlot, "datetime", run.updated_at || run.created_at);
  setAttr(r.whenSlot, "title", `updated ${at.title}`);

  setText(r.title, run.title || run.instruction || run.id);
  setText(r.repo, run.repo_name || "");
  setAttr(r.repo, "title", run.repo || "");

  const cands = Number(run.candidates) || 0;
  const viable = Number(run.viable) || 0;
  const judges = Number(run.judges) || 0;
  const bits = [];
  if (cands) bits.push(viable === cands ? plural(cands, "candidate", "candidates") : `${viable}/${cands} viable`);
  if (judges) bits.push(plural(judges, "judge", "judges"));
  setText(r.counts, bits.join(", "));
  show(r.counts, bits.length > 0);

  setText(r.winner, run.winner ? `winner ${run.winner}` : "");
  show(r.winner, Boolean(run.winner));

  const rounds = Number(run.reviews) || 0;
  const losses = Number(run.quota_losses) || 0;
  const extra = [];
  if (rounds) extra.push(plural(rounds, "review round", "review rounds"));
  if (losses) extra.push(`${plural(losses, "seat", "seats")} lost to quota`);
  setText(r.reviews, extra.join(", "));
  show(r.reviews, extra.length > 0);
  separate(r.reviews.parentNode);

  /* Spell out the endings that look like results but are not. `waiting` is
     excluded because the strip below says it better, and with a button. */
  const spell = Boolean(meta.note) && status !== "merged" && status !== "ready" && status !== "waiting";
  setText(r.note, spell ? meta.note : "");
  show(r.note, spell);

  const later = typeof run.superseded_by === "string" ? run.superseded_by : null;
  setText(r.superseded, later ? `Superseded by ${later} \u2014 a later attempt at the same task.` : "");
  show(r.superseded, Boolean(later));

  /* The run's own last line, on finished runs as well as moving ones. It used
     to be hidden the moment a run stopped, which is exactly when it is worth
     most: a `stalled` card then explained itself with a generic note while
     "verdict rests on 1 of 3 judges (quorum 2)" sat unread in the record, and
     a `blocked` one offered a guess with an "or" in it instead of "no check
     status is readable on the pull request". */
  const moving = !run.done;
  setText(r.event, run.event || "");
  show(r.event, Boolean(run.event));

  /* A parked run keeps its rail so the operator can see how far it got, with
     the node it stopped in drawn halted rather than pulsing. */
  const ask = parked ? openFor(run.id)[0] : null;
  const rail = moving ? phaseRail(status, ask ? ask.node : null) : null;
  clear(r.rail);
  if (rail) r.rail.append(rail);

  updateRunTail(row, run, { parked, ask });
}

/* The strip under the card: where the pull request lives, and where the one
   action the operator can take on a run appears when there is one. */
function updateRunTail(row, run, { parked, ask }) {
  const r = row.refs;
  const pr = run.pr && typeof run.pr === "object" ? run.pr : null;

  // The href goes through `forgeUrl`: a run record is data magi wrote, but a
  // `javascript:` value in it would be one tap from running in the operator's
  // session, and a link that cannot be trusted is not shown at all.
  const prHref = pr ? forgeUrl(pr.url) : null;
  if (prHref) {
    setAttr(r.prLink, "href", prHref);
    setAttr(r.prLink, "title", prHref);
    setText(r.prLink, `PR #${pr.number}`);
  }
  show(r.prLink, Boolean(prHref));

  if (pr) r.checks.replaceChildren(checksChip(pr));
  show(r.checks, Boolean(pr));

  const rounds = pr ? Number(pr.rounds) || 0 : 0;
  setText(r.prRound, rounds ? `land round ${Number(pr.round) || 0} of ${rounds}` : "");
  show(r.prRound, rounds > 0);

  if (ask) {
    setAttr(r.tailGo, "href", "#/questions");
    setText(r.tailGo, "Answer");
    setAttr(r.tailGo, "aria-label", `Answer: ${ask.summary || "the open question"}`);
  }
  show(r.tailGo, Boolean(ask));

  const note = parked
    ? `Waiting on you: ${(ask && ask.summary) || "an agent asked for a decision."}`
    : run.waiting
      ? "Answered. The loop picks this up on its next tick."
      : pr
        ? landNote(pr)
        : "";
  setText(r.tailNote, note);
  show(r.tailNote, note !== "");

  const tailed = Boolean(pr) || Boolean(run.waiting);
  show(r.tail, tailed);
  setAttr(row, "data-tail", tailed ? "1" : null);
}

/* ---- runs: grouping into sections ------------------------------------- *
 * The plain, updated-first list stops being readable once a few dozen runs
 * pile up, so it is split into the four questions an operator actually asks:
 * is anything waiting on me, what's moving, what landed, and what didn't.
 * `waiting` (the field, not the refined isWaiting() the card tail uses) wins
 * over status here on purpose \u2014 a run parked on a question is the one
 * thing that needs a human regardless of which node it stopped in. */
const RUN_SECTIONS = [
  { key: "waiting", label: "Waiting on you", defaultOpen: true },
  { key: "flight", label: "In flight", defaultOpen: true },
  { key: "landed", label: "Landed", defaultOpen: true },
  { key: "ended", label: "Ended", defaultOpen: true },
];

function runSection(run) {
  if (run.waiting) return "waiting";
  const status = String(run.status || "");
  if (status === "merged" || status === "ready") return "landed";
  if (status === "stalled" || status === "blocked" || status === "failed") return "ended";
  return "flight";
}

/* ---- runs: state chips -------------------------------------------------- *
 * A second, independent lens on the same heads RUN_SECTIONS groups. The tree
 * above (runs-tree) narrows by section/repo but is desktop-only — see the
 * width gate on .runs-tree in app.css — so a phone, the primary way this
 * deck gets read, has never had a way to ask for anything but the full flood
 * of every run ever competed. These chips are that control, and unlike the
 * tree they render everywhere.
 *
 * Defaulting to "active" (in flight + waiting) rather than "all" is the
 * point: a finished run needs nobody's attention, and piling every merged,
 * failed and superseded run above the handful still moving is exactly the
 * "too much to read on a phone" complaint this exists to fix. "done" and
 * "all" stay one tap away for whoever wants the history. */
const RUN_STATE_FILTERS = [
  { key: "active", label: "Active", countNoun: "active", match: (run) => !run.done },
  { key: "flight", label: "In flight", countNoun: "in flight", match: (run) => !run.done && !run.waiting },
  { key: "waiting", label: "Waiting", countNoun: "waiting", match: (run) => Boolean(run.waiting) },
  { key: "done", label: "Done", countNoun: "done", match: (run) => Boolean(run.done) },
  { key: "all", label: "All", countNoun: "runs", match: () => true },
];

function activeRunStateFilter() {
  return RUN_STATE_FILTERS.find((f) => f.key === state.runsStateFilter) || RUN_STATE_FILTERS[0];
}

function matchesRunState(run) {
  return activeRunStateFilter().match(run);
}

/* A head that still names a `superseded_by` (see foldRuns below) is one
   whose successor fell outside the page /api/runs returned, so it could not
   be folded under a newer card — it is genuinely an old attempt, just one
   this client has nowhere to nest. Hiding it by default is the same
   judgement call as hiding "done": it is not what an operator scanning for
   what needs them wants in front of them, and "all" still shows it. */
function isOrphanSuperseded(run) {
  return typeof run.superseded_by === "string" && run.superseded_by !== "";
}

/* Exactly one chip is ever selected, so picking the already-selected one is
   a no-op rather than clearing back to nothing — unlike the tree filter
   above, there is no "no filter" state here for the default to fall back to. */
function selectRunStateFilter(key) {
  if (state.runsStateFilter === key) return;
  state.runsStateFilter = key;
  renderRuns();
}

/* Built once and then only updated in place, not rebuilt like the tree —
   there are only five of these, but a full rebuild on every SSE tick would
   still steal keyboard focus off whichever chip the operator just tapped. */
function renderRunStateChips(runs) {
  const bar = $("runs-state-chips");
  if (!bar.childElementCount) {
    for (const def of RUN_STATE_FILTERS) {
      bar.append(el("button", {
        class: "state-chip",
        type: "button",
        role: "radio",
        "data-key": def.key,
        onclick: () => selectRunStateFilter(def.key),
      },
        el("span", { class: "state-chip-label", text: def.label }),
        el("span", { class: "state-chip-count" }),
      ));
    }
  }
  for (const node of bar.children) {
    const def = RUN_STATE_FILTERS.find((f) => f.key === node.dataset.key);
    // Counted from the full, unfiltered /api/runs list, not from `heads` —
    // a folded-away earlier attempt (see foldRuns) never gets its own card,
    // but it is still a real done/waiting/in-flight run and belongs in the
    // census this badge is reporting. Counting from `heads` instead would
    // make a completed retry disappear from the "Done" badge entirely
    // (0 where the fleet plainly has one), and it would still shift the
    // moment the run in question got folded under a new attempt — the same
    // unreadable-number failure mode this full-list count exists to avoid.
    setText(node.querySelector(".state-chip-count"), String(runs.filter(def.match).length));
    setAttr(node, "aria-checked", state.runsStateFilter === def.key ? "true" : "false");
  }
}

/* Which older attempts fold into which card. `superseded_by` names the
   *successor*'s short id, so a chain is walked forward from an attempt to
   whatever replaced it until nothing newer is known. The run that walk ends
   on is the one shown; everything behind it folds under that card.

   Walking stops the moment a `superseded_by` names a short id this page has
   never heard of \u2014 cut off by `limit`, or unreadable \u2014 and the run
   in hand is shown as-is rather than assumed superseded by something it
   cannot point at. That is what keeps a run from disappearing when the
   response happens to omit the attempt that replaced it.

   It also has to stop on a cycle \u2014 two runs naming each other, however that
   record came to be \u2014 without losing either one. Walking one run at a time
   with only its own path in hand would resolve A to B and B to A: neither
   satisfies "this run is its own head", so neither ever reaches `heads`
   below and the pair vanishes silently. Each walk here instead remembers
   its whole path and, on closing a loop, mints the run the loop closed on as
   the head for every run on that path \u2014 itself included \u2014 so a cycle always
   resolves to one real, present run rather than to none. */
function foldRuns(runs) {
  const byShort = new Map();
  for (const run of runs) if (run.short) byShort.set(run.short, run);
  const nextOf = (run) => (run.superseded_by && byShort.get(run.superseded_by)) || null;

  const headOf = new Map();
  for (const run of runs) {
    if (headOf.has(run.id)) continue;
    const path = [];
    const atIndex = new Map();
    let cur = run;
    while (!headOf.has(cur.id) && !atIndex.has(cur.id)) {
      atIndex.set(cur.id, path.length);
      path.push(cur);
      const next = nextOf(cur);
      if (!next) break;
      cur = next;
    }
    const head = headOf.get(cur.id) || cur;
    for (const node of path) headOf.set(node.id, head);
  }

  const heads = [];
  const childrenOf = new Map();
  for (const run of runs) {
    const head = headOf.get(run.id);
    if (head.id === run.id) {
      heads.push(run);
    } else {
      if (!childrenOf.has(head.id)) childrenOf.set(head.id, []);
      childrenOf.get(head.id).push(run);
    }
  }
  return { heads, childrenOf };
}

/* Section order preserved from RUN_SECTIONS; run order within a section
   preserved from the order `heads` arrived in, which is /api/runs' own
   updated-first order. */
function groupBySection(heads) {
  const bySection = new Map(RUN_SECTIONS.map((s) => [s.key, []]));
  for (const run of heads) bySection.get(runSection(run)).push(run);
  return bySection;
}

const repoLabel = (run) => run.repo_name || run.repo || "Unknown repository";

/* The wide-screen tree: section, then repo, each carrying the count of cards
   \u2014 cards, not raw runs, so this number always means the same thing as
   the section heading it rolls up to. Built from the *unfiltered* heads, so
   picking a node never shrinks the tree out from under the tap that picked
   it. Sections and repos with nothing in them are left out rather than shown
   at zero: an empty branch is not something to file into. */
function buildRunsTree(bySection) {
  const sections = [];
  for (const { key, label } of RUN_SECTIONS) {
    const heads = bySection.get(key);
    if (heads.length === 0) continue;
    const byRepo = new Map();
    for (const run of heads) {
      const repo = repoLabel(run);
      if (!byRepo.has(repo)) byRepo.set(repo, 0);
      byRepo.set(repo, byRepo.get(repo) + 1);
    }
    const repos = [...byRepo.entries()]
      .sort((a, b) => a[0].localeCompare(b[0]))
      .map(([repo, count]) => ({ repo, count }));
    sections.push({ key, label, count: heads.length, repos });
  }
  return sections;
}

/* Only ever one filter active at a time: a section, or a section plus one of
   its repos. There is no URL for it \u2014 the tree is a lens on the list
   already on screen, not a place worth deep-linking to. */
function matchesFilter(run) {
  const { section, repo } = state.runsFilter;
  if (!section) return true;
  if (runSection(run) !== section) return false;
  return !repo || repoLabel(run) === repo;
}

function selectRunsFilter(section, repo) {
  const same = state.runsFilter.section === section && state.runsFilter.repo === (repo || null);
  state.runsFilter = same ? { section: null, repo: null } : { section, repo: repo || null };
  renderRuns();
}

function clearRunsFilter() {
  state.runsFilter = { section: null, repo: null };
  renderRuns();
}

function renderRunsTree(sections) {
  const nav = $("runs-tree");
  show(nav, sections.length > 0);

  /* The tree is rebuilt from scratch below rather than reconciled node by
     node — it is small, at most four sections and a handful of repos each —
     but a full rebuild would otherwise drop keyboard focus on every poll, so
     whichever node has it is found again afterwards by the (section, repo)
     it names rather than by identity. */
  const active = document.activeElement;
  const focused = nav.contains(active)
    ? { section: active.dataset.section, repo: active.dataset.repo || null }
    : null;

  if (sections.length === 0) {
    clear(nav);
    return;
  }
  const root = el("ul", { class: "runs-tree-list" });
  for (const section of sections) {
    const on = state.runsFilter.section === section.key && !state.runsFilter.repo;
    const sub = el("ul", { class: "runs-tree-sub" });
    for (const r of section.repos) {
      const repoOn = state.runsFilter.section === section.key && state.runsFilter.repo === r.repo;
      sub.append(el("li", {},
        el("button", {
          class: "runs-tree-node runs-tree-repo",
          type: "button",
          "data-section": section.key,
          "data-repo": r.repo,
          "aria-current": repoOn ? "true" : null,
          onclick: () => selectRunsFilter(section.key, r.repo),
        },
          el("span", { class: "runs-tree-label", text: r.repo }),
          el("span", { class: "runs-tree-count", text: String(r.count) }),
        ),
      ));
    }
    root.append(el("li", {},
      el("button", {
        class: "runs-tree-node",
        type: "button",
        "data-section": section.key,
        "aria-current": on ? "true" : null,
        onclick: () => selectRunsFilter(section.key, null),
      },
        el("span", { class: "runs-tree-label", text: section.label }),
        el("span", { class: "runs-tree-count", text: String(section.count) }),
      ),
      sub,
    ));
  }
  clear(nav);
  nav.append(root);

  if (focused) {
    const match = [...nav.querySelectorAll(".runs-tree-node")].find((node) =>
      node.dataset.section === focused.section && (node.dataset.repo || null) === focused.repo);
    if (match) match.focus();
  }
}

function renderRunsFilterBar() {
  const bar = $("runs-filter");
  const { section, repo } = state.runsFilter;
  if (!section) {
    show(bar, false);
    return;
  }
  const label = (RUN_SECTIONS.find((s) => s.key === section) || {}).label || section;
  setText($("runs-filter-text"), `Showing ${label}${repo ? ` \u203a ${repo}` : ""}.`);
  show(bar, true);
}

/* ---- shared: section collapse, kept in localStorage --------------------- *
 * One mechanism, two independent users (Runs, Backlog): each keeps its own
 * storage key and its own per-section default open/closed state, since
 * neither shares section keys with the other. */
function loadCollapsed(storageKey) {
  try {
    const raw = localStorage.getItem(storageKey);
    const parsed = raw ? JSON.parse(raw) : null;
    return parsed && typeof parsed === "object" ? parsed : {};
  } catch {
    return {};   /* localStorage denied (private mode) or the value was junk */
  }
}

function saveCollapsed(storageKey, collapsed) {
  try {
    localStorage.setItem(storageKey, JSON.stringify(collapsed));
  } catch {
    /* localStorage denied in private mode; the choice just won't outlive the tab */
  }
}

function isSectionOpen(collapsed, key, defaultOpen) {
  const saved = collapsed[key];
  return typeof saved === "boolean" ? saved : defaultOpen;
}

/* ---- shared: one section (a native <details>, for free keyboard support) *
 * `def` is one entry of a *_SECTIONS array: { key, label, defaultOpen }. */
function createSection(def, collapsed, storageKey) {
  const count = el("span", { class: "list-section-count" });
  const summary = el("summary", { class: "list-section-head" },
    el("h2", { class: "list-section-title", text: def.label }), count);
  const list = el("ol", { class: "cards" });
  const details = el("details", {
    class: "list-section",
    open: isSectionOpen(collapsed, def.key, def.defaultOpen),
  }, summary, list);
  details.dataset.key = def.key;
  details.addEventListener("toggle", () => {
    collapsed[def.key] = details.open;
    saveCollapsed(storageKey, collapsed);
  });
  details.refs = { summary, count, list };
  return details;
}

/* Keyed reconcile across sections, the same shape as syncList() above but one
   level up: a section that empties out (everything in it superseded, or
   filtered away) is removed rather than left on screen at "0 items". */
function syncSections(root, sectionDefs, itemsByKey, createFn, updateFn) {
  const existing = new Map();
  for (const child of root.children) existing.set(child.dataset.key, child);

  let previous = null;
  for (const def of sectionDefs) {
    const items = itemsByKey.get(def.key) || [];
    if (items.length === 0) continue;
    let node = existing.get(def.key);
    if (node) existing.delete(def.key);
    else node = createFn(def);
    updateFn(node, items);
    const wanted = previous ? previous.nextSibling : root.firstChild;
    if (node !== wanted) root.insertBefore(node, wanted);
    previous = node;
  }
  for (const stale of existing.values()) stale.remove();
}

/* ---- runs: one section, plus the folded-attempts count Backlog has no
   equivalent of ------------------------------------------------------- */
function createRunSection(def) {
  const section = createSection(def, state.runsCollapsed, RUNS_COLLAPSE_KEY);
  const folded = el("span", { class: "runs-section-folded" });
  section.refs.summary.append(folded);
  section.refs.folded = folded;
  return section;
}

function updateRunSection(node, heads, childrenOf) {
  const foldedTotal = heads.reduce((sum, run) => sum + (childrenOf.get(run.id) || []).length, 0);
  setText(node.refs.count, plural(heads.length, "run", "runs"));
  setText(node.refs.folded, foldedTotal
    ? `, ${plural(foldedTotal, "earlier attempt", "earlier attempts")} folded`
    : "");
  syncList(node.refs.list, heads, (r) => r.id, createRunRow,
    (row, run) => updateRunRow(row, run, childrenOf.get(run.id) || []));
}

function syncRunSections(root, bySection, childrenOf) {
  syncSections(root, RUN_SECTIONS, bySection, createRunSection,
    (node, heads) => updateRunSection(node, heads, childrenOf));
}

/* ---- runs: one row, a card plus its folded-away earlier attempts ------- *
 * createRunCard()/updateRunCard() build and fill the card itself and are
 * left untouched; the folded list is a sibling appended to the same <li>,
 * because the card is a single <a> and an anchor may not contain another
 * interactive element. */
function createRunRow() {
  const row = createRunCard();
  const summary = el("summary", { class: "run-folded-summary" });
  const list = el("ul", { class: "run-folded-list" });
  const folded = el("details", { class: "run-folded advanced" }, summary, list);
  row.append(folded);
  row.refs.folded = folded;
  row.refs.foldedSummary = summary;
  row.refs.foldedList = list;
  return row;
}

function updateRunRow(row, run, children) {
  updateRunCard(row, run);
  const list = row.refs.foldedList;
  clear(list);
  for (const child of children) {
    const at = when(child.updated_at || child.created_at);
    list.append(el("li", {},
      el("a", { class: "run-folded-link", href: `#/runs/${child.id}` },
        el("span", { class: "run-folded-id", text: child.short || shortId(child.id) }),
        el("span", { class: "run-folded-status", text: child.waiting ? "waiting" : String(child.status || "") }),
        el("time", { class: "run-folded-when", text: at.text, title: at.title }),
      ),
    ));
  }
  setText(row.refs.foldedSummary, children.length
    ? plural(children.length, "earlier attempt", "earlier attempts")
    : "");
  show(row.refs.folded, children.length > 0);
}

function renderRuns() {
  const runs = state.runs;
  const sectionsRoot = $("runs-sections");

  if (runs === null) {
    setText($("runs-count"), "Loading\u2026");
    show($("runs-tree"), false);
    show($("runs-filter"), false);
    show($("runs-state-chips"), false);
    if (!sectionsRoot.dataset.skeleton) {
      clear(sectionsRoot);
      const list = el("ol", { class: "cards" });
      for (let i = 0; i < 3; i += 1) {
        list.append(el("li", { class: "card skeleton" },
          el("div", { class: "bar", style: "width:34%" }),
          el("div", { class: "bar", style: "width:88%;height:18px" }),
          el("div", { class: "bar", style: "width:56%" }),
        ));
      }
      sectionsRoot.append(list);
      sectionsRoot.dataset.skeleton = "1";
    }
    return;
  }

  if (sectionsRoot.dataset.skeleton) {
    clear(sectionsRoot);
    delete sectionsRoot.dataset.skeleton;
  }

  const unreadable = Number(state.health && state.health.runs_unreadable) || 0;
  const unreadableNote = unreadable
    ? `${unreadable} unreadable`
    : "";

  const { heads, childrenOf } = foldRuns(runs);

  show($("runs-state-chips"), runs.length > 0);
  if (runs.length > 0) renderRunStateChips(runs);

  /* Two hidings, on by default, both lifted by "all": a done run and an old
     attempt (isOrphanSuperseded, or a whole entry in childrenOf) are both
     "not what needs me right now", which is the whole reason this filter
     exists. supersededHidden exists only to keep the count honest — without
     it, runs-count would say "3 in flight" while quietly also having
     dropped a dozen cards the operator never asked to hide. */
  const passingState = heads.filter(matchesRunState);
  const stateFiltered = state.runsStateFilter === "all"
    ? passingState
    : passingState.filter((r) => !isOrphanSuperseded(r));
  const orphanHidden = passingState.length - stateFiltered.length;

  /* The tree stays built from every head regardless of the state chip, same
     as it already ignored the section/repo filter it sits beside — a chip
     that empties "Landed" out of the visible cards must not also erase the
     tree's own way of reaching Landed, or "all"/"done" become the only way
     back in even though the tree is the desktop's whole point. */
  renderRunsTree(buildRunsTree(groupBySection(heads)));
  renderRunsFilterBar();
  const visible = stateFiltered.filter(matchesFilter);

  /* Every list in childrenOf exists only because foldRuns resolved a
     superseded_by to a head on this page (see foldRuns above) — it is
     exactly as superseded as an orphan head is, so "all" is what shows it
     and anything else hides it, the same toggle isOrphanSuperseded answers
     to. Passing an empty map (rather than filtering each list) reuses
     updateRunRow's existing "nothing folded under this card" rendering
     instead of adding a second code path for the same outcome. */
  const foldedHidden = state.runsStateFilter === "all"
    ? 0
    : visible.reduce((sum, run) => sum + (childrenOf.get(run.id) || []).length, 0);
  const childrenForRender = state.runsStateFilter === "all" ? childrenOf : new Map();
  syncRunSections(sectionsRoot, groupBySection(visible), childrenForRender);

  const supersededHidden = orphanHidden + foldedHidden;

  const counts = runs.length === 0
    ? (unreadable ? `no readable runs, ${unreadableNote}` : "Nothing has run yet")
    : (() => {
        const countNoun = activeRunStateFilter().countNoun;
        const headline = countNoun === "runs"
          ? plural(visible.length, "run", "runs")
          : `${visible.length} ${countNoun}`;
        return [headline, supersededHidden ? `${supersededHidden} superseded hidden` : "", unreadableNote]
          .filter(Boolean)
          .join(", ");
      })();
  setText($("runs-count"), counts);

  // An unreadable run is still a run: offer the explanation instead of the
  // "file your first task" prompt, which would be wrong and confusing.
  show($("runs-empty"), runs.length === 0 && unreadable === 0);
  show($("runs-unreadable"), runs.length === 0 && unreadable > 0);
  // Runs exist, and at least one survives the state filter's own hiding, but
  // none of them are the state the operator picked — distinct from the tree
  // filter's empty state below, which only fires once the state filter has
  // already left something on the table for the tree to narrow further.
  show($("runs-state-empty"), runs.length > 0 && stateFiltered.length === 0);
  show($("runs-filter-empty"), stateFiltered.length > 0 && Boolean(state.runsFilter.section) && visible.length === 0);
}

/* ---- queue ------------------------------------------------------------- */
function createTaskCard() {
  const chipSlot = el("span");
  const priority = el("span", { class: "tag", "data-tone": "ink" });
  /* `solo` runs one implementer straight into review instead of the usual
     multi-agent competition - a fact about how the task will be spent that a
     card must show, the same way priority is shown, rather than something
     only visible by opening the full instruction. */
  const solo = el("span", { class: "tag", "data-tone": "teal", text: "solo" });
  const whenSlot = el("time", { class: "card-when" });
  const title = el("h2", { class: "card-title" });
  const source = el("a", { class: "task-source" });
  const repo = el("span", { class: "repo" });
  const attempts = el("span");
  const outcome = el("span");
  const meta = el("div", { class: "card-meta" }, source, repo, attempts, outcome);
  const note = el("p", { class: "card-note" });
  const error = el("pre", { class: "err" });
  const instruction = el("details", { class: "advanced" },
    el("summary", { text: "Full instruction" }),
    el("div", { class: "instruction md" }));
  const runLink = el("a", { class: "btn btn-quiet" });
  /* Priority is a step, not a typed value: the operator wants "ahead of
     that other one", not to compose a number. +1/-1 both reach the same
     places a competing task's priority already sits. */
  const priorityDown = el("button", { class: "btn btn-quiet btn-step", type: "button", text: "" });
  const priorityUp = el("button", { class: "btn btn-quiet btn-step", type: "button", text: "+" });
  const priorityBox = el("span", { class: "task-priority-box" }, priorityDown, priorityUp);
  const editBtn = el("button", { class: "btn btn-quiet", type: "button", text: "Edit" });
  const holdBox = el("span", { class: "task-hold-box" });
  const doneBox = el("span", { class: "task-done-box" });
  const deleteBox = el("span", { class: "task-delete-box" });
  const actions = el("div", { class: "card-actions" },
    runLink, priorityBox, editBtn, holdBox, doneBox, deleteBox);

  const card = el("li", { class: "card" },
    el("div", { class: "card-top" }, chipSlot, priority, solo, whenSlot),
    title, meta, note, error, instruction, actions,
  );
  card.refs = {
    card, chipSlot, priority, solo, whenSlot, title, source, repo, attempts,
    outcome, note, error, instruction, runLink, priorityDown, priorityUp,
    editBtn, holdBox, doneBox, deleteBox,
  };
  return card;
}

function updateTaskCard(row, task) {
  const r = row.refs;
  const status = String(task.status_str || task.status || "");
  const meta = TASK_STATUS[status] || {};

  setAttr(r.card, "data-tone", toneOf(status, TASK_STATUS));

  const next = chip(status, TASK_STATUS);
  if (r.chipSlot.firstChild) r.chipSlot.firstChild.replaceWith(next);
  else r.chipSlot.append(next);

  const priority = Number(task.priority) || 0;
  setText(r.priority, priority > 0 ? `priority +${priority}` : `priority ${priority}`);
  setAttr(r.priority, "data-tone", priority > 0 ? "rust" : "ink");
  show(r.priority, priority !== 0);

  show(r.solo, Boolean(task.solo));

  const at = when(task.updated_at || task.created_at);
  setText(r.whenSlot, at.text);
  setAttr(r.whenSlot, "datetime", task.updated_at || task.created_at);
  setAttr(r.whenSlot, "title", `updated ${at.title}`);

  setText(r.title, task.title || task.instruction || task.id);
  setText(r.source, task.source_label || "");
  /* An agent-filed task names the run or chat that filed it right in its
     label ("chat@a1b2", "implement@5dae") - that place still exists and is
     one tap away, so the label becomes the link instead of leaving the
     operator to go find it by hand. `node === "chat"` is how `Source::label`
     spells a talk conversation; everything else agent-filed is a run node. */
  const src = task.source || {};
  const sourceHref = src.kind === "agent"
    ? (src.node === "chat" ? `#/chat/${src.run}` : `#/runs/${src.run}`)
    : null;
  setAttr(r.source, "href", sourceHref);
  const repoName = typeof task.repo === "string" ? task.repo.split(/[\\/]/).filter(Boolean).pop() : "";
  setText(r.repo, repoName || "");
  setAttr(r.repo, "title", task.repo || "");

  const attempts = Number(task.attempts) || 0;
  setText(r.attempts, attempts ? plural(attempts, "attempt", "attempts") : "");
  show(r.attempts, attempts > 0);
  separate(r.attempts.parentNode);

  /* A held task's note gains whatever the operator said it is waiting on,
     since the queue cannot express a dependency between two tasks and this
     is the one place that reason survives. */
  const noteText = task.hold_reason && meta.note
    ? `${meta.note} Waiting on: ${task.hold_reason}`
    : meta.note || (task.hold_reason ? `Waiting on: ${task.hold_reason}` : "");
  setText(r.note, noteText);
  show(r.note, Boolean(noteText));

  setText(r.error, task.last_error || "");
  show(r.error, Boolean(task.last_error));

  const full = task.instruction || "";
  const instructionBox = r.instruction.querySelector(".instruction");
  if (instructionBox.dataset.forTask !== task.id) {
    instructionBox.dataset.forTask = task.id;
    renderMd(instructionBox, task.instruction_md);
  }
  show(r.instruction, full.trim() !== (task.title || "").trim() && full !== "");

  const runs = Array.isArray(task.runs) ? task.runs : [];
  const latest = runs.length ? runs[runs.length - 1] : null;
  if (latest) {
    setAttr(r.runLink, "href", `#/runs/${latest}`);
    setText(r.runLink, `Run ${shortId(latest)}`);
  }
  show(r.runLink, Boolean(latest));

  /* A task reads `done` the moment its run reaches a terminal success, and
     `ready` is one of those - the winner passed the gate but was never merged,
     because the run was configured not to. Side by side that looked like the
     Queue and the Runs page disagreeing, and it hid the fact that there is
     still something to land. Joined from the runs already loaded, so this
     costs no request and says nothing when the run is too old to be in the
     list. */
  const run = latest ? (state.runs || []).find((x) => x.id === latest) : null;
  const outcome = run && status === "done" && run.status !== "merged"
    ? `run ended ${run.status}  nothing merged it`
    : "";
  setText(r.outcome, outcome);
  show(r.outcome, Boolean(outcome));
  separate(r.outcome.parentNode);

  /* Priority only ever changes something for a task the loop could still
     claim; a running task has already left that pool (see
     `Task::set_priority`'s doc), so the buttons are disabled rather than
     left to round-trip a 4xx. */
  const priorityNow = Number(task.priority) || 0;
  r.priorityDown.disabled = status === "running";
  r.priorityUp.disabled = status === "running";
  setAttr(r.priorityDown, "aria-label", `Lower priority of ${task.title || task.id}`);
  setAttr(r.priorityUp, "aria-label", `Raise priority of ${task.title || task.id}`);
  r.priorityDown.onclick = () => changePriority(task.id, priorityNow - 1);
  r.priorityUp.onclick = () => changePriority(task.id, priorityNow + 1);

  const editable = status === "queued" || status === "held";
  r.editBtn.disabled = !editable;
  setAttr(
    r.editBtn,
    "title",
    editable ? "" : "Only a queued or held task's instruction can be edited.",
  );
  r.editBtn.onclick = () => openTaskEdit(task);
  show(r.editBtn, status !== "done");

  renderTaskHoldBox(row, task);
  renderTaskDoneBox(row, task);

  /* Two-step delete: first tap arms, second tap sends the DELETE request.
     Cancel takes the position of the initial button and receives focus. */
  clear(r.deleteBox);
  const armed = row.dataset.armedDelete === "1";
  if (armed) {
    const cancel = el("button", {
      class: "btn btn-quiet",
      type: "button",
      text: "Cancel",
      onclick: () => {
        row.dataset.armedDelete = "";
        updateTaskCard(row, task);
      },
    });
    const confirm = el("button", {
      class: "btn btn-quiet",
      type: "button",
      text: "Delete now",
      onclick: () => deleteTask(task.id, row),
    });
    r.deleteBox.append(
      el("div", { class: "stakes-confirm" },
        el("p", { class: "stakes-warn", text: "Deletes the task file. Its id, who filed it, and any run history go with it and cannot be recovered." }),
        el("div", { class: "stakes-row" }, cancel, confirm),
      ),
    );
    requestAnimationFrame(() => cancel.focus({ preventScroll: true }));
  } else {
    const del = el("button", {
      class: "btn btn-quiet",
      type: "button",
      text: "Delete…",
      disabled: status === "running",
      onclick: () => {
        row.dataset.armedDelete = "1";
        updateTaskCard(row, task);
      },
    });
    setAttr(del, "aria-label", `Delete task ${task.title || task.id}`);
    r.deleteBox.append(del);
  }
}

/* Hold takes an optional reason, so unlike release it is not a single tap:
   the first tap opens a short text field rather than acting immediately,
   the same two-step shape delete already uses but for input instead of
   confirmation. Release stays one tap - there is nothing to ask it. */
function renderTaskHoldBox(row, task) {
  const r = row.refs;
  const status = String(task.status_str || task.status || "");
  clear(r.holdBox);
  if (status === "done") return;

  if (status === "held") {
    const release = el("button", {
      class: "btn btn-quiet",
      type: "button",
      text: "Release",
      onclick: () => mutateTask(task.id, "release", release),
    });
    setAttr(release, "aria-label", `Release task ${task.title || task.id}`);
    r.holdBox.append(release);
    return;
  }

  if (row.dataset.armedHold === "1") {
    const reasonInput = el("input", {
      type: "text",
      placeholder: "What is this waiting on? (optional)",
    });
    const cancel = el("button", {
      class: "btn btn-quiet",
      type: "button",
      text: "Cancel",
      onclick: () => {
        row.dataset.armedHold = "";
        updateTaskCard(row, task);
      },
    });
    const confirm = el("button", {
      class: "btn btn-quiet",
      type: "button",
      text: "Hold",
      onclick: () => holdTask(task.id, reasonInput.value, row, confirm),
    });
    r.holdBox.append(
      el("div", { class: "stakes-confirm" },
        reasonInput,
        el("div", { class: "stakes-row" }, cancel, confirm),
      ),
    );
    requestAnimationFrame(() => reasonInput.focus({ preventScroll: true }));
  } else {
    const hold = el("button", {
      class: "btn btn-quiet",
      type: "button",
      text: "Hold…",
      disabled: status === "running",
      onclick: () => {
        row.dataset.armedHold = "1";
        updateTaskCard(row, task);
      },
    });
    setAttr(hold, "aria-label", `Hold task ${task.title || task.id}`);
    r.holdBox.append(hold);
  }
}

async function holdTask(id, reason, row, button) {
  const label = button.textContent;
  button.disabled = true;
  setText(button, "");
  try {
    await postJson(API.hold(id), reason.trim() ? { reason: reason.trim() } : undefined);
    ok();
    announce(`Task ${shortId(id)} held.`);
    row.dataset.armedHold = "";
    await loadQueue();
  } catch (error) {
    setText(button, label);
    button.disabled = false;
    fail(`Could not hold task ${shortId(id)}: ${error.message}`);
  }
}

/* Done and Delete both clear a task off the backlog, and are the two things
   an operator could tap for "I am finished with this" without reading
   closely - so the confirm text carries the difference, in the same tone
   Delete's already does: one keeps the record, one removes it. */
function renderTaskDoneBox(row, task) {
  const r = row.refs;
  const status = String(task.status_str || task.status || "");
  clear(r.doneBox);
  if (status === "done") return;

  if (row.dataset.armedDone === "1") {
    const cancel = el("button", {
      class: "btn btn-quiet",
      type: "button",
      text: "Cancel",
      onclick: () => {
        row.dataset.armedDone = "";
        updateTaskCard(row, task);
      },
    });
    const confirm = el("button", {
      class: "btn btn-quiet",
      type: "button",
      text: "Yes, mark done",
      onclick: () => doneTask(task.id, row, confirm),
    });
    r.doneBox.append(
      el("div", { class: "stakes-confirm" },
        el("p", { class: "hint", text: "Marks the task finished. Its id, who filed it, and its run history are kept — nothing is deleted." }),
        el("div", { class: "stakes-row" }, cancel, confirm),
      ),
    );
    requestAnimationFrame(() => cancel.focus({ preventScroll: true }));
  } else {
    const done = el("button", {
      class: "btn btn-quiet",
      type: "button",
      text: "Mark done…",
      onclick: () => {
        row.dataset.armedDone = "1";
        updateTaskCard(row, task);
      },
    });
    setAttr(done, "aria-label", `Mark task ${task.title || task.id} done`);
    r.doneBox.append(done);
  }
}

async function doneTask(id, row, button) {
  const label = button.textContent;
  button.disabled = true;
  setText(button, "");
  try {
    await postJson(API.doneTask(id));
    ok();
    announce(`Task ${shortId(id)} marked done.`);
    row.dataset.armedDone = "";
    await loadQueue();
  } catch (error) {
    setText(button, label);
    button.disabled = false;
    fail(`Could not mark task ${shortId(id)} done: ${error.message}`);
  }
}

async function changePriority(id, priority) {
  try {
    await postJson(API.priority(id), { priority });
    ok();
    announce(`Task ${shortId(id)} priority set to ${priority}.`);
    await loadQueue();
  } catch (error) {
    fail(`Could not change priority of task ${shortId(id)}: ${error.message}`);
  }
}

async function deleteTask(id, row) {
  try {
    await deleteReq(API.deleteTask(id));
    ok();
    announce(`Task ${shortId(id)} removed.`);
    await loadQueue();
  } catch (error) {
    if (row) {
      row.dataset.armedDelete = "";
      const task = (state.queue || []).find((t) => t.id === id);
      if (task) updateTaskCard(row, task);
    }
    fail(`Could not delete task ${shortId(id)}: ${error.message}`);
  }
}

async function mutateTask(id, action, button) {
  const label = button.textContent;
  button.disabled = true;
  setText(button, "\u2026");
  try {
    await postJson(action === "hold" ? API.hold(id) : API.release(id));
    ok();
    announce(`Task ${shortId(id)} ${action === "hold" ? "held" : "released"}.`);
    await loadQueue();
  } catch (error) {
    setText(button, label);
    button.disabled = false;
    fail(`Could not ${action} task ${shortId(id)}: ${error.message}`);
  }
}

/* ---- queue: grouping into sections ------------------------------------- *
 * The flat, priority-then-recency list stops being readable once a few
 * dozen tasks pile up (in practice: mostly `held`), so it is split into what
 * an operator actually wants to see first: what's running, what's next,
 * what's parked, what's finished. `queued` and `failed` share a section
 * because both are `TaskStatus::runnable` in src/queue.rs - the loop could
 * pick up either next - and the card's own chip/tone/error already tell them
 * apart, so a second section would only duplicate that distinction. */
const QUEUE_SECTIONS = [
  { key: "running", label: "Running", defaultOpen: true },
  { key: "upnext", label: "Up next", defaultOpen: true },
  { key: "held", label: "Held", defaultOpen: false },
  { key: "done", label: "Done", defaultOpen: false },
];

function queueSection(task) {
  const status = String(task.status_str || task.status || "");
  if (status === "running") return "running";
  if (status === "queued" || status === "failed") return "upnext";
  if (status === "held") return "held";
  return "done";
}

/* Section order preserved from QUEUE_SECTIONS; task order within a section
   preserved from the order tasks arrived in, which is /api/queue's own
   priority-then-recency order. */
function groupQueueBySection(tasks) {
  const bySection = new Map(QUEUE_SECTIONS.map((s) => [s.key, []]));
  for (const task of tasks) bySection.get(queueSection(task)).push(task);
  return bySection;
}

function createQueueSection(def) {
  return createSection(def, state.queueCollapsed, QUEUE_COLLAPSE_KEY);
}

function updateQueueSection(node, tasks) {
  setText(node.refs.count, plural(tasks.length, "task", "tasks"));
  syncList(node.refs.list, tasks, (t) => t.id, createTaskCard, updateTaskCard);
}

function syncQueueSections(root, bySection) {
  syncSections(root, QUEUE_SECTIONS, bySection, createQueueSection, updateQueueSection);
}

function renderQueue() {
  const sectionsRoot = $("queue-sections");
  const tasks = state.queue;

  if (tasks === null) {
    setText($("queue-count"), "Loading\u2026");
    return;
  }

  const runnable = tasks.filter((t) => {
    const status = t.status_str || t.status;
    return status === "queued" || status === "failed";
  }).length;
  const held = tasks.filter((t) => (t.status_str || t.status) === "held").length;
  const parts = [`${plural(tasks.length, "task", "tasks")}`];
  if (runnable) parts.push(`${runnable} runnable`);
  if (held) parts.push(`${held} held`);
  setText($("queue-count"), tasks.length === 0 ? "Nothing waiting" : parts.join(", "));

  show($("queue-empty"), tasks.length === 0);
  syncQueueSections(sectionsRoot, groupQueueBySection(tasks));
  /* The strip's wording depends on how many tasks are runnable, so it is
     re-rendered from the queue rather than only from health: "off, with two
     tasks waiting" has to appear the moment the second one is filed. */
  renderLoop();
}

/* ---- questions --------------------------------------------------------- *
 * An agent inside a run can stop and ask the owner something, and the run
 * parks until it is answered. That makes an open question the only state in
 * this product where nothing anywhere is making progress and no timeout will
 * rescue it: the machine is burning nothing and going nowhere until a human
 * taps. So the question is put in front of the operator from wherever they
 * are — a band above every view, a count on the nav item and in the document
 * title — and the controls to answer it are rendered in place, because a
 * question you have to navigate somewhere else to answer is a question that
 * waits until morning.
 */
const openQuestions = () => (state.questions || []).filter((q) => q.status === "open");
const openFor = (runId) => openQuestions().filter((q) => q.run === runId);

/* Of the open questions, the ones that actually need the owner right now:
   not the ones the owner has already talked back on and is waiting on the
   agent's `magi ask --thread` reply to. `status` cannot tell the two apart -
   see `Question.waiting_on_agent` - which is exactly why this is a separate
   filter from `openQuestions` rather than a tweak to it: `openQuestions` is
   still what the Questions page counts as "blocking a run", and a round trip
   is still blocking, just not on the owner. */
const needsOwnerQuestions = () => openQuestions().filter((q) => q.waiting_on_agent !== true);

/* Until /api/questions has answered, health's own count is what is known.
   `questions_needs_owner` is health's version of the same filter - see
   `ask::Questions::count_needs_owner` - so the ask bar, the nav badge and the
   title agree with the sharper truth from the moment /api/questions lands. */
function needsOwnerCount() {
  return state.questions === null
    ? Number(state.health && state.health.questions_needs_owner) || 0
    : needsOwnerQuestions().length;
}

function sortQuestions(list) {
  return list.slice().sort((a, b) => {
    const rank = (ASK_ORDER[a.status] ?? 3) - (ASK_ORDER[b.status] ?? 3);
    return rank || (Date.parse(b.asked_at) || 0) - (Date.parse(a.asked_at) || 0);
  });
}

/* RunSummary.waiting is one revision behind an answer the operator has just
   given. Once the questions are loaded they are the sharper truth: a run with
   no open question is not parked, whatever the summary still says. This is
   what makes answering read as immediate instead of as a round trip. */
function isWaiting(run) {
  if (!run.waiting) return false;
  return state.questions === null || openFor(run.id).length > 0;
}

/* ---- markdown ----------------------------------------------------------- *
 * Parsing markdown happens once, server-side (`magi::md`), which hands back a
 * tree of typed nodes rather than a string of HTML. What follows is the one
 * and only place this client turns that tree into DOM, with createElement and
 * textContent exactly as everywhere else — there is no second reader of
 * markdown syntax in this file, and no innerHTML anywhere in it. A run's
 * instruction, a standing chat's agent turn and a question's detail all go
 * through `renderMd`; nothing here re-derives structure from the raw string
 * the way the old hand-rolled reader did. */

/* One markdown node to one DOM node. The server already refused to build a
   `link`/`image` node for anything it would be unsafe to render (see
   `magi::md::normalize_link`/`normalize_image`), so this never has to
   inspect a URL itself — it only has to trust the shape it was handed. */
function buildMd(node) {
  switch (node && node.type) {
    case "paragraph":
      return el("p", {}, (node.children || []).map(buildMd));
    case "heading": {
      const level = Math.min(6, Math.max(1, Number(node.level) || 1));
      return el(`h${level}`, {}, (node.children || []).map(buildMd));
    }
    case "bullet_list":
      return el("ul", {}, (node.items || []).map(buildMd));
    case "ordered_list":
      return el("ol", { start: node.start && node.start !== 1 ? node.start : null },
        (node.items || []).map(buildMd));
    case "list_item":
      if (node.checked === null || node.checked === undefined) {
        return el("li", {}, (node.children || []).map(buildMd));
      }
      return el("li", { class: "task" },
        el("input", { type: "checkbox", checked: Boolean(node.checked), disabled: true }),
        (node.children || []).map(buildMd));
    case "block_quote":
      return el("blockquote", {}, (node.children || []).map(buildMd));
    case "thematic_break":
      return el("hr");
    case "code_block":
      return el("pre", { "data-lang": node.lang || null }, el("code", { text: node.code || "" }));
    case "code":
      return el("code", { text: node.code || "" });
    case "emphasis":
      return el("em", {}, (node.children || []).map(buildMd));
    case "strong":
      return el("strong", {}, (node.children || []).map(buildMd));
    case "strikethrough":
      return el("s", {}, (node.children || []).map(buildMd));
    case "link":
      return el("a", { href: node.href, target: "_blank", rel: "noopener noreferrer" },
        (node.children || []).map(buildMd));
    case "image":
      return el("img", { src: node.src, alt: node.alt || "", loading: "lazy" });
    case "table":
      return buildMdTable(node);
    case "soft_break":
      return document.createTextNode(" ");
    case "line_break":
      return el("br");
    case "text":
      return document.createTextNode(node.value ?? "");
    default:
      return document.createTextNode("");
  }
}

function buildMdTable(node) {
  const rows = Array.isArray(node.rows) ? node.rows : [];
  const row = (cells) => el("tr", {}, (Array.isArray(cells) ? cells : []).map((cell) =>
    el(cell.header ? "th" : "td",
      { "data-align": cell.align && cell.align !== "none" ? cell.align : null },
      (cell.children || []).map(buildMd))));
  const head = rows.length ? el("thead", {}, row(rows[0])) : null;
  const body = el("tbody", {}, rows.slice(1).map(row));
  return el("div", { class: "table-scroll" }, el("table", {}, head, body));
}

/* Replace `container`'s children with `nodes` (a server-sent markdown tree)
   turned into DOM. The one call every one of the five markdown surfaces in
   this UI goes through. */
function renderMd(container, nodes) {
  clear(container);
  append(container, (Array.isArray(nodes) ? nodes : []).map(buildMd));
}

/* ---- agent-authored panels --------------------------------------------- *
 * A question may hand over a whole HTML page instead of a paragraph: a table
 * of changed files, a coloured diff, an inline image. This client otherwise
 * refuses to put API data into markup at all, and that rule is not being
 * relaxed here — the panel is never parsed, inspected or inserted by this
 * document. It is fetched by the browser from its own endpoint into an
 * <iframe sandbox> carrying NO tokens, which means no script inside it runs,
 * it has no origin, and it can reach neither this document, nor its cookies,
 * nor localStorage. The endpoint additionally sends a Content-Security-Policy
 * of `default-src 'none'`, so nothing inside the frame can reach the network
 * either: a panel cannot beacon out through a remote image.
 *
 * Nothing below may add a sandbox token. `allow-scripts` would hand a
 * scriptable document to agent-authored HTML and `allow-same-origin` would
 * hand it this session; either one, and rendering the panel stops being
 * defensible. Everything the design wants is done in the frame's own CSS or
 * not at all.
 */

/* A tokenless frame is opaque in both directions, so a 404 inside it looks
   exactly like a rendered panel and would leave a silent blank hole where the
   evidence should be. The status is therefore asked for directly, once per
   question — the panel of a given question never changes — with HEAD, which
   the route answers identically to GET without sending the body. */
async function panelReachable(id) {
  if (state.panelOk.has(id)) return state.panelOk.get(id);
  let reachable = false;
  try {
    const res = await fetch(API.panel(id), { method: "HEAD", cache: "no-store" });
    reachable = res.ok;
  } catch {
    reachable = false;   /* the server went away; that is a failed panel too */
  }
  state.panelOk.set(id, reachable);
  return reachable;
}

/* The one place an iframe is built. `sandbox: ""` is deliberate and load
   bearing: `el` writes an empty attribute value for it, which is a sandbox
   with every capability withheld. An omitted `sandbox` attribute would be no
   sandbox at all, and any token inside it would give some of them back. */
function panelFrame(question, label) {
  return el("iframe", {
    src: API.panel(question.id),
    sandbox: "",
    referrerpolicy: "no-referrer",
    title: `${label}: ${question.summary || shortId(question.id)}`,
  });
}

function mountPanel(row, question) {
  const r = row.refs;
  clear(r.panelBox);

  const assets = Array.isArray(question.assets) ? question.assets : [];
  const full = el("button", {
    class: "btn btn-quiet", type: "button", text: "Full screen",
    "aria-label": `Open the panel full screen: ${question.summary || shortId(question.id)}`,
    onclick: () => openPanel(question),
  });
  const pending = el("p", { class: "frame-note", text: "Loading the panel\u2026" });
  r.panelBox.append(
    el("div", { class: "ask-panel-bar" },
      el("span", { class: "ask-panel-label", text: "Panel from the agent" }),
      full),
    pending,
  );

  panelReachable(question.id).then((reachable) => {
    if (row.dataset.panel !== question.id) return;   /* the row was reused */
    pending.remove();
    if (!reachable) {
      full.disabled = true;
      r.panelBox.append(el("div", { class: "frame-fail" },
        el("span", { text: "The agent attached a panel, but this server cannot serve it." }),
        el("span", { class: "hint", text: "The summary and the context above are all of it that survived \u2014 and the question is still answerable below." }),
      ));
      return;
    }
    r.panelBox.append(
      /* The sill: a fade at the bottom edge saying the panel continues past
         it. It is not the only signal, because a gradient is not a sentence
         and cannot be read out; the note below says the same thing in
         words. */
      el("div", { class: "frame-wrap" }, panelFrame(question, "Panel for"), el("div", { class: "frame-more" })),
      el("p", { class: "frame-note", text: `${assets.length ? `${plural(assets.length, "attachment", "attachments")} \u00b7 ` : ""}The panel scrolls inside this window. Full screen shows all of it.` }),
    );
  });
}

function renderPanel(row, question) {
  const r = row.refs;
  const wanted = question.panel === true;
  show(r.panelBox, wanted);
  if (!wanted) {
    if (row.dataset.panel) {
      row.dataset.panel = "";
      clear(r.panelBox);
    }
    return;
  }
  /* Mounted once. Re-mounting on every SSE tick would restart the frame's
     load and throw away wherever the operator had scrolled inside it. */
  if (row.dataset.panel === question.id) return;
  row.dataset.panel = question.id;
  mountPanel(row, question);
}

/* Full screen, which on a phone is where a unified diff becomes legible at
   all. The frame is built on open and dropped on close, so a dismissed
   dialog holds no live document and no decoded image. */
function openPanel(question) {
  const dialog = $("panel-full");
  setText($("panel-full-h"), question.summary || `Panel ${shortId(question.id)}`);
  const body = $("panel-full-body");
  clear(body);
  body.append(panelFrame(question, "Panel, full screen, for"));
  if (!dialog.open) dialog.showModal();
  requestAnimationFrame(() => $("panel-full-close").focus());
}

function closePanel() {
  const dialog = $("panel-full");
  if (dialog.open) dialog.close();
  clear($("panel-full-body"));
}

/* ---- merge approval ---------------------------------------------------- *
 * The land loop asks before it merges. Every other question in this product
 * chooses between two futures that can both be revisited; this one ends in a
 * merge, and magi has no way to take that back. So it does not get the same
 * card, and it does not get a single tap.
 */
function isMergeQuestion(question) {
  const choices = (Array.isArray(question.choices) ? question.choices : []).map((c) => String(c).toLowerCase());
  const pair = choices.includes("merge") && choices.includes("hold");
  return pair && (question.node === MERGE_NODE || choices.length === 2);
}

/* The answer is sent back exactly as the question spelt it, whatever case the
   node used, so the land loop's own comparison cannot miss it. */
function choiceNamed(question, want) {
  const choices = Array.isArray(question.choices) ? question.choices : [];
  return choices.find((choice) => String(choice).toLowerCase() === want) || want;
}

/* Two taps, not a timer. The first arms; the confirm row it reveals begins
   with the warning sentence and puts Cancel where the arm button just was, so
   the pixel under a thumb that was only scrolling is never the irreversible
   one. Nothing is disabled and nothing counts down, so an operator who means
   it is two deliberate taps away rather than made to wait. */
function renderStakes(row, question) {
  const r = row.refs;
  const armed = row.dataset.armed === "1";
  clear(r.stakes);

  r.stakes.append(el("p", { class: "stakes-what" },
    "Merging closes this run: the branch goes into ",
    el("span", { class: "ask-seat", text: "the base branch" }),
    " and magi has no undo for it.",
  ));

  if (armed) {
    const cancel = el("button", {
      class: "btn btn-quiet", type: "button", text: "Cancel",
      onclick: () => { row.dataset.armed = ""; renderStakes(row, question); },
    });
    r.stakes.append(el("div", { class: "stakes-confirm" },
      el("p", { class: "stakes-warn", text: "Tapping merge now merges it." }),
      el("div", { class: "stakes-row" },
        cancel,
        el("button", {
          class: "btn btn-gold", type: "button", text: "Yes, merge now",
          onclick: () => answerQuestion(question.id, { choice: choiceNamed(question, "merge") }, row),
        }),
      ),
    ));
    /* The caret lands on Cancel, never on the button that merges: a stray
       Enter after arming must not be the last thing that happens. */
    requestAnimationFrame(() => cancel.focus({ preventScroll: true }));
  } else {
    r.stakes.append(el("button", {
      class: "btn btn-gold stakes-arm", type: "button", text: "Merge this pull request\u2026",
      onclick: () => { row.dataset.armed = "1"; renderStakes(row, question); },
    }));
  }

  /* Hold is the safe answer, so it keeps a full target and a real edge
     instead of being demoted to a text link nobody can hit. */
  r.stakes.append(el("button", {
    class: "btn btn-quiet stakes-hold", type: "button", text: "Hold \u2014 do not merge",
    onclick: () => answerQuestion(question.id, { choice: choiceNamed(question, "hold") }, row),
  }));

  /* A land-approval question that also offered something else keeps those
     options: the two-step guard is for merge, not a reason to hide a choice
     the agent asked for. */
  for (const choice of Array.isArray(question.choices) ? question.choices : []) {
    const name = String(choice).toLowerCase();
    if (name === "merge" || name === "hold") continue;
    r.stakes.append(el("button", {
      class: "btn", type: "button", text: choice,
      onclick: () => answerQuestion(question.id, { choice }, row),
    }));
  }
}

/* ---- question card ----------------------------------------------------- *
 * Reconciled rather than rebuilt, because the free-text box may hold a
 * half-typed answer: an SSE tick arriving mid-sentence must not throw it
 * away. */
function createAskCard() {
  const chipSlot = el("span");
  const whenSlot = el("time", { class: "ask-when" });
  /* tabindex -1 so the ask bar can put the caret on the question it sent the
     operator here to answer, instead of on the top of the document. */
  const summary = el("h2", { class: "ask-summary", tabindex: "-1" });
  const runLink = el("a", { class: "ask-seat" });
  const node = el("span");
  const seat = el("span", { class: "ask-seat" });
  const where = el("div", { class: "ask-where" }, runLink, node, seat);
  const detail = el("div");
  const hint = el("p", { class: "hint" });
  const choices = el("div", { class: "choices" });
  const text = el("textarea", { rows: "4", "aria-label": "Your answer" });
  const send = el("button", { class: "btn btn-gold", type: "button", text: "Send answer" });
  const free = el("div", { class: "ask-free" }, text, send);
  const error = el("p", { class: "form-error", role: "alert" });
  const answerLabel = el("span", { class: "answer-label" });
  const answerText = el("p", { class: "answer-text" });
  const answer = el("div", { class: "answer" }, answerLabel, answerText);
  const note = el("p", { class: "panel-note" });
  /* Both are always present and hidden until they apply, so reconciling a
     card never has to move a node the operator is mid-tap on. */
  const band = el("p", { class: "stakes-band" });
  const panelBox = el("div", { class: "ask-panel" });
  const stakes = el("div", { class: "stakes" });

  /* The round trip: every turn after the question itself, oldest first, and a
     box to add one without deciding anything. */
  const thread = el("ol", { class: "ask-thread" });
  const waitingNote = el("p", { class: "ask-waiting" });
  const sayText = el("textarea", { rows: "3", "aria-label": "Ask the agent back" });
  const saySend = el("button", { class: "btn", type: "button", text: "Ask back" });
  const sayBox = el("div", { class: "ask-say" },
    el("label", { class: "ask-say-label", text: "Not ready to decide? Ask back instead:" }),
    sayText, saySend);

  const row = el("li", { class: "ask" },
    band,
    el("div", { class: "ask-top" }, chipSlot, whenSlot),
    /* The panel sits above the prose: when there is one, it is the case for
       the decision and the detail is the footnote. */
    summary, where, panelBox, detail, thread, hint, waitingNote, stakes, choices, free, sayBox, error, answer, note,
  );
  row.refs = { chipSlot, whenSlot, summary, runLink, node, seat, where, detail,
               hint, choices, text, send, free, error, answerLabel, answerText, answer, note,
               band, panelBox, stakes, thread, waitingNote, sayText, saySend, sayBox };
  return row;
}

function updateAskCard(row, question, { compact = false } = {}) {
  const r = row.refs;
  const status = String(question.status || "open");
  const open = status === "open";
  const choices = Array.isArray(question.choices) ? question.choices : [];

  /* The land loop's approval question. It is detected here rather than
     styled by the server, because the client is what knows the difference
     between a card that can be tapped through and one that cannot. */
  const merge = isMergeQuestion(question);
  setAttr(row, "data-state", status);
  setAttr(row, "data-stakes", merge ? "merge" : null);
  setText(r.band, merge
    ? (open ? "Irreversible \u00b7 this merges the pull request" : "Merge decision")
    : "");
  show(r.band, merge);

  const next = chip(status, QUESTION_STATUS);
  if (r.chipSlot.firstChild) r.chipSlot.firstChild.replaceWith(next);
  else r.chipSlot.append(next);

  const settledAt = !open && question.answered_at ? question.answered_at : question.asked_at;
  const at = when(settledAt);
  setText(r.whenSlot, `${!open && question.answered_at ? "answered" : "asked"} ${at.text}`);
  setAttr(r.whenSlot, "datetime", settledAt || null);
  setAttr(r.whenSlot, "title", at.title);

  setText(r.summary, question.summary || firstLine(question.detail) || `question ${shortId(question.id)}`);

  setAttr(r.runLink, "href", `#/runs/${question.run}`);
  setText(r.runLink, `run ${shortId(question.run)}`);
  show(r.runLink, Boolean(question.run) && !compact);
  setText(r.node, question.node ? `node ${question.node}` : "");
  show(r.node, Boolean(question.node));
  setText(r.seat, question.seat ? `seat ${question.seat}` : "");
  show(r.seat, Boolean(question.seat));
  separate(r.where);

  renderPanel(row, question);

  /* The round trip after the question itself: the owner talking back, the
     agent replying. `waiting_on_agent` names the one state nothing about
     `status` can - the question is still open, but nobody is waiting on the
     owner right now, they are waiting on the agent's `magi ask --thread`. */
  const waitingOnAgent = open && question.waiting_on_agent === true;
  setAttr(row, "data-waiting-agent", waitingOnAgent ? "1" : null);

  const turns = Array.isArray(question.thread) ? question.thread : [];
  const threadKey = String(turns.length);
  if (row.dataset.threadKey !== threadKey) {
    row.dataset.threadKey = threadKey;
    clear(r.thread);
    for (const turn of turns) {
      const isAgent = turn.who === "agent";
      const at = when(turn.at);
      r.thread.append(el("li", { class: "ask-turn", "data-who": isAgent ? "agent" : "operator" },
        el("span", { class: "ask-turn-who", text: isAgent ? "Agent" : "You" }),
        el("time", { class: "ask-turn-when", datetime: turn.at, title: at.title, text: at.text }),
        el("p", { class: "ask-turn-body", text: turn.body || "" }),
      ));
    }
  }
  show(r.thread, turns.length > 0);

  setText(r.waitingNote, waitingOnAgent
    ? "Waiting for the agent to reply. There is nothing to decide until it does."
    : "");
  show(r.waitingNote, waitingOnAgent);

  r.saySend.onclick = () => sayToQuestion(question.id, r.sayText.value, row);
  show(r.sayBox, open);
  r.sayText.disabled = waitingOnAgent;
  r.saySend.disabled = waitingOnAgent;

  /* The detail is immutable for a given question, so it is parsed once. An
     open question shows it outright — it is the case for the decision. A
     settled one folds it away, so the record does not push the next open
     question off a 390px screen. */
  const detail = typeof question.detail === "string" ? question.detail.trim() : "";
  const key = `${open ? "open" : "settled"}:${detail.length}`;
  if (row.dataset.detailKey !== key) {
    row.dataset.detailKey = key;
    clear(r.detail);
    if (detail) {
      const body = el("div", { class: "md" });
      renderMd(body, question.detail_md);
      r.detail.append(open
        ? body
        : el("details", { class: "advanced" }, el("summary", { text: "Context" }), body));
    }
  }
  show(r.detail, detail !== "");

  /* The choice set is keyed with the treatment as well, so a question that
     turns out to be a merge approval cannot keep a row of plain buttons. */
  const choiceKey = `${merge ? "merge" : "plain"}:${choices.join("\u0000")}`;
  if (row.dataset.choiceKey !== choiceKey) {
    row.dataset.choiceKey = choiceKey;
    row.dataset.armed = "";
    clear(r.choices);
    clear(r.stakes);
    if (merge) {
      renderStakes(row, question);
    } else {
      for (const choice of choices) {
        r.choices.append(el("button", {
          class: "btn", type: "button", text: choice,
          onclick: () => answerQuestion(question.id, { choice }, row),
        }));
      }
    }
  }
  r.send.onclick = () => answerQuestion(question.id, { text: r.text.value }, row);

  setText(r.hint, !open || waitingOnAgent
    ? ""
    : merge
      ? "Read the panel, then decide. Nothing merges until you say so twice."
      : choices.length
        ? "Pick one. The run resumes as soon as you do."
        : "No options were offered \u2014 answer in your own words.");
  show(r.hint, open && !waitingOnAgent);
  show(r.stakes, open && merge);
  show(r.choices, open && !merge && choices.length > 0);
  show(r.free, open && choices.length === 0);
  show(r.error, open && !r.error.hidden && r.error.textContent !== "");

  // While the agent has not replied yet, deciding is not an option: the
  // controls stay visible - the owner can still see what was on offer - but
  // disabled, with `waitingNote` above saying why.
  r.text.disabled = waitingOnAgent;
  r.send.disabled = waitingOnAgent;
  for (const btn of r.choices.querySelectorAll("button")) btn.disabled = waitingOnAgent;
  for (const btn of r.stakes.querySelectorAll("button")) btn.disabled = waitingOnAgent;

  const given = question.answer && typeof question.answer === "object" ? question.answer : null;
  const value = given
    ? typeof given.choice === "string" ? given.choice : typeof given.text === "string" ? given.text : ""
    : "";
  if (value) {
    const decided = when(question.answered_at);
    setText(r.answerLabel, `Decided ${decided.text}`);
    setAttr(r.answerLabel, "title", decided.title);
    setText(r.answerText, value);
  }
  show(r.answer, Boolean(value));

  setText(r.note, status === "abandoned"
    ? "The run ended before this was answered, so nothing acted on it."
    : row.dataset.raced === "1"
      ? "This was answered elsewhere while you had it open. The recorded answer is above."
      : "");
  show(r.note, r.note.textContent !== "");
}

/* A 409 is not a failure worth a dialog: it means the operator answered from
   the terminal, or a second phone got there first. What matters is the answer
   that was actually recorded, so the list is refetched and the question is
   shown as settled with a line saying why it changed under them. */
async function answerQuestion(id, body, row) {
  const r = row.refs;
  /* Only the answer controls are locked while the answer is in flight. The
     panel's own controls are not part of the decision, and one of them is
     deliberately disabled when the panel failed to load — re-enabling it
     here would offer a full-screen view of something that is not there. */
  const buttons = [...row.querySelectorAll("button")].filter((b) => !b.closest(".ask-panel"));
  const value = typeof body.choice === "string" ? body.choice : String(body.text || "");

  if (!value.trim()) {
    setText(r.error, "An answer cannot be empty.");
    show(r.error, true);
    r.text.focus();
    return;
  }

  show(r.error, false);
  for (const button of buttons) button.disabled = true;

  try {
    reflectQuestion(await postJson(API.answer(id), body));
    announce(`Answered: ${value.trim()}`);
    ok();
  } catch (error) {
    if (error.status === 409) {
      row.dataset.raced = "1";
      announce("That question had already been answered.");
      await loadQuestions();
      return;
    }
    setText(r.error, error.message);
    show(r.error, true);
  }
  for (const button of buttons) button.disabled = false;
}

/* Talk back without deciding anything: `POST /api/questions/{id}/say`, the
   phone's half of the round trip `magi ask --thread` completes from the
   agent's side. Same 409 handling as `answerQuestion` - answered or abandoned
   from elsewhere between the list and the tap reads as settled, not as an
   error the operator has to parse. */
async function sayToQuestion(id, text, row) {
  const r = row.refs;
  const value = String(text || "").trim();
  if (!value) {
    r.sayText.focus();
    return;
  }

  r.sayText.disabled = true;
  r.saySend.disabled = true;
  try {
    reflectQuestion(await postJson(API.questionSay(id), { body: value }));
    r.sayText.value = "";
    announce("Sent. Waiting for the agent to reply.");
    ok();
  } catch (error) {
    if (error.status === 409) {
      row.dataset.raced = "1";
      announce("That question was already settled.");
      await loadQuestions();
      return;
    }
    setText(r.error, error.message);
    show(r.error, true);
    r.sayText.disabled = false;
    r.saySend.disabled = false;
  }
}

/* Show the answer without waiting for the stream to confirm it, including in
   the runs list: the run stops reading as blocked-on-you the moment it stops
   being blocked on you. */
function reflectQuestion(question) {
  if (!question || typeof question !== "object" || !question.id) return;
  state.questions = sortQuestions([
    question,
    ...(state.questions || []).filter((q) => q.id !== question.id),
  ]);
  renderQuestions();
  renderAskBar();
  renderRuns();
  if (state.route.name === "run" && state.detail.run) renderRunDetail();
}

/* ---- ask bar and indicators -------------------------------------------- */

/* The band never renders when there is nothing to answer. A permanent "no
   questions" strip would train the operator to look straight past the place a
   real one appears, which is the one failure this feature cannot survive. */
function renderAskBar() {
  const bar = $("ask-bar");
  const count = needsOwnerCount();
  const open = needsOwnerQuestions();

  show(bar, count > 0);
  renderIndicators(count);
  if (count === 0) return;

  setText(bar.querySelector(".ask-bar-count"), count === 1
    ? "An agent is waiting on your decision"
    : `${count} agents are waiting on your decision`);

  /* The oldest one is quoted, because it is the one that has been blocking
     longest; the list is newest-first, so that is the last of them. */
  const oldest = open.length ? open[open.length - 1] : null;
  const line = bar.querySelector(".ask-bar-summary");
  setText(line, oldest ? oldest.summary || "" : "");
  show(line, Boolean(oldest && oldest.summary));
}

function renderIndicators(count) {
  for (const id of ["ask-badge-rail", "ask-badge-dock"]) {
    const badge = $(id);
    setText(badge, count > 99 ? "99+" : String(count));
    show(badge, count > 0);
  }
  for (const link of document.querySelectorAll('[data-nav="questions"]')) {
    setAttr(link, "aria-label", count > 0 ? `Questions, ${count} unanswered` : "Questions");
  }
  renderTitle();
}

/* The count rides on the document title as well, because a phone with the
   deck open in a background tab shows the title in the tab strip and in the
   app switcher — which is the only notification channel this UI has. */
function renderTitle() {
  const count = needsOwnerCount();
  const base = state.route.name === "queue"
    ? "Backlog \u2014 magi"
    : state.route.name === "questions"
      ? "Questions \u2014 magi"
      : state.route.name === "talks"
        ? "Chat \u2014 magi"
        : state.route.name === "talk"
          ? `Chat ${shortId(state.route.id)} \u2014 magi`
          : state.route.name === "run"
            ? `Run ${shortId(state.route.id)} \u2014 magi`
            : "magi \u2014 observation deck";
  document.title = count > 0 ? `(${count}) ${base}` : base;
}

function renderQuestions() {
  const list = $("questions-list");
  const questions = state.questions;

  if (questions === null) {
    setText($("questions-count"), "Loading\u2026");
    return;
  }

  const open = openQuestions().length;
  const settled = questions.length - open;
  setText($("questions-count"), questions.length === 0
    ? "Nothing asked yet"
    : open === 0
      ? `nothing open \u00b7 ${plural(settled, "decision on record", "decisions on record")}`
      : [`${plural(open, "question is blocking a run", "questions are blocking runs")}`,
         settled ? `${settled} on record` : null].filter(Boolean).join(" \u00b7 "));

  show($("questions-empty"), questions.length === 0);
  syncList(list, questions, (q) => q.id, createAskCard, (row, q) => updateAskCard(row, q));
}

/* The operator followed the band here to answer one specific thing; leaving
   the caret at the top of the document would make them find it again. */
function focusFirstAsk() {
  requestAnimationFrame(() => {
    const first = $("questions-list").querySelector('.ask[data-state="open"] .ask-summary');
    if (first) first.focus({ preventScroll: true });
  });
}

/* When the standing chat's agent times out, fails or runs out of quota, the
   server still records the exchange and writes the failure as an agent turn
   whose body begins with `magi: `. That is magi speaking, not the model, and
   it must not be read as an answer to the operator's question — so it is
   drawn as a third kind of turn. */
const MAGI_PREFIX = "magi: ";
function turnWho(turn) {
  if (turn.who === "agent" && String(turn.body || "").startsWith(MAGI_PREFIX)) return "system";
  return turn.who === "operator" ? "operator" : "agent";
}

/* ---- one conversation -------------------------------------------------- */
function createTurnRow() {
  const who = el("span", { class: "turn-who" });
  const body = el("div", { class: "turn-body" });
  const attachments = el("div", { class: "turn-attachments" });
  const at = el("time", { class: "turn-at" });
  const row = el("li", { class: "turn" }, who, body, attachments, at);
  row.refs = { who, body, attachments, at };
  return row;
}

function attachmentUrl(conversationId, att) {
  return API.talkAttachment(conversationId, att.id);
}

function updateTurnRow(row, item) {
  const r = row.refs;
  const turn = item.turn;
  const kind = turnWho(turn);
  const body = String(turn.body || "");

  setAttr(row, "data-who", kind);
  setText(r.who, kind === "operator" ? "You" : kind === "system" ? "magi" : "Agent");

  /* A turn never changes once it is on disk, so its body is built once. The
     agent's is markdown prose, already parsed server-side, and is rendered as
     nodes, never as markup: the rule that no API data is ever assigned as
     HTML holds everywhere outside the sandboxed panel frame, and a model that
     writes a script tag into a fence has to see the characters of one. */
  const key = `${kind}:${body.length}`;
  if (row.dataset.turnKey !== key) {
    row.dataset.turnKey = key;
    clear(r.body);
    if (kind === "agent") {
      const div = el("div", { class: "md" });
      renderMd(div, item.md);
      r.body.append(div);
    } else {
      r.body.append(el("p", {
        class: "turn-text",
        text: kind === "system" ? body.slice(MAGI_PREFIX.length) : body,
      }));
    }
  }

  /* Images already attached to this turn - distinct from the pending row the
     composer shows before Send, and rebuilt only when the set actually
     changes, on the same append-only reasoning the body gets above. */
  const atts = Array.isArray(turn.attachments) ? turn.attachments : [];
  const attKey = atts.map((a) => a.id).join(",");
  if (r.attachments.dataset.attKey !== attKey) {
    r.attachments.dataset.attKey = attKey;
    clear(r.attachments);
    for (const att of atts) {
      const url = attachmentUrl(item.conversationId, att);
      const name = String(att.name || "attachment");
      const thumb = el("button", {
        class: "turn-thumb", type: "button",
        "aria-label": `Open ${name} at full size`,
        onclick: () => showAttachment(url, name),
      }, el("img", { src: url, alt: "", loading: "lazy" }));
      r.attachments.append(thumb);
    }
  }

  const at = when(turn.at);
  setText(r.at, at.text);
  setAttr(r.at, "datetime", turn.at || null);
  setAttr(r.at, "title", at.title);
}

/* Full size, in the same dialog shell `openPanel` uses for a question's
   panel - a plain same-origin `<img>` here rather than a sandboxed iframe,
   since `web::attachment_response` already serves this from a closed
   content-type whitelist with `nosniff` and there is no agent-authored
   markup to contain. */
function showAttachment(url, name) {
  const dialog = $("attachment-view");
  const img = $("attachment-view-img");
  setText($("attachment-view-h"), name || "Attachment");
  img.src = url;
  img.alt = name || "";
  if (!dialog.open) dialog.showModal();
}

function closeAttachmentView() {
  const dialog = $("attachment-view");
  if (dialog.open) dialog.close();
}

/* Shared by the talk composer's own attachment queue below - one counter is
   enough since only one composer is ever active at a time. */
let nextLocalAttachmentId = 1;

/* Scroll the page so the last turn's top sits just below the sticky header.
   The header (.top) uses position:sticky;top:0, so scrollIntoView would hide
   the first line behind it. We account for its height with scroll-margin-top
   set via JS on the target element, using getBoundingClientRect for a
   reliable measurement regardless of safe-area insets or zoom level.
   `containerId` is always "talk-turns", the standing chat's transcript. */
function scrollToLastTurn(containerId) {
  const turns = $(containerId);
  if (!turns.children.length) return;
  const last = turns.lastElementChild;
  const header = document.querySelector(".top");
  const gap = header ? Math.ceil(header.getBoundingClientRect().height) + 4 : 0;
  last.style.scrollMarginTop = `${gap}px`;
  const motion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
  last.scrollIntoView({ behavior: motion ? "auto" : "smooth", block: "start" });
}

/* ---- standing chat ------------------------------------------------------ *
 * A conversation that stays open, for questions, investigation and thinking
 * out loud between tasks. Opening one takes no agent turn, because there is
 * nothing yet to answer (see `talk::begin`'s doc); a turn here can run for
 * `talk::TURN_TIMEOUT`, since the agent is expected to run commands and read
 * their output rather than answer from what it already knows.
 */
const talkTurns = (talk) => (talk && Array.isArray(talk.turns) ? talk.turns : []);
const talkTurnsMd = (talk) => (talk && Array.isArray(talk.turn_bodies_md) ? talk.turn_bodies_md : []);

/* What names a conversation before it has a title of its own: the first
   thing the operator said, if anything has been said yet. */
function talkOpener(talk) {
  const first = talkTurns(talk).find((turn) => turn.who === "operator");
  return first ? String(first.body || "") : "";
}

/* Open first, then newest first - the same ordering `Talks::list` uses on
   the server: what the operator is still using belongs above what they are
   done with. Sorting on `updated_at` instead would lift a conversation to
   the top on every agent reply, rearranging the list under the operator's
   finger - so position is identity, and a closed conversation does not jump
   to the top of the list the moment it is closed. */
function sortTalks(list) {
  return list.slice().sort((a, b) => {
    const rank = (a.status === "open" ? 0 : 1) - (b.status === "open" ? 0 : 1);
    const started = (talk) => Date.parse(talk.created_at) || 0;
    return rank || started(b) - started(a);
  });
}

function createTalkCard() {
  const chipSlot = el("span");
  const thinking = el("span", { class: "tag", "data-tone": "blue", text: "thinking…" });
  const whenSlot = el("time", { class: "card-when" });
  const title = el("h2", { class: "card-title" });
  const agent = el("span", { class: "repo" });
  const turns = el("span");
  const tasks = el("span", { class: "win" });
  const meta = el("div", { class: "card-meta" }, agent, turns, tasks);
  const last = el("p", { class: "card-event" });

  const card = el("a", { class: "card" },
    el("div", { class: "card-top" }, chipSlot, thinking, whenSlot),
    title, meta, last,
  );
  const row = el("li", {}, card);
  row.refs = { card, chipSlot, thinking, whenSlot, title, agent, turns, tasks, last };
  return row;
}

function updateTalkCard(row, talk) {
  const r = row.refs;
  const status = String(talk.status || "open");
  const turns = talkTurns(talk);
  const tone = toneOf(status, TALK_STATUS);

  r.card.setAttribute("href", `#/chat/${talk.id}`);
  setAttr(r.card, "data-tone", tone);
  setAttr(row, "data-tone", tone);

  const next = chip(status, TALK_STATUS);
  if (r.chipSlot.firstChild) r.chipSlot.firstChild.replaceWith(next);
  else r.chipSlot.append(next);
  show(r.thinking, talkIsThinking(talk));

  const at = when(talk.updated_at || talk.created_at);
  setText(r.whenSlot, at.text);
  setAttr(r.whenSlot, "datetime", talk.updated_at || talk.created_at);
  setAttr(r.whenSlot, "title", `updated ${at.title}`);

  setText(r.title, firstLine(talkOpener(talk)) || `conversation ${shortId(talk.id)}`);
  setText(r.agent, talk.agent || "");
  show(r.agent, Boolean(talk.agent));
  setText(r.turns, plural(turns.length, "turn", "turns"));
  const tasks = Array.isArray(talk.tasks) ? talk.tasks.length : 0;
  setText(r.tasks, tasks ? plural(tasks, "task filed", "tasks filed") : "");
  show(r.tasks, tasks > 0);
  separate(r.turns.parentNode);

  const tail = turns.length ? turns[turns.length - 1] : null;
  setText(r.last, tail && tail.who === "agent" ? firstLine(tail.body) : "");
  show(r.last, Boolean(tail && tail.who === "agent"));
}

function renderTalks() {
  const list = $("talks-list");
  const talks = state.talks;
  renderTalkIndicators();

  if (talks === null) {
    setText($("talks-count"), "Loading…");
    return;
  }

  const open = talks.filter((t) => t.status === "open").length;
  setText($("talks-count"), talks.length === 0
    ? "No conversations yet"
    : open ? `${plural(open, "conversation open", "conversations open")}` : "nothing open");

  show($("talks-empty"), talks.length === 0);
  syncList(list, sortTalks(talks), (t) => t.id, createTalkCard, updateTalkCard);
}

/* The rail and dock carry the same count as Questions' badges: conversations
   this server currently reports as thinking. The accessible name says what
   the bare numeral means. */
function renderTalkIndicators() {
  const count = (state.talks || []).filter(talkIsThinking).length;
  for (const id of ["talk-badge-rail", "talk-badge-dock"]) {
    const badge = $(id);
    setText(badge, count > 99 ? "99+" : String(count));
    show(badge, count > 0);
  }
  for (const link of document.querySelectorAll('[data-nav="talks"]')) {
    setAttr(link, "aria-label", count > 0 ? `Chat, ${count} conversations thinking` : "Chat");
  }
}

/* A wait is newer than an overlapping list read. Keep its activity visible
   until a read that observed that same wait proves the server released it. */
function talkIsThinking(talk) {
  return Boolean(talk && (talk.thinking || state.talkWaits.has(talk.id)));
}

async function loadTalks() {
  /* A response started before a send cannot revoke the wait that send just
     created. Keep the per-talk generation that was current when this read
     began, rather than comparing a late response with today's state. */
  const observedAt = Date.now();
  const observed = new Map([...state.talkWaits].map(([id, wait]) => [id, {
    generation: wait.generation, startedAt: observedAt,
  }]));
  try {
    const list = await getJson(API.talks);
    state.talks = Array.isArray(list) ? list : [];
    for (const talk of state.talks) trackTalkThinking(talk, observed.get(talk.id));
    renderTalks();
    ok();
  } catch (error) {
    fail(`Could not load conversations: ${error.message}`);
  }
}

/* Refresh one conversation. This must not decide which conversation is on
   screen - that is the router's job, in `applyRoute` - and the wait strip is
   settled from here whether or not the reply landed while the operator was
   looking at something else. */
async function loadTalk(id) {
  const wait = state.talkWaits.get(id);
  const observed = wait && { generation: wait.generation, startedAt: Date.now() };
  try {
    const talk = await getJson(API.talk(id));
    trackTalkThinking(talk, observed);
    if (state.talkDetail.id !== id) return;
    state.talkDetail.talk = talk;
    renderTalk();
    ok();
  } catch (error) {
    if (state.talkDetail.id === id) {
      fail(`Could not load conversation ${shortId(id)}: ${error.message}`);
    }
  }
}

/* A standing Chat can outlive dozens of tasks filed from it, so the panel
   defaults folded and this is what stays visible either way: not a count,
   but the breakdown an operator actually reads it for - whether what they
   filed is moving, stuck, or still waiting its turn. Order puts the states
   that want a human (running, held, failed) ahead of the quiet ones, and a
   zero count is left out rather than printed as "0 done". */
function talkTasksSummary(tasks) {
  const counts = { running: 0, held: 0, failed: 0, queued: 0, done: 0 };
  for (const task of tasks) {
    const status = String(task.status_str || task.status || "");
    if (status in counts) counts[status] += 1;
  }
  const parts = [`${tasks.length} filed`];
  for (const key of ["running", "held", "failed", "queued", "done"]) {
    if (counts[key]) parts.push(`${counts[key]} ${key}`);
  }
  return parts.join(" · ");
}

const TALK_TASKS_STORAGE_KEY = "magi.talkTasksOpen";

function renderTalkTasks(talk) {
  const panel = $("talk-tasks-panel");
  const tasks = Array.isArray(talk && talk.tasks) ? talk.tasks : [];
  show(panel, tasks.length > 0);
  if (tasks.length === 0) return;
  setText($("talk-tasks-count"), talkTasksSummary(tasks));
  syncList($("talk-tasks"), tasks, (t) => t.id, createTalkTaskRow, updateTalkTaskRow);

  /* Folded is the default for any conversation the operator hasn't touched
     this panel on before; once they open or close it here, that sticks by
     talk id so returning to the same standing Chat keeps their choice, but
     switching to a different one never inherits it. */
  const talkId = String(talk.id || "");
  if (panel.dataset.talkId !== talkId) {
    panel.dataset.talkId = talkId;
    panel.open = isSectionOpen(loadCollapsed(TALK_TASKS_STORAGE_KEY), talkId, false);
  }
}

function createTalkTaskRow() {
  const chipSlot = el("span");
  const title = el("span");
  const row = el("li", {}, chipSlot, title);
  row.refs = { chipSlot, title };
  return row;
}

function updateTalkTaskRow(row, task) {
  const r = row.refs;
  const status = String(task.status_str || task.status || "");
  const next = chip(status, TASK_STATUS);
  if (r.chipSlot.firstChild) r.chipSlot.firstChild.replaceWith(next);
  else r.chipSlot.append(next);
  setText(r.title, `${task.title || task.id} · ${shortId(task.id)}`);
}

function renderTalk() {
  const talk = state.talkDetail.talk;
  const wait = talk ? state.talkWaits.get(talk.id) : undefined;
  const busy = Boolean(wait) || Boolean(talk && talk.thinking);

  if (!talk) {
    setText($("talk-h"), "Loading conversation…");
    setText($("talk-meta"), "");
    clear($("talk-status"));
    clear($("talk-turns"));
    show($("talk-tasks-panel"), false);
    show($("talk-say"), false);
    show($("talk-closed"), false);
    show($("talk-close-go"), false);
    show($("talk-reopen-go"), false);
    show($("talk-wait"), false);
    clear($("talk-delete-box"));
    renderTalkThumbs();
    return;
  }

  const status = String(talk.status || "open");
  /* The operator's own message, shown immediately and held until the
     transcript on disk has grown past it - the ten-second re-read below
     replaces the whole conversation and would otherwise make the message
     the operator just sent vanish for the rest of the wait. */
  const pending = wait && wait.pending && talkTurns(talk).length <= wait.since
    ? [{ who: "operator", body: wait.pending.body, at: wait.pending.at }]
    : [];
  const turns = [...talkTurns(talk), ...pending];

  const head = $("talk-status");
  clear(head);
  head.append(chip(status, TALK_STATUS));

  setText($("talk-h"), firstLine(talkOpener(talk)) || `Conversation ${shortId(talk.id)}`);
  const started = when(talk.created_at);
  setText($("talk-meta"),
    `${shortId(talk.id)} · ${talk.agent || "agent"} · ${plural(turns.length, "turn", "turns")} · started ${started.text}`);
  setAttr($("talk-meta"), "title", `${talk.id}\nstarted ${started.title}`);

  const turnsMd = talkTurnsMd(talk);
  syncList(
    $("talk-turns"),
    turns.map((turn, i) => ({ turn, md: turnsMd[i], key: String(i), conversationId: talk.id })),
    (item) => item.key, createTurnRow, updateTurnRow,
  );

  /* Auto-scroll: the one-second tickTalkWaits tick makes this stricter than a
     one-shot render would need - turnCount must actually hold still across a
     render that changes nothing else, or the page would yank every second. */
  const turnCount = turns.length;
  const lastIsPending = wait && wait.pending
    && turns.length > 0 && turns[turns.length - 1].who === "operator"
    && turns[turns.length - 1].body === wait.pending.body;
  if (state.openingTalk) {
    state.openingTalk = false;
    if (turnCount > 0) requestAnimationFrame(() => scrollToLastTurn("talk-turns"));
  } else if (turnCount > state.prevTalkTurnCount && !lastIsPending) {
    requestAnimationFrame(() => scrollToLastTurn("talk-turns"));
  }
  state.prevTalkTurnCount = turnCount;

  renderTalkTasks(talk);

  const canSay = status === "open";
  show($("talk-say"), canSay);
  show($("talk-closed"), !canSay);
  show($("talk-close-go"), canSay);
  show($("talk-reopen-go"), !canSay);
  renderTalkThumbs();
  const uploading = talkAttachmentsBusy();
  $("f-talk-say").disabled = false;
  $("talk-send").disabled = uploading;
  setText($("talk-send"), uploading ? "Uploading…" : busy ? "Queue next" : "Send");
  renderTalkPending(talk);
  show($("talk-wait"), busy);
  renderTalkDelete(talk);
}

/* Pending is server data, not an optimistic browser-only message: it survives
   reload and shows an attachment count so an image can never disappear from
   the operator's understanding of what will be sent next. */
function renderTalkPending(talk) {
  const box = $("talk-pending");
  const text = String(talk.pending || "");
  const attachments = Array.isArray(talk.pending_attachments) ? talk.pending_attachments : [];
  const busy = Boolean(talk.thinking) || state.talkWaits.has(talk.id);
  clear(box);
  show(box, Boolean(text || attachments.length));
  if (!text && attachments.length === 0) return;
  append(box, [
    el("p", { class: "panel-note", text: "Queued for the next reply" }),
    text ? el("pre", { class: "talk-pending-text", text }) : null,
    attachments.length ? el("p", { class: "frame-note", text: `${plural(attachments.length, "attachment", "attachments")} queued` }) : null,
    !busy ? el("button", { class: "btn", type: "button", text: "Resume queued draft", onclick: resumeTalkPending }) : null,
    el("button", { class: "btn btn-quiet", type: "button", text: "Clear", onclick: clearTalkPending }),
    el("button", { class: "btn btn-quiet", type: "button", text: "Edit text", onclick: editTalkPending }),
  ]);
}

async function resumeTalkPending() {
  const id = state.talkDetail.id;
  const talk = state.talkDetail.talk;
  if (!id || !talk) return;
  try {
    const next = await postJson(API.talkPendingResume(id), {});
    if (state.talkDetail.id === id) {
      state.talkDetail.talk = next;
      trackTalkThinking(next);
      renderTalk();
    }
    announce("Queued draft resumed.");
    loadTalks();
  } catch (error) {
    if (error.status === 409) await loadTalk(id);
    talkError(`Could not resume the queued draft: ${error.message}`);
  }
}

async function editTalkPending() {
  const id = state.talkDetail.id;
  const talk = state.talkDetail.talk;
  if (!id || !talk) return;
  const expectedText = String(talk.pending || "");
  const expectedAttachments = Array.isArray(talk.pending_attachments)
    ? talk.pending_attachments.map((attachment) => attachment.id)
    : [];
  const text = window.prompt("Edit queued text", expectedText);
  if (text === null || text === expectedText) return;
  try {
    const next = await postJson(API.talkPendingEdit(id), { text, expected_text: expectedText, expected_attachments: expectedAttachments });
    if (state.talkDetail.id === id) {
      state.talkDetail.talk = next;
      trackTalkThinking(next);
      renderTalk();
    }
    announce("Queued text updated. Attachments are preserved.");
    loadTalks();
  } catch (error) {
    if (error.status === 409) await loadTalk(id);
    talkError(`Could not edit the queued message: ${error.message}`);
  }
}

async function clearTalkPending() {
  const id = state.talkDetail.id;
  const talk = state.talkDetail.talk;
  if (!id || !talk) return;
  const expectedText = String(talk.pending || "");
  const expectedAttachments = Array.isArray(talk.pending_attachments)
    ? talk.pending_attachments.map((attachment) => attachment.id)
    : [];
  try {
    const next = await postJson(API.talkPendingClear(id), { expected_text: expectedText, expected_attachments: expectedAttachments });
    if (state.talkDetail.id === id) {
      state.talkDetail.talk = next;
      renderTalk();
    }
    announce("Queued message cleared.");
    loadTalks();
  } catch (error) {
    if (error.status === 409) await loadTalk(id);
    talkError(`Could not clear the queued message: ${error.message}`);
  }
}

/* One timer services every busy conversation: it redraws the visible wait
   strip and refreshes all conversations every ten seconds as insurance when
   the change stream is unavailable. */
function tickTalkWaits() {
  const now = Date.now();
  for (const [id, wait] of state.talkWaits) {
    if (now - wait.lastPoll >= 10000) {
      wait.lastPoll = now;
      loadTalk(id);
    }
  }

  const box = $("talk-wait");
  const wait = state.talkDetail.id ? state.talkWaits.get(state.talkDetail.id) : undefined;
  if (!wait) {
    show(box, false);
    return;
  }
  const secs = Math.max(Math.round((now - wait.waitFrom) / 1000), 0);
  setText(box.querySelector(".waiting-text"), secs >= 90
    ? "Still working — a standing chat turn can run for several minutes while the agent investigates. Long, but not stuck."
    : "The agent is looking into it.");
  setText(box.querySelector(".waiting-secs"), `${secs}s`);
  show(box, true);
}

function beginTalkTurn(id, since, target, pending = null) {
  state.talkWaits.set(id, {
    since, target, pending, waitFrom: Date.now(), lastPoll: Date.now(),
    generation: nextTalkWaitGeneration++, confirmed: target === null, missingClaimSince: null,
  });
  if (!state.talkWaitTimer) state.talkWaitTimer = setInterval(tickTalkWaits, 1000);
  tickTalkWaits();
}

function endTalkTurn(id) {
  if (!state.talkWaits.has(id)) return;
  state.talkWaits.delete(id);
  if (state.talkDetail.id === id) show($("talk-wait"), false);
  if (state.talkWaits.size === 0 && state.talkWaitTimer) {
    clearInterval(state.talkWaitTimer);
    state.talkWaitTimer = null;
  }
}

/* A TalkView can arrive from this browser, another device, or after reload.
   A known local target is settled by transcript growth, never merely by a
   claim disappearing: guard release and the reply write are distinct events.
   `observed` identifies the wait a GET saw when it began, so an older false
   response cannot release a later send. Once a matching response confirmed
   the claim, one matching false only schedules suspicion: a second false
   from a GET begun after that suspicion proves the process lost the claim,
   so a restart cannot leave the composer stale forever. */
function trackTalkThinking(talk, observed) {
  const wait = state.talkWaits.get(talk.id);
  if (wait) {
    if (wait.target !== null && talkTurns(talk).length >= wait.target) endTalkTurn(talk.id);
    else if (observed && observed.generation === wait.generation && talk.thinking) {
      wait.confirmed = true;
      wait.missingClaimSince = null;
    } else if (!talk.thinking && observed && observed.generation === wait.generation
      && wait.confirmed) {
      if (wait.missingClaimSince !== null && observed.startedAt > wait.missingClaimSince) {
        endTalkTurn(talk.id);
      } else {
        wait.missingClaimSince = Date.now();
      }
    }
    return;
  }
  if (talk.thinking) beginTalkTurn(talk.id, talkTurns(talk).length, null);
}

function talkError(message) {
  const box = $("talk-error");
  setText(box, message || "");
  show(box, Boolean(message));
}

/* ---- talk composer attachments ------------------------------------------ *
 * Three ways an image reaches the file input - the picker, a paste, or a
 * drop, all wired in wire() below to attachTalkFiles() - and one thing that
 * happens next: every file is POSTed the moment it arrives, well before Send
 * is even tappable, so the thumbnail row has something to key on and a slow
 * mobile upload is visible as progress rather than as a silent wait right
 * before the tap that would have started it. `say` later carries only the
 * ids this minted; see `API.talkAttachmentPost` and `web::validate_attachment`
 * for what the server actually accepts - this side repeats none of that
 * whitelist and just shows whatever message a rejection carries.
 */
function talkAttachmentsBusy() {
  return state.talkAttachments.id === state.talkDetail.id
    && state.talkAttachments.items.some((item) => item.status === "uploading");
}

function resetTalkAttachments(id) {
  for (const item of state.talkAttachments.items) {
    if (item.previewUrl) URL.revokeObjectURL(item.previewUrl);
  }
  state.talkAttachments = { id, items: [] };
}

/* A send owns the completed uploads present at its click. Removing just those
   objects synchronously means a later click or attachment cannot reuse them,
   and a delayed 202 cannot erase the later draft. */
function takeTalkAttachments(id) {
  if (state.talkAttachments.id !== id) return [];
  const taken = state.talkAttachments.items.filter((item) => item.status === "done");
  state.talkAttachments.items = state.talkAttachments.items.filter((item) => item.status !== "done");
  return taken;
}

function releaseTalkAttachments(items) {
  for (const item of items) {
    if (item.previewUrl) URL.revokeObjectURL(item.previewUrl);
  }
}

function restoreTalkSubmission(id, text, attachments) {
  if (state.talkAttachments.id === id) {
    const known = new Set(state.talkAttachments.items.map((item) => item.localId));
    state.talkAttachments.items.unshift(...attachments.filter((item) => !known.has(item.localId)));
  }
  if (state.talkDetail.id !== id) return;
  const box = $("f-talk-say");
  if (!box.value) box.value = text;
  else if (text && box.value !== text) box.value = `${text}\n\n${box.value}`;
  renderTalk();
}

function renderTalkThumbs() {
  const box = $("talk-say-thumbs");
  const items = state.talkAttachments.id === state.talkDetail.id ? state.talkAttachments.items : [];
  clear(box);
  show(box, items.length > 0);
  for (const item of items) {
    const thumb = el("div", { class: "say-thumb" });
    if (item.status === "uploading") thumb.classList.add("is-uploading");
    if (item.status === "error") thumb.classList.add("is-failed");
    thumb.append(el("img", { src: item.previewUrl || "", alt: "" }));
    if (item.status === "uploading") {
      thumb.append(el("div", { class: "say-thumb-spinner" }, el("i", {})));
    }
    thumb.append(el("button", {
      class: "say-thumb-remove", type: "button",
      "aria-label": `Remove ${item.name || "image"}`,
      onclick: () => removeTalkAttachment(item.localId),
    }, svg(
      "svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", "stroke-width": "2.5", "stroke-linecap": "round" },
      svg("path", { d: "M6 6l12 12M18 6L6 18" }),
    )));
    box.append(thumb);
  }

  const uploading = items.filter((item) => item.status === "uploading").length;
  const status = $("talk-say-upload-status");
  setText(status, uploading > 0 ? `Uploading ${plural(uploading, "image", "images")}` : "");
  show(status, uploading > 0);
}

function removeTalkAttachment(localId) {
  const items = state.talkAttachments.items;
  const at = items.findIndex((item) => item.localId === localId);
  if (at < 0) return;
  const [item] = items.splice(at, 1);
  if (item.previewUrl) URL.revokeObjectURL(item.previewUrl);
  renderTalk();
}

async function attachTalkFiles(files) {
  const id = state.talkDetail.id;
  if (!id) return;
  if (state.talkAttachments.id !== id) resetTalkAttachments(id);

  const images = [...files].filter((file) => file.type.startsWith("image/"));
  if (images.length === 0) return;

  for (const file of images) {
    // The operator can navigate to a different conversation between two
    // files of the same batch - every `await` below is a point where
    // `applyRoute` can swap `state.talkAttachments` out from under this loop.
    if (state.talkAttachments.id !== id) break;

    const localId = nextLocalAttachmentId++;
    const item = {
      localId,
      previewUrl: URL.createObjectURL(file),
      name: file.name || "image",
      status: "uploading",
      serverId: null,
    };
    state.talkAttachments.items.push(item);
    renderTalk();

    try {
      const att = await postBytes(API.talkAttachmentPost(id), file, file.name);
      item.status = "done";
      item.serverId = att.id;
    } catch (error) {
      // Kept, not dropped: "error" is what lets renderTalkThumbs show the
      // failed thumbnail instead of it vanishing without a trace.
      item.status = "error";
      if (state.talkAttachments.id === id) {
        talkError(`Could not attach ${item.name}: ${error.message}`);
      }
    }
    if (state.talkAttachments.id === id) renderTalk();
  }
}

/* Opening a talk takes no agent turn - see `talk::begin`'s doc - so this is
   as fast as any other write and needs no waiting state of its own. */
async function startTalk() {
  const go = $("talk-start-go");
  go.disabled = true;
  setText(go, "Opening…");
  try {
    const talk = await postJson(API.talks, {});
    state.talks = sortTalks([talk, ...(state.talks || []).filter((t) => t.id !== talk.id)]);
    state.talkDetail = { id: talk.id, talk };
    trackTalkThinking(talk);
    renderTalks();
    announce("Conversation opened.");
    location.hash = `#/chat/${talk.id}`;
    ok();
  } catch (failure) {
    fail(`Could not open a conversation: ${failure.message}`);
  } finally {
    go.disabled = false;
    setText(go, "Start a conversation");
  }
}

async function sendTalkTurn(event) {
  event.preventDefault();
  const id = state.talkDetail.id;
  const box = $("f-talk-say");
  const text = box.value;
  if (!id || talkAttachmentsBusy()) return;
  const attachments = state.talkAttachments.id === id
    ? state.talkAttachments.items.filter((item) => item.status === "done")
    : [];
  if (!text.trim() && attachments.length === 0) {
    talkError("Say something, or attach an image, first.");
    box.focus();
    return;
  }

  talkError("");
  const submissionAttachments = takeTalkAttachments(id);
  const before = talkTurns(state.talkDetail.talk).length;
  const ownsTurn = !state.talkWaits.has(id) && !(state.talkDetail.talk && state.talkDetail.talk.thinking);
  if (ownsTurn) beginTalkTurn(id, before, before + 2, { body: text, at: new Date().toISOString() });
  box.value = "";
  renderTalk();
  $("talk-wait").scrollIntoView({ block: "nearest" });

  try {
    /* 202, for exactly the reason `sendTurn` documents: a turn here can run
       for the whole of `talk::TURN_TIMEOUT`, and holding a connection open
       that long is not a thing to ask a phone to do. The reply arrives
       through the change stream's `talks_rev`, or the ten-second insurance
       in `tickTalkWait`. */
    const queued = await postJson(API.talkSay(id), {
      text,
      attachments: submissionAttachments.map((item) => item.serverId),
    });
    /* This 202 was received after the local wait was created, so it is the
       matching observation that makes a later fresh false useful for
       recovering from a process restart. */
    const wait = state.talkWaits.get(id);
    trackTalkThinking(queued, wait && { generation: wait.generation, startedAt: Date.now() });
    releaseTalkAttachments(submissionAttachments);
    if (state.talkDetail.id === id) {
      state.talkDetail.talk = queued;
      renderTalk();
      announce("Sent. The agent is answering.");
    }
    loadTalks();
    ok();
  } catch (error) {
    restoreTalkSubmission(id, text, submissionAttachments);
    if (ownsTurn) endTalkTurn(id);
    talkError(`The message may not have been sent: ${error.message}`);
    await loadTalk(id);
  }
}

async function closeTalk() {
  const id = state.talkDetail.id;
  const button = $("talk-close-go");
  if (!id) return;
  button.disabled = true;
  try {
    const talk = await postJson(API.talkClose(id), {});
    state.talkDetail.talk = talk;
    renderTalk();
    await loadTalks();
    announce("Conversation closed.");
    ok();
  } catch (error) {
    fail(`Could not close the conversation: ${error.message}`);
  } finally {
    button.disabled = false;
  }
}

async function reopenTalk() {
  const id = state.talkDetail.id;
  const button = $("talk-reopen-go");
  if (!id) return;
  button.disabled = true;
  try {
    const talk = await postJson(API.talkReopen(id), {});
    state.talkDetail.talk = talk;
    renderTalk();
    await loadTalks();
    announce("Conversation reopened.");
    ok();
  } catch (error) {
    fail(`Could not reopen the conversation: ${error.message}`);
  } finally {
    button.disabled = false;
  }
}

/* Armed by the talk's own id, the same two-step confirm `renderRunDelete`
   uses: comparing against `talk.id` rather than a plain boolean means
   navigating to a different conversation resets the confirm state for free,
   with no separate "leaving this view" hook to remember to call. */
let armedTalkDelete = null;
let armedTalkDeleteFocused = null;

function renderTalkDelete(talk) {
  const box = $("talk-delete-box");
  if (!box) return;
  clear(box);

  const armed = armedTalkDelete === talk.id;
  if (!armed) armedTalkDeleteFocused = null;
  if (armed) {
    const cancel = el("button", {
      class: "btn btn-quiet",
      type: "button",
      text: "Cancel",
      onclick: () => {
        armedTalkDelete = null;
        renderTalkDelete(talk);
      },
    });
    const confirm = el("button", {
      class: "btn btn-quiet",
      type: "button",
      text: "Yes, delete conversation",
      onclick: () => deleteTalk(talk.id),
    });
    box.append(
      el("div", { class: "stakes-confirm" },
        el("p", { class: "stakes-warn", text: "Deleting removes the whole conversation and its artifacts. This cannot be undone." }),
        el("div", { class: "stakes-row" }, cancel, confirm),
      ),
    );
    if (armedTalkDeleteFocused !== talk.id) {
      armedTalkDeleteFocused = talk.id;
      requestAnimationFrame(() => cancel.focus({ preventScroll: true }));
    }
  } else {
    box.append(
      el("button", {
        class: "btn btn-quiet",
        type: "button",
        text: "Delete conversation…",
        onclick: () => {
          armedTalkDelete = talk.id;
          renderTalkDelete(talk);
        },
      }),
    );
  }
}

async function deleteTalk(id) {
  try {
    await deleteReq(API.talkDelete(id));
    ok();
    announce("Conversation deleted.");
    armedTalkDelete = null;
    await loadTalks();
    location.hash = "#/chat";
  } catch (error) {
    armedTalkDelete = null;
    fail(`Could not delete the conversation: ${error.message}`);
    renderTalk();
  }
}

/* ---- landing ----------------------------------------------------------- *
 * After a run wins, the land loop opens a pull request and watches it. The
 * only thing the operator needs from this panel is whether it is their turn,
 * so every state below ends in a sentence that says so in words. */

/* `pr` is frozen on RunSummary; the detail payload is whatever the server
   chose to include, so the run is asked first and the list second. */
function landOf(run) {
  if (run.pr && typeof run.pr === "object") return run.pr;
  const summary = (state.runs || []).find((r) => r.id === run.id);
  return summary && summary.pr && typeof summary.pr === "object" ? summary.pr : null;
}

/* Red checks are not a verdict on the run: the loop answers them with another
   fixer round, and only becomes the operator's problem once the round budget
   is spent. Saying which of those it is, in words, is the part that does not
   depend on colour or on a glyph. */
function landNote(pr) {
  const rounds = Number(pr.rounds) || 0;
  const left = Math.max(rounds - (Number(pr.round) || 0), 0);
  if (pr.state === "merged") return "Merged. The land loop is finished with this run.";
  if (pr.state === "closed") return "The pull request was closed without merging. This one needs you.";
  if (pr.checks === "red") {
    return left > 0
      ? `Checks failed, so a fixer round is coming \u2014 ${plural(left, "round", "rounds")} of ${rounds} left. Nothing is needed from you.`
      : `Checks failed and all ${rounds} fix rounds are spent. This one needs you.`;
  }
  if (pr.checks === "pending") return "Waiting on the checks. Nothing is needed from you.";
  if (pr.checks === "green") return "Checks are green; the loop is taking it to merge.";
  return "The check state could not be read from the forge.";
}

function checksChip(pr) {
  const level = String(pr.checks || "unknown");
  const check = CHECKS[level] || CHECKS.unknown;
  return el("span", {
    class: "checks",
    "data-checks": level,
    "data-glyph": check.glyph,
    text: check.word,
  });
}

/* ---- run detail -------------------------------------------------------- */
function viable(candidate) {
  /* Candidate::viable is a method, so it is not on the wire; the rule it
     encodes is. */
  return !candidate.failed && !candidate.empty;
}

function renderRunDetail() {
  const run = state.detail.run;
  const report = state.detail.report;

  $("run-report").dataset.wrap = state.wrap ? "1" : "0";

  if (!run) {
    setText($("run-h"), "Loading run\u2026");
    setText($("run-meta"), "");
    clear($("run-status"));
    /* Both of these are about a specific run, and a question belonging to a
       different one is not merely stale, it is wrong. */
    show($("run-ask-panel"), false);
    show($("run-land-panel"), false);
    show($("run-active-panel"), false);
    /* The fab and its sheet stay reachable across this route (see
       applyRoute), so a switch to a different run id \u2014 the daemon strip's
       currentRunLink, or back/forward between two run pages \u2014 must not leave
       the previous run's Resume/Fold/Delete buttons sitting in the sheet:
       their onclick closures still carry the old id, and Delete says itself
       "cannot be undone". Clearing here, before the new run's data arrives,
       is what used to happen for free when the whole panel was hidden. */
    clear($("run-actions-box"));
    clear($("run-delete-box"));
    setText($("run-report"), report === null ? "Loading\u2026" : report);
    return;
  }

  /* The detail payload carries the run's own status; the list carries the
     derived `waiting`. Prefer whichever says the run is parked, because that
     is the state the operator has to act on. */
  const summary = (state.runs || []).find((r) => r.id === run.id);
  const parkedNow = Boolean(summary && isWaiting(summary)) || openFor(run.id).length > 0;
  const status = parkedNow ? "waiting" : String(run.status || "");
  const meta = RUN_STATUS[status] || {};

  const head = $("run-status");
  clear(head);
  head.append(chip(status, RUN_STATUS));
  const parkedAt = parkedNow ? (openFor(run.id)[0] || {}).node || null : null;
  const rail = PHASES.includes(status) || parkedAt
    ? phaseRail(status, parkedAt, activeNote(run))
    : null;
  if (rail) head.append(rail);
  if (meta.note) head.append(el("p", { class: "card-note", text: meta.note }));

  setText($("run-h"), firstLine(run.instruction) || shortId(run.id));

  const created = when(run.created_at);
  const updated = when(run.updated_at);
  const repoName = typeof run.repo === "string" ? run.repo.split(/[\\/]/).filter(Boolean).pop() : "";
  setText($("run-meta"),
    `${shortId(run.id)} \u00b7 ${repoName} \u00b7 ${run.base_branch || ""} \u00b7 started ${created.text} \u00b7 updated ${updated.text}`);
  setAttr($("run-meta"), "title", `${run.id}\n${run.repo || ""}\nstarted ${created.title}\nupdated ${updated.title}`);

  const instructionEl = $("run-instruction");
  if (instructionEl.dataset.forRun !== run.id) {
    instructionEl.dataset.forRun = run.id;
    renderMd(instructionEl, run.instruction_md);
  }

  renderAsks(run);
  renderLand(run);
  renderActive(run);
  renderVerdict(run);
  renderCandidates(run);
  renderReviews(run);
  renderQuota(run);
  renderTimeline(run);
  renderRunActions(run);
  renderRunDelete(run);

  setText($("run-report"), report === null ? "Loading\u2026" : report);
}

let armedRunDelete = null;
/* Mirrors armedFoldFocused: only the render that just armed the delete
   confirmation moves focus to Cancel, not every periodic redraw after it. */
let armedRunDeleteFocused = null;

function runDeleteReason(run) {
  /* `run.live` is whether a daemon's heartbeat currently claims this run
     (`daemon::is_working_on`), the same check the delete route itself gates
     on. A non-terminal `status` alone is not proof of that: a killed process
     leaves it stuck (`implementing`, say) forever with nobody left to answer
     for it, and blocking delete on `status` read that dead run as still in
     flight right alongside a genuinely running one. */
  if (run.live) {
    return "This run is still in flight and cannot be deleted.";
  }
  if (unfolded(run)) {
    return "Fold the candidate worktrees first \u2014 the button below does it.";
  }
  return null;
}

/* Whether any candidate still holds a worktree and a branch. Delete refuses
   these, and folding is how an operator clears them; before there was a
   button, the deck told a phone to go and run `magi fold` in a terminal. */
function unfolded(run) {
  const candidates = Array.isArray(run.candidates) ? run.candidates : [];
  return candidates.some((c) => !c.folded);
}

let armedFold = null;
/* Which armed run last received the focus-on-arm below, so a periodic
   re-render (loadRun runs every 5s) does not steal focus back to Cancel on
   every redraw — only the render that actually just armed does. */
let armedFoldFocused = null;
let foldBusy = null;
let resumeBusy = null;

/* Fold and resume are opposites and share this row, so the copy has to be
   blunt about it: folding throws away the worktrees a resume would continue
   from. Resume is offered first for that reason. */
function renderRunActions(run) {
  const box = $("run-actions-box");
  if (!box) return;
  clear(box);

  const status = String(run.status || "");
  if (["stalled", "blocked"].includes(status)) {
    const busy = resumeBusy === run.id;
    const gone = !unfolded(run);
    box.append(
      el("div", { class: "stakes-confirm" },
        el("button", {
          class: "btn",
          type: "button",
          text: busy ? "Resuming\u2026" : "Resume this run",
          disabled: busy || gone,
          onclick: () => resumeRun(run.id),
        }),
        el("p", { class: "card-note", text: gone
          ? "The candidate worktrees are gone, so there is nothing left to continue from. File the task again instead."
          : "Carries on from where it stopped, re-asking only the seats that went missing. It spends agent calls." }),
      ),
    );
  }

  if (!unfolded(run)) return;

  if (armedFold === run.id) {
    const cancel = el("button", {
      class: "btn btn-quiet",
      type: "button",
      text: "Cancel",
      onclick: () => { armedFold = null; renderRunActions(run); },
    });
    box.append(
      el("div", { class: "stakes-confirm" },
        el("p", { class: "stakes-warn", text: "Folding removes this run's worktrees and branches. Anything not committed goes with them, and the run can no longer be resumed." }),
        el("div", { class: "stakes-row" },
          cancel,
          el("button", {
            class: "btn btn-quiet",
            type: "button",
            text: "Yes, fold worktrees",
            onclick: () => foldRun(run.id),
          }),
        ),
      ),
    );
    if (armedFoldFocused !== run.id) {
      armedFoldFocused = run.id;
      requestAnimationFrame(() => cancel.focus({ preventScroll: true }));
    }
  } else {
    armedFoldFocused = null;
    box.append(
      el("div", { class: "stakes-confirm" },
        el("button", {
          class: "btn btn-quiet",
          type: "button",
          text: foldBusy === run.id ? "Folding\u2026" : "Fold worktrees\u2026",
          disabled: foldBusy === run.id,
          onclick: () => { armedFold = run.id; renderRunActions(run); },
        }),
        el("p", { class: "card-note", text: "Frees the disk this run is holding, and is what the delete button is waiting for." }),
      ),
    );
  }
}

async function foldRun(id) {
  armedFold = null;
  foldBusy = id;
  try {
    const out = await postJson(API.foldRun(id));
    ok();
    const n = Number(out.removed_count || 0);
    announce(n > 0
      ? `Folded ${shortId(id)}: ${n} worktree${n === 1 ? "" : "s"} and branches removed.`
      : `Run ${shortId(id)} had nothing left to fold.`);
    closeRunActions();
    await loadRun(id);
  } catch (error) {
    /* The alert banner sits in normal flow, under the sheet's own top-layer
       backdrop, so it must close first or the failure is unreadable. */
    closeRunActions();
    fail(`Could not fold run ${shortId(id)}: ${error.message}`);
  } finally {
    foldBusy = null;
  }
}

async function resumeRun(id) {
  resumeBusy = id;
  try {
    await postJson(API.resumeRun(id));
    ok();
    announce(`Run ${shortId(id)} is being resumed. The card will follow it.`);
    closeRunActions();
    await loadRun(id);
  } catch (error) {
    closeRunActions();
    fail(`Could not resume run ${shortId(id)}: ${error.message}`);
  } finally {
    resumeBusy = null;
  }
}

function renderRunDelete(run) {
  const box = $("run-delete-box");
  if (!box) return;
  clear(box);

  const reason = runDeleteReason(run);
  if (reason) {
    const disabledBtn = el("button", {
      class: "btn btn-quiet",
      type: "button",
      text: "Delete run\u2026",
      disabled: true,
    });
    box.append(
      el("div", { class: "stakes-confirm" },
        disabledBtn,
        el("p", { class: "card-note", text: reason }),
      ),
    );
    return;
  }

  const armed = armedRunDelete === run.id;
  if (!armed) armedRunDeleteFocused = null;
  if (armed) {
    const cancel = el("button", {
      class: "btn btn-quiet",
      type: "button",
      text: "Cancel",
      onclick: () => {
        armedRunDelete = null;
        renderRunDelete(run);
      },
    });
    const confirm = el("button", {
      class: "btn btn-quiet",
      type: "button",
      text: "Yes, delete run now",
      onclick: () => deleteRun(run.id),
    });
    box.append(
      el("div", { class: "stakes-confirm" },
        el("p", { class: "stakes-warn", text: "Deleting removes all recorded state and artifacts. This cannot be undone." }),
        el("div", { class: "stakes-row" },
          cancel,
          confirm,
        ),
      ),
    );
    if (armedRunDeleteFocused !== run.id) {
      armedRunDeleteFocused = run.id;
      requestAnimationFrame(() => cancel.focus({ preventScroll: true }));
    }
  } else {
    box.append(
      el("button", {
        class: "btn btn-quiet",
        type: "button",
        text: "Delete run\u2026",
        onclick: () => {
          armedRunDelete = run.id;
          renderRunDelete(run);
        },
      }),
    );
  }
}

async function deleteRun(id) {
  try {
    await deleteReq(API.deleteRun(id));
    ok();
    announce(`Run ${shortId(id)} removed.`);
    armedRunDelete = null;
    closeRunActions();
    location.hash = "#/runs";
  } catch (error) {
    armedRunDelete = null;
    closeRunActions();
    fail(`Could not delete run ${shortId(id)}: ${error.message}`);
  }
}

/* Every question this run has ever asked, open ones first: the answered ones
   are the record of the decisions that shaped the work below. They are
   answerable right here, so arriving from the runs list is not a detour. */
function renderAsks(run) {
  const mine = (state.questions || []).filter((q) => q.run === run.id);
  show($("run-ask-panel"), mine.length > 0);
  if (mine.length === 0) return;

  const open = mine.filter((q) => q.status === "open").length;
  setText($("run-ask-title"), open > 0 ? "Waiting on you" : "Decisions");
  setText($("run-ask-count"), open > 0 ? `${open} open` : plural(mine.length, "on record", "on record"));
  syncList($("run-asks"), sortQuestions(mine), (q) => q.id, createAskCard,
    (row, q) => updateAskCard(row, q, { compact: true }));
}

function renderLand(run) {
  const pr = landOf(run);
  show($("run-land-panel"), Boolean(pr));
  if (!pr) return;

  const box = $("run-land");
  clear(box);
  // Same reasoning as the card link: an untrusted scheme is rendered as plain
  // text rather than as something tappable.
  const prHref = forgeUrl(pr.url);
  box.append(
    el("div", { class: "land-top" },
      prHref
        ? el("a", {
            class: "pr-link", href: prHref, title: prHref,
            target: "_blank", rel: "noopener noreferrer",
            text: `PR #${pr.number}`,
          })
        : el("span", { class: "ask-seat", text: `PR #${pr.number}` }),
      el("span", { class: "tag", "data-tone": PR_TONE[pr.state] || "ink", text: pr.state || "unknown" }),
      checksChip(pr),
    ),
    Number(pr.rounds) ? el("p", { class: "land-note", text: `Land round ${Number(pr.round) || 0} of ${pr.rounds}.` }) : null,
    roundRail(pr),
    el("p", { class: "land-note", text: landNote(pr) }),
  );
}

function firstLine(text) {
  if (typeof text !== "string") return "";
  for (const line of text.split("\n")) {
    const trimmed = line.trim();
    if (trimmed) return trimmed.length > 96 ? `${trimmed.slice(0, 95)}\u2026` : trimmed;
  }
  return "";
}

function renderVerdict(run) {
  const tally = run.tally;
  const panel = $("run-verdict");
  const candidates = Array.isArray(run.candidates) ? run.candidates : [];
  show(panel, Boolean(tally) || candidates.length > 0);
  if (!tally && candidates.length === 0) return;

  const converge = $("converge");
  clear(converge);
  /* A winner label alone does not mean a verdict. A run whose panel collapsed
     still records the one ranking it got, so the diamond is only drawn as
     decided when the quorum backs it. */
  const decided = Boolean(tally && tally.met_quorum);
  converge.append(convergeDiagram(candidates, tally ? tally.winner : null, decided));

  const facts = $("tally-facts");
  clear(facts);
  if (!tally) {
    facts.append(
      el("dt", { text: "Verdict" }),
      el("dd", { text: "Not reached yet." }),
    );
    return;
  }

  const first = tally.first_choice || {};
  const votes = Object.keys(first)
    .sort()
    .map((label) => `${label}: ${first[label]}`)
    .join("  \u00b7  ");

  const rows = [
    ["Winner", tally.winner
      ? `Candidate ${tally.winner}${decided ? "" : " \u2014 provisional only"}`
      : "\u2014"],
  ];
  /* `uncontested` means no panel was asked \u2014 a single viable candidate, or
     a review-only run. The panel/quorum/agreement rows below all describe a
     panel that sat, so showing them here (0 of 0 present, "still split" with
     nothing to split) would read as the same collapse a real stall produces. */
  if (tally.uncontested) {
    rows.push(["Judging", `Not needed \u2014 ${tally.uncontested}`]);
  } else {
    rows.push(
      ["First choices", votes || "\u2014"],
      ["Panel", `${Number(tally.present) || 0} of ${Number(tally.judges) || 0} present, quorum ${Number(tally.quorum) || 0}`],
      /* Quorum is the field that says whether the verdict is worth anything. */
      ["Quorum", tally.met_quorum ? "Met" : "NOT MET \u2014 the verdict is not trustworthy"],
      ["Agreement", tally.unanimous_final
        ? "Unanimous final vote"
        : `Split; ${plural(Number(tally.changed_votes) || 0, "judge", "judges")} moved`],
      ["Deliberated", tally.deliberated ? "Yes" : "No"],
    );
    if (tally.tie_break) rows.push(["Tie break", tally.tie_break]);
  }

  for (const [term, value] of rows) {
    facts.append(el("dt", { text: term }), el("dd", { text: value }));
  }
}

/* The mark, drawn from the real candidate list: independent bodies at the top,
   one gold verdict at the convergence point. The winner's stroke survives at
   full weight; the others recede, and a candidate that never produced work is
   dashed. `decided` is the quorum: without it the convergence point stays
   hollow, because a stalled run reached no verdict however its ranking read. */
function convergeDiagram(candidates, winner, decided) {
  const width = 320;
  const height = 132;
  const midX = width / 2;
  const knot = 96;
  const count = Math.max(candidates.length, 1);

  const labels = candidates.map((c) => c.label).filter(Boolean).join(", ");
  const root = svg("svg", {
    viewBox: `0 0 ${width} ${height}`,
    role: "img",
    "aria-label": candidates.length
      ? `${plural(candidates.length, "candidate", "candidates")} ${labels}${winner && decided ? `; ${winner} won` : winner ? `; ${winner} leads but the panel reached no quorum` : "; no verdict yet"}`
      : "No candidates yet",
  });

  const span = Math.min(96, (width - 68) / Math.max(count - 1, 1));
  const xs = candidates.map((_, i) => midX + (i - (count - 1) / 2) * span);

  candidates.forEach((candidate, i) => {
    const x = xs[i];
    const won = winner && candidate.label === winner && decided;
    const dead = !viable(candidate);
    const tone = candTone(i);
    const path = x === midX
      ? `M ${x} 44 L ${x} ${knot}`
      : `M ${x} 44 C ${x} ${knot - 22}, ${(x + midX) / 2} ${knot - 8}, ${midX} ${knot}`;

    root.append(svg("path", {
      d: path,
      fill: "none",
      stroke: tone,
      "stroke-width": won ? 5 : 2.5,
      "stroke-linecap": "round",
      "stroke-dasharray": dead ? "3 5" : null,
      opacity: won ? 1 : dead ? 0.35 : 0.55,
    }));
    root.append(svg("circle", {
      cx: x, cy: 26, r: 13,
      fill: dead ? "var(--sunk)" : tone,
      stroke: tone,
      "stroke-width": 2,
      "stroke-dasharray": dead ? "3 3" : null,
    }));
    root.append(svg("text", {
      x, y: 31,
      "text-anchor": "middle",
      fill: dead ? tone : "var(--surface)",
      text: candidate.label || "?",
    }));
  });

  if (winner && decided) {
    root.append(svg("rect", {
      x: midX - 11, y: knot - 11, width: 22, height: 22,
      transform: `rotate(45 ${midX} ${knot})`,
      fill: "var(--gold-line)",
    }));
    root.append(svg("path", {
      d: `M ${midX} ${knot + 16} L ${midX} ${height - 8}`,
      stroke: "var(--gold-line)", "stroke-width": 5, "stroke-linecap": "round",
    }));
  } else {
    /* No verdict: the convergence point is drawn hollow, so an unfinished or
       collapsed run does not display a decided diamond. */
    root.append(svg("rect", {
      x: midX - 10, y: knot - 10, width: 20, height: 20,
      transform: `rotate(45 ${midX} ${knot})`,
      fill: "none", stroke: "var(--line-2)", "stroke-width": 2, "stroke-dasharray": "3 3",
    }));
  }

  return root;
}

function renderCandidates(run) {
  const candidates = Array.isArray(run.candidates) ? run.candidates : [];
  show($("run-cands-panel"), candidates.length > 0);
  if (candidates.length === 0) return;

  const winner = run.tally ? run.tally.winner : null;
  const decided = Boolean(run.tally && run.tally.met_quorum);
  setText($("cand-count"), `${candidates.filter(viable).length} viable of ${candidates.length}`);

  const list = $("run-cands");
  clear(list);
  candidates.forEach((candidate, i) => {
    const dead = !viable(candidate);
    const facts = [];
    if (candidate.commits) facts.push(plural(candidate.commits, "commit", "commits"));
    if (candidate.files) facts.push(plural(candidate.files, "file", "files"));
    const took = seconds(candidate.duration_ms);
    if (took) facts.push(took);
    if (candidate.branch) facts.push(candidate.branch);

    list.append(el("li", {
      class: "cand",
      "data-winner": winner && candidate.label === winner && decided ? "1" : null,
      style: `--cand-tone: ${candTone(i)}`,
    },
      el("div", { class: "cand-head" },
        el("span", { class: "cand-label", text: candidate.label || "?" }),
        el("span", { class: "cand-agent", text: candidate.agent || "" }),
        winner && candidate.label === winner
          ? el("span", {
              class: "crown",
              "data-provisional": decided ? null : "1",
              text: decided ? "winner" : "provisional",
            })
          : null,
      ),
      facts.length ? numbers(facts) : null,
      dead
        ? el("p", { class: "card-note", text: candidate.failed || "Produced no change at all." })
        : null,
      candidate.summary ? el("p", { class: "cand-summary", text: candidate.summary }) : null,
      candidate.stat ? el("pre", { class: "stat", text: candidate.stat }) : null,
    ));
  });
}

/* `ReviewVote` on the wire: "approve" | "approve_with_findings" | "reject".
   Same three-colour scale a finding's severity gets, since a vote is exactly
   that kind of verdict — none, some, or stop. */
function voteTone(vote) {
  switch (vote) {
    case "approve": return "teal";
    case "approve_with_findings": return "gold";
    case "reject": return "rust";
    default: return null;
  }
}

function voteLabel(vote) {
  switch (vote) {
    case "approve": return "approve";
    case "approve_with_findings": return "approve w/ findings";
    case "reject": return "reject";
    default: return String(vote || "");
  }
}

function renderReviews(run) {
  /* On the wire this is Vec<ReviewRound>, each round holding the reviewers'
     records. */
  const rounds = Array.isArray(run.reviews) ? run.reviews : [];
  const gate = Array.isArray(run.gate) ? run.gate : [];
  show($("run-reviews-panel"), rounds.length > 0 || gate.length > 0);
  if (rounds.length === 0 && gate.length === 0) return;

  setText($("review-count"), rounds.length ? plural(rounds.length, "round", "rounds") : "gate only");

  const list = $("run-reviews");
  clear(list);

  for (const round of rounds) {
    const blocking = Number(round.blocking) || 0;
    const records = Array.isArray(round.reviews) ? round.reviews : [];

    const node = el("li", { class: "round" },
      el("div", { class: "round-head" },
        el("span", { class: "round-n", text: `Round ${round.round}` }),
        round.clean
          ? el("span", { class: "tag", "data-tone": "teal", text: "clean" })
          : el("span", { class: "tag", "data-tone": "rust", text: `${plural(blocking, "blocker", "blockers")}` }),
        round.verify_retried
          ? el("span", { class: "tag", "data-tone": "gold", text: "verify retried" })
          : null,
        round.e2e_deferred
          ? el("span", { class: "tag", "data-tone": "gold", text: "e2e deferred" })
          : null,
        round.verdict
          ? el("span", { class: "tag", "data-tone": voteTone(round.verdict), text: `verdict: ${voteLabel(round.verdict)}` })
          : null,
        round.vote_split
          ? el("span", { class: "tag", "data-tone": "gold", text: "votes split" })
          : null,
        round.head ? el("span", { class: "head-sha", title: "reviewed HEAD", text: String(round.head).slice(0, 7) }) : null,
        round.verified_head
          ? el("span", { class: "head-sha", title: "verified HEAD", text: `verified ${String(round.verified_head).slice(0, 7)}` })
          : null,
      ),
    );

    for (const record of records) {
      const findings = Array.isArray(record.findings) ? record.findings : [];
      node.append(el("div", { class: "reviewer" },
        el("p", {},
          el("span", { class: "reviewer-name", text: `reviewer ${record.reviewer} \u00b7 ${record.agent || ""}` }),
          record.vote
            ? el("span", { class: "tag", "data-tone": voteTone(record.vote), text: voteLabel(record.vote) })
            : null,
        ),
        record.failed ? el("p", { class: "card-note", text: record.failed }) : null,
        record.summary ? el("p", { class: "cand-summary", text: record.summary }) : null,
        findings.length ? el("div", { class: "findings" }, findings
          .slice()
          .sort((a, b) => (SEV_RANK[b.severity] || 0) - (SEV_RANK[a.severity] || 0))
          .map((finding) => el("div", { class: "finding", "data-sev": finding.severity },
            el("div", { class: "finding-top" },
              el("span", { class: "finding-sev", text: finding.severity || "" }),
              el("span", { class: "finding-title", text: finding.title || "" }),
              finding.id ? el("span", { class: "finding-id", text: finding.id }) : null,
            ),
            finding.file
              ? el("p", { class: "finding-where", text: `${finding.file}${finding.line ? `:${finding.line}` : ""}` })
              : null,
            finding.detail ? el("p", { class: "finding-detail", text: finding.detail }) : null,
          ))) : null,
      ));
    }

    // Reconsideration only ever has entries when the round's initial votes
    // split \u2014 an empty array here means the panel already agreed, same as
    // an empty judge `deliberation`.
    const reconsideration = Array.isArray(round.reconsideration) ? round.reconsideration : [];
    if (reconsideration.length) {
      node.append(el("div", { class: "reviewer" },
        el("p", {}, el("span", { class: "reviewer-name", text: "reconsideration" })),
        el("div", { class: "findings" }, reconsideration.map((rv) =>
          el("div", { class: "finding" },
            el("div", { class: "finding-top" },
              el("span", { class: "finding-id", text: `reviewer ${rv.reviewer}` }),
              rv.vote
                ? el("span", { class: "tag", "data-tone": voteTone(rv.vote), text: voteLabel(rv.vote) })
                : el("span", { class: "tag", "data-tone": "rust", text: "no revote" }),
            ),
            rv.reason ? el("p", { class: "finding-detail", text: rv.reason }) : null,
            rv.failed ? el("p", { class: "card-note", text: rv.failed }) : null,
          ))),
      ));
    }

    const e2e = Array.isArray(round.e2e) ? round.e2e : [];
    if (e2e.length) {
      node.append(commandList("Verification", e2e));
    } else if (round.e2e_deferred) {
      // Empty on purpose here, never "nothing to report": an empty `e2e`
      // also means "not configured" elsewhere, and the two must not look
      // the same — a deferred round has not passed and has not failed.
      node.append(el("p", { class: "card-note", text: round.e2e_defer_reason
        ? `Verification deferred to the fixer: ${round.e2e_defer_reason}`
        : "Verification deferred to the fixer" }));
    }

    if (round.fix) {
      const fix = round.fix;
      const addressed = Array.isArray(fix.addressed) ? fix.addressed : [];
      const rejected = Array.isArray(fix.rejected) ? fix.rejected : [];
      node.append(el("div", { class: "reviewer" },
        el("p", {}, el("span", { class: "reviewer-name", text: `fix \u00b7 ${fix.agent || ""}` })),
        // A lost adoption report is not "0 addressed / 0 declined": that
        // literal reads as every finding reviewed and rejected, when the
        // truth is magi never learned what the fixer did with them.
        fix.failed
          ? numbers([fix.committed ? "committed" : "no commit"])
          : numbers([
              `${addressed.length} addressed`,
              `${rejected.length} declined`,
              fix.committed ? "committed" : "no commit",
            ]),
        fix.failed ? el("p", { class: "card-note", text: `adoption report lost: ${fix.failed}` }) : null,
        fix.notes ? el("p", { class: "cand-summary", text: fix.notes }) : null,
        rejected.length ? el("div", { class: "findings" }, rejected.map((r) =>
          el("div", { class: "finding" },
            el("div", { class: "finding-top" },
              el("span", { class: "finding-id", text: r.id || "" }),
              el("span", { class: "finding-title", text: "declined" }),
            ),
            r.why ? el("p", { class: "finding-detail", text: r.why }) : null,
          ))) : null,
      ));
    }

    list.append(node);
  }

  if (gate.length) list.append(el("li", { class: "round" }, commandList("Gate", gate)));
}

function commandList(heading, commands) {
  return el("div", { class: "reviewer" },
    el("p", {}, el("span", { class: "reviewer-name", text: heading })),
    el("div", { class: "findings" }, commands.map((command) => {
      /* CommandOutcome::ok is a method; the wire has the exit code. */
      const passed = command.code === 0;
      return el("div", { class: "finding", "data-sev": passed ? null : "blocker" },
        el("div", { class: "finding-top" },
          el("span", { class: "tag", "data-tone": passed ? "teal" : "rust", text: passed ? "pass" : "fail" }),
          el("span", { class: "finding-where", text: command.command || "" }),
          el("span", { class: "finding-id", text: command.code === null || command.code === undefined ? "timeout" : `exit ${command.code}` }),
        ),
        !passed && command.output_tail
          ? el("pre", { class: "stat", text: command.output_tail })
          : null,
      );
    })),
  );
}

/* One line for the phase rail's label: which seat(s) the current phase is
   still waiting on, or null when nothing is out. Seat identifiers only —
   never an agent id, since a judge or reviewer seat is blind. */
function activeNote(run) {
  const active = run.active && typeof run.active === "object" ? run.active : {};
  const seats = Object.keys(active).sort();
  if (seats.length === 0) return null;
  if (!run.live) return `${plural(seats.length, "seat", "seats")} left mid-answer by a dead process`;
  return seats.length === 1
    ? `${seats[0]} has not answered yet`
    : `${plural(seats.length, "seat", "seats")} have not answered yet (${seats.join(", ")})`;
}

/* Seats still mid-answer, for the panel between "Landing" and "Verdict" —
   the same place in the column as the ask panel's reasoning: while a seat is
   still out, nothing below it that depends on the panel is going to change.

   `run.active` is keyed by seat, not by candidate or judge number, and on
   purpose carries no agent id: a judge or reviewer seat is blind, and the
   identifier alone ("judge-2", "review-1") is what the operator needs to
   answer "which seat is quiet" without this view becoming a second place
   that could leak who is behind it mid-run. `run.live` says whether a daemon
   is actually still asking these seats anything right now, or whether they
   are a leftover from a process that died before it could say so itself —
   see `ActiveSeat`'s Rust docs for why the entry alone never proves that. */
function renderActive(run) {
  const active = run.active && typeof run.active === "object" ? run.active : {};
  const seats = Object.keys(active).sort();
  show($("run-active-panel"), seats.length > 0);
  if (seats.length === 0) return;

  setText($("run-active-count"), String(seats.length));
  const note = $("run-active-note");
  show(note, !run.live);
  if (!run.live) {
    setText(note, "No live daemon claims this run right now — likely left behind by a killed process, not a seat that is actually still working.");
  }

  const list = $("run-active");
  clear(list);
  const now = Date.now();
  for (const key of seats) {
    const a = active[key];
    const startedMs = Date.parse(a.started_at || "");
    const elapsed = Number.isFinite(startedMs) ? Math.max(Math.round((now - startedMs) / 1000), 0) : null;
    const budget = Number(a.timeout_secs) || 0;
    const remaining = elapsed === null ? null : Math.max(budget - elapsed, 0);
    const retry = Number(a.attempt) > 0 ? ` · retry ${a.attempt}` : "";
    list.append(el("li", {},
      el("span", { class: "seat", text: key }),
      el("span", { text: `${a.node || "?"}${retry}` }),
      el("span", {
        text: elapsed === null
          ? "in progress"
          : `${elapsed}s elapsed · ${remaining}s left of ${budget}s`,
      }),
    ));
  }
}

/* Local clock tick, not a fetch: `renderActive` only recomputes the elapsed /
   remaining text from data already in hand, so a run with one seat quiet for
   ten minutes does not sit there showing the number from whenever the change
   stream last had a reason to fire. Nothing here talks to the network. */
function tickActive() {
  if (state.route.name === "run" && state.detail.run) renderActive(state.detail.run);
}

function renderQuota(run) {
  const losses = Array.isArray(run.quota) ? run.quota : [];
  show($("run-quota-panel"), losses.length > 0);
  if (losses.length === 0) return;

  const list = $("run-quota");
  clear(list);
  for (const loss of losses) {
    list.append(el("li", {},
      el("span", { class: "seat", text: loss.seat || "" }),
      el("span", { text: `during ${loss.node || "?"}` }),
      el("span", { text: clock(loss.at) }),
      loss.reset ? el("span", { text: `resets ${loss.reset}` }) : null,
    ));
  }
}

function renderTimeline(run) {
  const events = Array.isArray(run.events) ? run.events : [];
  show($("run-events-panel"), events.length > 0);
  if (events.length === 0) return;

  const list = $("run-events");
  clear(list);
  for (const event of events) {
    list.append(el("li", {},
      el("span", { class: "event-at", text: clock(event.at) }),
      el("div", { class: "event-body" },
        el("p", { class: "event-node", text: event.node || "" }),
        el("p", { class: "event-msg", text: event.message || "" }),
      ),
    ));
  }
}

/* ---- loading ----------------------------------------------------------- */
async function loadRuns() {
  try {
    state.runs = await getJson(API.runs(RUN_LIMIT));
    renderRuns();
    ok();
  } catch (error) {
    fail(`Could not load runs: ${error.message}`);
  }
}

async function loadQueue() {
  try {
    state.queue = await getJson(API.queue);
    renderQueue();
    ok();
  } catch (error) {
    fail(`Could not load the queue: ${error.message}`);
  }
}

/* Questions are loaded whole rather than by id: the list is short by nature —
   a backlog of them would mean the loop had been stalled for days — and one
   fetch keeps the runs list, the ask bar and the open run in agreement about
   which runs are parked. */
async function loadQuestions() {
  try {
    const list = await getJson(API.questions);
    state.questions = sortQuestions(Array.isArray(list) ? list : []);
    renderQuestions();
    renderAskBar();
    /* A run's `waiting` only means something next to the questions, so both
       views are re-rendered from the answer, not from the run revision. */
    renderRuns();
    if (state.route.name === "run" && state.detail.run) renderRunDetail();
    ok();
  } catch (error) {
    fail(`Could not load questions: ${error.message}`);
  }
}

/* A restart hands the address from one process to the next, and the gap is
   meant to be sub-second (see `bind_waiting` server-side) - a fetch landing
   in it is not a fault. Reported as an error it used to read
   `Cannot reach magi: Failed to fetch` with a Retry button that fixed
   nothing: this page already retries on its own by polling health, and
   reconnects the moment the successor is listening. Returns whether it
   handled the failure, so `loadHealth` knows not to also call `fail`.
   `UPGRADE_WAIT_LIMIT_MS` is the one exception - past it, patience stops
   being the right read and a human is told instead. */
function reportUnreachableDuringUpgrade(error) {
  const upgradeInfo = state.health && state.health.upgrade;
  if (!upgradeInfo || !UPGRADE_BUSY_STAGES.has(upgradeInfo.stage)) return false;
  if (upgradeOverdue(upgradeInfo)) {
    fail(`Cannot reach magi: ${error.message}. It was replacing itself with ${upgradeInfo.to || "a new release"} and has not come back in over an hour  check on it by hand.`);
    return true;
  }
  setAttr($("daemon"), "data-state", "upgrading");
  setAttr($("daemon"), "data-owned", null);
  const why = $("loop-why");
  setText(why, "The deck is restarting on the new build. This page reconnects on its own.");
  show(why, true);
  show($("loop-toggle"), false);
  return true;
}

async function loadHealth({ applyRevisions = false } = {}) {
  try {
    state.health = await getJson(API.health);
    /* Through applyLoop rather than a bare render, so a loop that went quiet
       between ticks is confirmed here too: with the stream up, this interval
       is the only thing that asks. */
    if (state.health.loop) applyLoop(state.health.loop);
    else renderLoop();
    /* health.questions_needs_owner is the count until /api/questions has
       answered, so the indicator is right on the very first paint. */
    renderAskBar();
    if (applyRevisions) await applyRevisions_(state.health);
    ok();
  } catch (error) {
    if (!reportUnreachableDuringUpgrade(error)) fail(`Cannot reach magi: ${error.message}`);
  }
}

async function loadRun(id) {
  const fresh = state.detail.id !== id;
  if (fresh) state.detail = { id, run: null, report: null };
  renderRunDetail();

  const [run, report] = await Promise.allSettled([getJson(API.run(id)), getText(API.report(id))]);

  if (state.detail.id !== id) return;   /* the operator navigated away */

  if (run.status === "fulfilled") {
    state.detail.run = run.value;
    ok();
  } else {
    fail(`Could not load run ${shortId(id)}: ${run.reason.message}`);
  }
  state.detail.report = report.status === "fulfilled"
    ? report.value
    : `The report could not be rendered: ${report.reason.message}`;

  renderRunDetail();
}

/* Named with a trailing underscore because `applyRevisions` is also the option
   name on loadHealth. */
async function applyRevisions_(source) {
  const queueRev = source.queue_rev;
  const runsRev = source.runs_rev;
  const questionsRev = source.questions_rev;
  const talksRev = source.talks_rev;
  const jobs = [];

  if (queueRev !== state.rev.queue) {
    state.rev.queue = queueRev;
    jobs.push(loadQueue());
  }
  if (runsRev !== state.rev.runs) {
    state.rev.runs = runsRev;
    jobs.push(loadRuns());
    if (state.route.name === "run" && state.detail.id) jobs.push(loadRun(state.detail.id));
  }
  if (questionsRev !== state.rev.questions) {
    state.rev.questions = questionsRev;
    jobs.push(loadQuestions());
  }
  /* A turn landing on disk is what bumps this, so it is also how the reply
     reaches a phone whose own POST is still outstanding. */
  if (talksRev !== state.rev.talks) {
    state.rev.talks = talksRev;
    jobs.push(loadTalks());
    if (state.route.name === "talk" && state.talkDetail.id) jobs.push(loadTalk(state.talkDetail.id));
  }
  /* Bumped by this process whenever the loop it owns starts, stops, claims or
     finishes, so a phone learns about a tap it did not make. Guarded on the
     field existing: a payload without it must not refetch every tick. */
  if (source.loop_rev !== undefined && source.loop_rev !== state.rev.loop) {
    state.rev.loop = source.loop_rev;
    jobs.push(loadLoop());
  }
  if (jobs.length) {
    const saidBefore = saidCount;
    await Promise.allSettled(jobs);
    /* Only the generic word, and only when nothing better was said: a job in
       this batch may have announced the loop stopping, and overwriting that
       with "Updated." would be the one sentence the operator needed lost. */
    if (saidCount === saidBefore) announce("Updated.");
  }
}

/* ---- live stream ------------------------------------------------------- */
function subscribe() {
  let stream;
  try {
    stream = new EventSource(API.events);
  } catch {
    return;   /* no EventSource: the health interval still refreshes revisions */
  }

  stream.addEventListener("open", () => {
    state.streamOpen = true;
    ok();
  });

  stream.addEventListener("change", (message) => {
    let payload;
    try {
      payload = JSON.parse(message.data);
    } catch {
      return;
    }
    state.streamOpen = true;
    applyRevisions_(payload);
  });

  /* EventSource reconnects on its own. The one thing it will not do is repair
     the data that went stale while it was down, so a single refresh is
     scheduled — debounced, because a server that is gone errors repeatedly. */
  stream.addEventListener("error", () => {
    state.streamOpen = false;
    if (fallbackTimer) return;
    fallbackTimer = setTimeout(() => {
      fallbackTimer = null;
      loadHealth({ applyRevisions: true });
    }, 3000);
  });
}

/* ---- routing ----------------------------------------------------------- */
function parseRoute() {
  const parts = location.hash.replace(/^#\/?/, "").split("/").filter(Boolean);
  if (parts[0] === "queue") return { name: "queue", id: null };
  if (parts[0] === "questions") return { name: "questions", id: null };
  if (parts[0] === "chat" && parts[1]) return { name: "talk", id: decodeURIComponent(parts[1]) };
  if (parts[0] === "chat") return { name: "talks", id: null };
  if (parts[0] === "runs" && parts[1]) return { name: "run", id: decodeURIComponent(parts[1]) };
  return { name: "runs", id: null };
}

function applyRoute() {
  const route = parseRoute();
  const changed = route.name !== state.route.name || route.id !== state.route.id;
  state.route = route;

  show($("view-runs"), route.name === "runs");
  show($("view-run"), route.name === "run");
  show($("view-queue"), route.name === "queue");
  show($("view-questions"), route.name === "questions");
  show($("view-talks"), route.name === "talks");
  show($("view-talk"), route.name === "talk");

  /* The fab is the only entry point into Resume / Fold / Delete, so it must
     not survive a navigation away from the run it belongs to — nor stay
     around to be tapped from another screen. */
  show($("run-actions-fab"), route.name === "run");
  if (route.name !== "run") closeRunActions();

  const section = route.name === "run" ? "runs"
    : route.name === "talk" ? "talks"
    : route.name;
  for (const link of document.querySelectorAll("[data-nav]")) {
    setAttr(link, "aria-current", link.dataset.nav === section ? "page" : null);
  }

  if (route.name === "run") {
    if (state.detail.id !== route.id) loadRun(route.id);
  } else {
    state.detail = { id: null, run: null, report: null };
  }

  /* A conversation that is not on screen is dropped so the next one cannot
     flash the previous transcript first. The in-flight turn is deliberately
     not cancelled: it is running on the server either way, and coming back
     to the conversation re-reads it. */
  if (route.name === "talk") {
    if (changed) state.openingTalk = true;
    if (state.talkDetail.id !== route.id) {
      resetTalkAttachments(route.id);
      state.talkDetail = { id: route.id, talk: null };
      loadTalk(route.id);
    }
    renderTalk();
  } else if (state.talkDetail.id) {
    resetTalkAttachments(null);
    state.talkDetail = { id: null, talk: null };
  }

  if (changed) window.scrollTo({ top: 0 });
  /* The operator arrived to answer one specific thing, so the caret goes on
     it rather than on the top of the document. */
  if (changed && route.name === "questions") focusFirstAsk();
  renderTitle();
}

/* ---- run actions sheet -------------------------------------------------- */
function openRunActions() {
  const dialog = $("run-actions-sheet");
  if (!dialog.open) dialog.showModal();
}

function closeRunActions() {
  const dialog = $("run-actions-sheet");
  if (dialog.open) dialog.close();
}

/* ---- task edit sheet ----------------------------------------------------
 * Full-text replacement, not append: the operator may want to rewrite the
 * task as much as add to it, so the field opens with the current instruction
 * already in it rather than blank - overwriting is how "add a clause" gets
 * typed, but starting from nothing is how the rest of it gets lost. */
let editingTaskId = null;

function openTaskEdit(task) {
  editingTaskId = task.id;
  $("task-edit-title").value = task.title || "";
  $("task-edit-instruction").value = task.instruction || "";
  show($("task-edit-error"), false);
  setText($("task-edit-error"), "");
  const dialog = $("task-edit-sheet");
  if (!dialog.open) dialog.showModal();
  requestAnimationFrame(() => $("task-edit-title").focus({ preventScroll: true }));
}

function closeTaskEdit() {
  const dialog = $("task-edit-sheet");
  if (dialog.open) dialog.close();
  editingTaskId = null;
}

async function saveTaskEdit() {
  if (!editingTaskId) return;
  const id = editingTaskId;
  const title = $("task-edit-title").value.trim();
  const instruction = $("task-edit-instruction").value;
  if (!title || !instruction.trim()) {
    setText($("task-edit-error"), "Give both a title and an instruction.");
    show($("task-edit-error"), true);
    return;
  }
  const button = $("task-edit-save");
  const label = button.textContent;
  button.disabled = true;
  setText(button, "Saving…");
  try {
    await postJson(API.editTask(id), { title, instruction });
    ok();
    announce(`Task ${shortId(id)} edited.`);
    closeTaskEdit();
    await loadQueue();
  } catch (error) {
    setText($("task-edit-error"), error.message);
    show($("task-edit-error"), true);
  } finally {
    button.disabled = false;
    setText(button, label);
  }
}

/* ---- theme ------------------------------------------------------------- */
const THEMES = ["auto", "light", "dark"];
const THEME_LABEL = {
  auto: "Colour theme: follow system",
  light: "Colour theme: light",
  dark: "Colour theme: dark",
};

function currentTheme() {
  const value = document.documentElement.dataset.theme;
  return THEMES.includes(value) ? value : "auto";
}

function applyTheme(theme) {
  if (theme === "auto") delete document.documentElement.dataset.theme;
  else document.documentElement.dataset.theme = theme;
  setAttr($("theme-toggle"), "aria-label", THEME_LABEL[theme]);
  setAttr($("theme-toggle"), "title", THEME_LABEL[theme]);
  try {
    if (theme === "auto") localStorage.removeItem("magi-theme");
    else localStorage.setItem("magi-theme", theme);
  } catch {
    /* localStorage is denied in private mode; the theme still applies now */
  }
}

/* The three ways an image reaches a composer: the file input's own `change`,
   a paste into the textarea, and a drop on either the composer or the
   transcript above it - "入力欄ないし会話パネル" is both, so both are drop
   targets. Takes `attach` as a parameter so a second composer could reuse
   this without this function needing to know which one it is wiring. */
function wireAttachments({ fileInput, say, turns, box, attach }) {
  const input = $(fileInput);
  input.addEventListener("change", () => {
    if (input.files && input.files.length) attach(input.files);
    input.value = "";   /* so picking the same file again still fires change */
  });

  $(box).addEventListener("paste", (event) => {
    const items = event.clipboardData && event.clipboardData.items;
    if (!items) return;
    const files = [...items]
      .filter((item) => item.kind === "file")
      .map((item) => item.getAsFile())
      .filter(Boolean);
    if (files.length === 0) return;
    /* Only when there is a picture to take: an ordinary text paste must not
       be swallowed just because this listener exists. */
    event.preventDefault();
    attach(files);
  });

  for (const id of [say, turns]) {
    const zone = $(id);
    zone.addEventListener("dragover", (event) => {
      if (!event.dataTransfer || ![...event.dataTransfer.types].includes("Files")) return;
      event.preventDefault();
      zone.classList.add("is-drop-target");
    });
    /* `relatedTarget` is what stops this from flickering as the pointer
       crosses a child element on the way out - a drag over `.turns` moves
       across many `<li>`s, each of which is its own dragleave otherwise. */
    zone.addEventListener("dragleave", (event) => {
      if (event.relatedTarget && zone.contains(event.relatedTarget)) return;
      zone.classList.remove("is-drop-target");
    });
    zone.addEventListener("drop", (event) => {
      zone.classList.remove("is-drop-target");
      if (!event.dataTransfer || event.dataTransfer.files.length === 0) return;
      event.preventDefault();
      attach(event.dataTransfer.files);
    });
  }
}

/* ---- boot -------------------------------------------------------------- */
function wire() {
  $("run-actions-fab").addEventListener("click", openRunActions);
  $("run-actions-close").addEventListener("click", closeRunActions);
  /* Clicking the backdrop hits the dialog element itself, since nothing else
     is there to catch it — a click on the sheet's own content lands on a
     descendant instead and never reaches this listener. */
  $("run-actions-sheet").addEventListener("click", (event) => {
    if (event.target === event.currentTarget) closeRunActions();
  });
  /* Fires for every close path — the close button, Escape (which the
     dialog's default "cancel" handling turns into a close), and the backdrop
     handler above — so the focus return only has to live in one place. */
  $("run-actions-sheet").addEventListener("close", () => {
    $("run-actions-fab").focus({ preventScroll: true });
  });

  $("task-edit-close").addEventListener("click", closeTaskEdit);
  $("task-edit-save").addEventListener("click", saveTaskEdit);
  $("task-edit-sheet").addEventListener("click", (event) => {
    if (event.target === event.currentTarget) closeTaskEdit();
  });
  $("task-edit-sheet").addEventListener("close", () => {
    editingTaskId = null;
  });

  $("runs-filter-clear").addEventListener("click", clearRunsFilter);

  $("theme-toggle").addEventListener("click", () => {
    const next = THEMES[(THEMES.indexOf(currentTheme()) + 1) % THEMES.length];
    applyTheme(next);
  });

  $("wrap-toggle").addEventListener("click", (event) => {
    state.wrap = !state.wrap;
    event.currentTarget.setAttribute("aria-pressed", String(state.wrap));
    $("run-report").dataset.wrap = state.wrap ? "1" : "0";
  });

  $("alert-retry").addEventListener("click", () => {
    ok();
    loadHealth({ applyRevisions: true });
    loadQuestions();
    if (state.route.name === "run" && state.detail.id) loadRun(state.detail.id);
    if (state.route.name === "talk" && state.talkDetail.id) loadTalk(state.talkDetail.id);
  });

  $("talk-start-go").addEventListener("click", startTalk);
  $("talk-say").addEventListener("submit", sendTalkTurn);
  $("talk-close-go").addEventListener("click", closeTalk);
  $("talk-reopen-go").addEventListener("click", reopenTalk);
  $("talk-tasks-panel").addEventListener("toggle", () => {
    const panel = $("talk-tasks-panel");
    const talkId = panel.dataset.talkId;
    if (!talkId) return;
    const collapsed = loadCollapsed(TALK_TASKS_STORAGE_KEY);
    collapsed[talkId] = panel.open;
    saveCollapsed(TALK_TASKS_STORAGE_KEY, collapsed);
  });
  wireAttachments({
    fileInput: "talk-file-input", say: "talk-say", turns: "talk-turns", box: "f-talk-say",
    attach: attachTalkFiles,
  });
  /* Same accommodation `f-say` gets: Enter is a newline on a phone, Ctrl/Cmd
     with Enter sends. */
  $("f-talk-say").addEventListener("keydown", (event) => {
    if (event.key === "Enter" && (event.metaKey || event.ctrlKey)) {
      event.preventDefault();
      $("talk-say").requestSubmit();
    }
  });

  $("panel-full-close").addEventListener("click", closePanel);
  /* Escape closes a dialog without a click, so the frame is dropped from the
     close event rather than from the button: a dismissed panel must not go
     on holding a live document. */
  $("panel-full").addEventListener("close", () => clear($("panel-full-body")));

  $("attachment-view-close").addEventListener("click", closeAttachmentView);
  $("attachment-view").addEventListener("click", (event) => {
    if (event.target === event.currentTarget) closeAttachmentView();
  });
  $("attachment-view").addEventListener("close", () => {
    $("attachment-view-img").src = "";
  });

  window.addEventListener("hashchange", applyRoute);

  /* A phone spends most of its time with the screen off. Asking again on wake
     is what stops the operator reading a snapshot from an hour ago. */
  document.addEventListener("visibilitychange", () => {
    if (!document.hidden) loadHealth({ applyRevisions: true });
  });
}

async function boot() {
  applyTheme(currentTheme());
  wire();
  applyRoute();

  await loadHealth();
  if (state.health) {
    state.rev.queue = state.health.queue_rev;
    state.rev.runs = state.health.runs_rev;
    state.rev.questions = state.health.questions_rev;
    state.rev.talks = state.health.talks_rev;
    state.rev.loop = state.health.loop_rev;
    if (state.health.loop) state.loop = state.health.loop;
  }
  await Promise.allSettled([
    loadRuns(), loadQueue(), loadQuestions(), loadTalks(),
  ]);

  subscribe();
  setInterval(() => {
    if (document.hidden) return;
    loadHealth({ applyRevisions: !state.streamOpen });
  }, HEALTH_MS);
  setInterval(tickActive, 1000);
}

boot();