brokk-mj-controller 2.1.3

Daemon-side controller, session manager, and web server for Mjolnir
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
import { renderMarkdown } from './markdown.js';
import { renderToolOutput } from './tool-output.js';

/// Build one element. Every piece of this application creates nodes and sets
/// `textContent`; nothing builds markup as a string, which is what makes agent
/// output structurally unable to inject an element.
function el(name, className, textContent) {
  const node = document.createElement(name);
  if (className) node.className = className;
  if (textContent !== undefined) node.textContent = textContent;
  return node;
}

/// A button carrying the data a click handler reads back off it.
function button(label, className, data) {
  const node = el('button', className, label);
  for (const [key, value] of Object.entries(data || {})) node.dataset[key] = value;
  return node;
}

const login = document.querySelector('#login'),
  app = document.querySelector('#app'),
  header = document.querySelector('#shell-header'),
  shellTitle = document.querySelector('#shell-title'),
  backButton = document.querySelector('#back'),
  menuButton = document.querySelector('#menu-button'),
  menu = document.querySelector('#menu'),
  announcer = document.querySelector('#announcer'),
  workspaceStrip = document.querySelector('#workspaces'),
  sessions = document.querySelector('#sessions'),
  resumable = document.querySelector('#resumable'),
  targetsPanel = document.querySelector('#targets'),
  quotaPanel = document.querySelector('#quota'),
  logout = document.querySelector('#logout'),
  newForm = document.querySelector('#new-form'),
  newStep = document.querySelector('#new-step'),
  newProgress = document.querySelector('#new-progress'),
  newBackButton = document.querySelector('#new-back'),
  newNextButton = document.querySelector('#new-next'),
  newError = document.querySelector('#new-error'),
  moveForm = document.querySelector('#move-form'),
  moveStep = document.querySelector('#move-step'),
  moveProgress = document.querySelector('#move-progress'),
  moveBackButton = document.querySelector('#move-back'),
  moveNextButton = document.querySelector('#move-next'),
  moveError = document.querySelector('#move-error'),
  actionError = document.querySelector('#action-error'),
  resumeError = document.querySelector('#resume-error'),
  feed = document.querySelector('#conversation-feed'),
  feedScroll = document.querySelector('#conversation-scroll'),
  conversationTransition = document.querySelector('#conversation-transition'),
  conversationTransitionTitle = document.querySelector('#conversation-transition-title'),
  conversationTransitionStage = document.querySelector('#conversation-transition-stage'),
  conversationTransitionNotice = document.querySelector('#conversation-transition-notice'),
  conversationTransitionError = document.querySelector('#conversation-transition-error'),
  conversationTransitionCancel = document.querySelector('#conversation-transition-cancel'),
  jumpToLatest = document.querySelector('#jump-to-latest'),
  cancelTurnButton = document.querySelector('#cancel-turn'),
  commandPalette = document.querySelector('#command-palette'),
  sendButton = document.querySelector('#send-button'),
  queue = document.querySelector('#conversation-queue'),
  shells = document.querySelector('#conversation-shells'),
  conversationSide = document.querySelector('#conversation-side'),
  conversationSummary = conversationSide?.querySelector('summary'),
  queueHeading = queue?.previousElementSibling,
  shellsHeading = shells?.previousElementSibling,
  elicitations = document.querySelector('#elicitations'),
  reviewHost = document.querySelector('#turn-review'),
  promptText = document.querySelector('#prompt-text'),
  attachments = document.querySelector('#attachments'),
  attachImage = document.querySelector('#attach-image'),
  imagePicker = document.querySelector('#image-picker');

/// Every page, by the route name that shows it.
const PAGES = {
  dashboard: document.querySelector('#dashboard'),
  new: document.querySelector('#new-page'),
  resume: document.querySelector('#resume-page'),
  move: document.querySelector('#move-page'),
  targets: document.querySelector('#targets-page'),
  quota: document.querySelector('#quota-page'),
  conversation: document.querySelector('#conversation'),
};

/// Transcript nodes by entry id, so an update patches the row it belongs to
/// rather than searching the whole document for it.
const entryNodes = new Map();
let snapshot,
  route = { name: 'dashboard' },
  currentSession,
  moveDraft,
  cursor = 0,
  acknowledged = 0,
  eventSource,
  conversationMode = null;

/// Actions the browser has asked for and not yet heard back about.
///
/// A control is disabled because it is in this set, not because a handler
/// disabled it: state decides, so a re-render cannot lose the fact and a
/// failure cannot leave a button dead.
const pendingActions = new Set();

async function request(url, options = {}) {
  const response = await fetch(url, {
    ...options,
    headers: { 'content-type': 'application/json', ...(options.headers || {}) },
  });
  if (response.status === 401) {
    // Authentication expired. Every route has to reach the login swap, not
    // only the snapshot refresh, or a phone sits on a dead page issuing
    // requests that will never succeed.
    showLogin();
    throw new Error('unauthorized');
  }
  if (!response.ok) {
    const body = await response.json().catch(() => ({}));
    throw new Error(body.error || response.statusText);
  }
  if (response.status === 202 || response.status === 204) return null;
  return response.json();
}

/// Say something once, for a screen reader.
function announce(message) {
  announcer.textContent = message;
}

// ---------------------------------------------------------------------------
// Routing
// ---------------------------------------------------------------------------
//
// The URL is the state. Back, Forward, reload and a shared link all work
// because nothing but the router writes `location.hash`, and every page is
// rendered from what the router parsed rather than from what a click handler
// remembered.

const ID = '[A-Za-z0-9_-]+';
const ROUTE_PATTERNS = [
  [new RegExp(`^#workspace/(${ID})/new$`), ([id]) => ({ name: 'new', workspaceId: id })],
  [new RegExp(`^#workspace/(${ID})/resume$`), ([id]) => ({ name: 'resume', workspaceId: id })],
  [new RegExp(`^#workspace/(${ID})/move/(${ID})$`), ([workspaceId, sessionId]) => ({ name: 'move', workspaceId, sessionId })],
  [new RegExp(`^#workspace/(${ID})$`), ([id]) => ({ name: 'dashboard', workspaceId: id })],
  [new RegExp(`^#conversation/(${ID})$`), ([id]) => ({ name: 'conversation', sessionId: id })],
  [/^#targets$/, () => ({ name: 'targets' })],
  [/^#quota$/, () => ({ name: 'quota' })],
];

function parseRoute(hash) {
  for (const [pattern, build] of ROUTE_PATTERNS) {
    const match = pattern.exec(hash);
    if (match) return build(match.slice(1));
  }
  return { name: 'dashboard' };
}

function routeHash(next) {
  switch (next.name) {
    case 'new':
      return `#workspace/${next.workspaceId}/new`;
    case 'resume':
      return `#workspace/${next.workspaceId}/resume`;
    case 'move':
      return `#workspace/${next.workspaceId}/move/${next.sessionId}`;
    case 'conversation':
      return `#conversation/${next.sessionId}`;
    case 'targets':
      return '#targets';
    case 'quota':
      return '#quota';
    default:
      return next.workspaceId ? `#workspace/${next.workspaceId}` : '';
  }
}

/// Go to a route. Assigning the hash it already has fires no `hashchange`, so
/// the render is called directly in that case rather than being dropped.
function navigate(next) {
  const hash = routeHash(next);
  const current = location.hash;
  if (hash === current || (!hash && !current)) {
    applyRoute();
    return;
  }
  location.hash = hash;
}

/// The workspace the route names, or the one to fall back to.
function selectedWorkspaceId() {
  const workspaces = snapshot?.workspaces || [];
  if (route.workspaceId && workspaces.some(w => w.id === route.workspaceId)) {
    return route.workspaceId;
  }
  if (route.name === 'conversation') {
    const session = snapshot?.sessions.find(s => s.id === route.sessionId);
    if (session?.workspace_id) return session.workspace_id;
  }

  return workspaces[0]?.id;
}

function applyRoute() {
  cancelSessionPress();
  route = parseRoute(location.hash);
  if (!snapshot) return;

  // The dashboard names its workspace in the URL, so a reload, a Back press
  // and a shared link all return to the same one. An empty hash is the state
  // a first visit is in, and canonicalising it here is what gives every later
  // navigation something to go back to.
  if (route.name === 'dashboard' && !route.workspaceId) {
    const workspaceId = selectedWorkspaceId();
    if (workspaceId) {
      navigate({ name: 'dashboard', workspaceId });
      return;
    }
  }

  // A conversation route only means a conversation while that session still
  // has one. Otherwise it is a stale link, and the dashboard is the answer.
  if (route.name === 'conversation') {
    const session = snapshot.sessions.find(s => s.id === route.sessionId);
    if (!session
      || (!session.capabilities?.open
        && !isTransitioningSession(session)
        && !isLoadingConversationSession(session))) {
      navigate({ name: 'dashboard', workspaceId: selectedWorkspaceId() });
      return;
    }
  }

  if (route.name === 'move') {
    const session = snapshot.sessions.find(s => s.id === route.sessionId);
    if (!session?.capabilities?.move_session
      && session?.operation?.kind !== 'move'
      && !session?.move_recovery?.checkpoint_retained) {
      navigate({ name: 'dashboard', workspaceId: selectedWorkspaceId() });
      return;
    }
  }

  const name = PAGES[route.name] ? route.name : 'dashboard';
  for (const [key, page] of Object.entries(PAGES)) page.classList.toggle('hidden', key !== name);
  workspaceStrip.classList.toggle('hidden', name === 'conversation');
  backButton.classList.toggle('hidden', name === 'dashboard');
  shellTitle.textContent =
    {
      new: 'New session',
      resume: 'Resume',
      move: 'Move session',
      targets: 'Targets',
      quota: 'Quota',
      conversation: 'Conversation',
    }[name] || 'MJ';

  if (name === 'conversation') {
    openConversation(route.sessionId);
  } else if (currentSession) {
    leaveConversation();
  }
  // Arriving at the wizard starts it over; leaving it discards what was
  // half-answered rather than keeping it to surprise the next visit.
  if (name !== 'new') newDraft = null;
  if (name !== 'move') moveDraft = null;
  renderRoute();
  // A screen reader should land at the top of the page it just moved to
  // rather than wherever it happened to be.
  PAGES[name].setAttribute('tabindex', '-1');
  PAGES[name].focus({ preventScroll: true });
  announce(shellTitle.textContent);
}

function renderRoute() {
  if (!snapshot) return;
  if (route.name !== 'dashboard') closeSessionMenu(false);
  renderWorkspaces();
  renderLaunchFailures();
  switch (route.name) {
    case 'new':
      renderNewForm();
      break;
    case 'resume':
      renderResumable();
      break;
    case 'move':
      renderMoveForm();
      break;
    case 'targets':
      renderTargets();
      break;
    case 'quota':
      renderQuota();
      break;
    case 'conversation':
      break;
    default:
      renderSessions();
  }
}

// ---------------------------------------------------------------------------
// Workspaces
// ---------------------------------------------------------------------------

const dismissedLaunchFailures = new Set();

function renderLaunchFailures() {
  const notices = (snapshot.launch_failures || []).filter(
    failure => route.name === 'dashboard' && failure.workspace_id === selectedWorkspaceId() && !dismissedLaunchFailures.has(failure.id),
  );
  const failureCards = notices.map(failure => {
    const card = el('div', 'card');
    card.append(el('p', '', 'A session could not be started. Check the project and target, then retry. Details are in the daemon logs.'));
    const dismiss = el('button', 'secondary', 'Dismiss launch error');
    dismiss.onclick = () => {
      dismissedLaunchFailures.add(failure.id);
      renderLaunchFailures();
    };
    card.append(dismiss);
    return card;
  });
  if (route.name === 'dashboard') {
    const moveFailures = (snapshot.sessions || []).filter(session =>
      session.workspace_id === selectedWorkspaceId() &&
      session.move_recovery?.checkpoint_retained &&
      ['failed', 'cancelled'].includes(session.move_recovery.phase),
    );
    failureCards.push(...moveFailures.map(session => {
      const recovery = session.move_recovery;
      const card = el('article', 'card move-recovery');
      const phase = recovery.phase === 'cancelled' ? 'cancelled' : 'failed';
      card.append(el('p', '', `Move of ${session.title || session.id} was ${phase}. The verified checkpoint is retained.`));
      if (recovery.destination_ready && recovery.queue_admission_started) {
        card.append(el('p', 'dim', 'The destination is retained. Retry uses the same destination and queue choice so already accepted work is not replayed elsewhere.'));
      } else {
        card.append(el('p', 'dim', 'Retry the move with the recorded destination, or resume with the source settings.'));
      }
      const row = el('div', 'row');
      if (recovery.checkpoint_retained) {
        const retry = button('Retry move', 'secondary', { action: 'move', id: session.id });
        retry.onclick = () => navigate({
          name: 'move',
          workspaceId: session.workspace_id || selectedWorkspaceId(),
          sessionId: session.id,
        });
        row.append(retry);
      }
      const queuePinned = recovery.queue_admission_started && !recovery.queue_admission_finished;
      if (recovery.checkpoint_retained && !queuePinned && session.capabilities?.resume) {
        const resume = button('Resume with previous settings', 'secondary', { action: 'resume', id: session.id });
        resume.dataset.profile = recovery.source_profile_id;
        resume.dataset.target = recovery.source_target_template_id;
        resume.onclick = () => navigate({
          name: 'resume',
          workspaceId: session.workspace_id || selectedWorkspaceId(),
        });
        row.append(resume);
      }
      card.append(row);
      return card;
    }));
    const failedSessions = (snapshot.sessions || []).filter(session =>
      session.workspace_id === selectedWorkspaceId() &&
      session.has_error &&
      !session.capabilities?.open &&
      session.operation?.kind !== 'move' &&
      !session.move_recovery?.checkpoint_retained,
    );
    failureCards.push(...failedSessions.map(session => {
      const card = el('div', 'card');
      card.append(el('p', '', `Session ${session.title || session.id} needs recovery. Its verified checkpoint is retained when available.`));
      const resume = button('Open resume', 'secondary');
      resume.onclick = () => navigate({ name: 'resume', workspaceId: session.workspace_id || selectedWorkspaceId() });
      card.append(resume);
      return card;
    }));
  }
  document.querySelector('#launch-failures').replaceChildren(...failureCards);
}

function renderWorkspaces() {
  const selected = selectedWorkspaceId();
  workspaceStrip.replaceChildren(
    ...(snapshot.workspaces || []).map(workspace => {
      const tab = el('button', 'tab', workspace.name);
      tab.setAttribute('role', 'tab');
      tab.setAttribute('aria-selected', String(workspace.id === selected));
      // Selection is a word to a screen reader and a border to everyone else,
      // never colour alone.
      if (workspace.id === selected) tab.setAttribute('aria-current', 'page');
      tab.dataset.workspaceId = workspace.id;
      return tab;
    }),
  );
}

// ---------------------------------------------------------------------------
// The session list
// ---------------------------------------------------------------------------

// Dashboard order is deliberately a view concern.  A live snapshot may
// report a newer activity watermark for an existing session, but moving that
// row under a reader's finger makes the dashboard feel broken.  Each
// workspace gets one seed order per document; ranks are retained after a row
// disappears so a reconnect cannot make it jump when it returns.
const dashboardOrders = new Map();
const sessionCards = new Map();
const sessionItems = new Map();
const sessionGroups = new Map();
let openSessionMenuId = null;
let openSessionMenuTrigger = null;
let suppressedSessionClickId = null;
let activeSessionPress = null;
let snapshotReceivedAtMs = 0;
let dashboardOrderSeeded = false;

function reconcileChildren(parent, desired) {
  // Remove departed siblings before inserting arrivals, so removing an earlier
  // row never detaches and reinserts the focused row. Ordinary refreshes do
  // no structural DOM work at all.
  const desiredSet = new Set(desired);
  for (const child of [...parent.children]) {
    if (!desiredSet.has(child)) parent.removeChild(child);
  }
  for (let index = 0; index < desired.length; index += 1) {
    if (parent.children[index] !== desired[index]) {
      parent.insertBefore(desired[index], parent.children[index] || null);
    }
  }
}

function epochMs(value) {
  if (value === undefined || value === null || value === '') return null;
  if (typeof value === 'number' && Number.isFinite(value)) return value;
  const parsed = Date.parse(value);
  return Number.isFinite(parsed) ? parsed : null;
}

function epochSecondsMs(value) {
  if (value === undefined || value === null || value === '') return null;
  if (typeof value === 'number' && Number.isFinite(value)) return value * 1000;
  return epochMs(value);
}

function sessionActivityMs(session) {
  return epochMs(session.last_activity_at_ms) ?? epochMs(session.created_at) ?? 0;
}

function projectKeyFor(session) {
  return session.project_key || session.bundle_id || session.id;
}

function orderState(workspaceId, live) {
  let state = dashboardOrders.get(workspaceId);
  if (!state) {
    state = { sessions: new Map(), groups: new Map(), nextSession: 0, nextGroup: 0 };
    dashboardOrders.set(workspaceId, state);
    const initial = [...live].sort((left, right) =>
      sessionActivityMs(right) - sessionActivityMs(left) || left.id.localeCompare(right.id),
    );
    for (const session of initial) {
      if (!state.sessions.has(session.id)) state.sessions.set(session.id, state.nextSession++);
    }
    const maxima = new Map();
    for (const session of initial) {
      const key = projectKeyFor(session);
      maxima.set(key, Math.max(maxima.get(key) ?? 0, sessionActivityMs(session)));
    }
    [...maxima.entries()]
      .sort((left, right) =>
        right[1] - left[1] ||
        left[0].localeCompare(right[0]),
      )
      .forEach(([key]) => state.groups.set(key, state.nextGroup++));
  }
  // New ids append to the remembered order.  Deliberately never delete a
  // rank: a stopped session can return after a reconnect without reordering
  // every row below it.
  for (const session of live) {
    if (!state.sessions.has(session.id)) state.sessions.set(session.id, state.nextSession++);
    const key = projectKeyFor(session);
    if (!state.groups.has(key)) state.groups.set(key, state.nextGroup++);
  }
  return state;
}

function seedDashboardOrders(data) {
  if (dashboardOrderSeeded) return;
  dashboardOrderSeeded = true;
  const workspaceIds = new Set((data.workspaces || []).map(workspace => workspace.id));
  for (const session of data.sessions || []) {
    if (session.workspace_id) workspaceIds.add(session.workspace_id);
  }
  for (const workspaceId of workspaceIds) {
    const workspaceLive = (data.sessions || []).filter(session =>
      session.workspace_id === workspaceId && isDashboardSession(session),
    );
    orderState(workspaceId, workspaceLive);
  }
  // Snapshots predating workspaces still have a single implicit workspace.
  if (!(data.workspaces || []).length) {
    orderState('', (data.sessions || []).filter(session =>
      isDashboardSession(session),
    ));
  }
}

function isTransitioningSession(session) {
  if (!session) return false;
  if (session.transitioning === true) return true;
  // A snapshot from just before the shared boolean was deployed still has
  // enough information to protect its transcript: every operation except a
  // normal checkpoint owns the conversation until completion.
  return Boolean(session.operation && session.operation.kind !== 'checkpoint');
}

/// A live session can briefly lose its conversation projection just after a
/// lifecycle operation hands it back to the running worker. This is not a
/// lifecycle transition (and therefore must not make ordinary checkpoints or
/// reconnects hide a readable conversation): it is only the completion gap of
/// the transition route already open in this tab.
function isLoadingConversationSession(session) {
  return Boolean(
    session
    && session.id === currentSession
    && !session.capabilities?.open
    && !isTransitioningSession(session)
    && session.operation?.kind !== 'checkpoint'
    && session.lifecycle === 'live'
    && !session.has_error
    && (conversationMode === 'loading' || conversationMode?.startsWith('transition:')),
  );
}

function isDashboardSession(session) {
  return ['live', 'starting', 'stopping'].includes(session.lifecycle)
    || isTransitioningSession(session);
}

function orderedSessions(live) {
  const workspaceId = selectedWorkspaceId();
  const state = orderState(workspaceId || '', live);
  return [...live].sort((left, right) =>
    state.sessions.get(left.id) - state.sessions.get(right.id) || left.id.localeCompare(right.id),
  );
}

function liveSessions() {
  const workspaceId = selectedWorkspaceId();
  return (snapshot.sessions || []).filter(
    session =>
      session.workspace_id === workspaceId &&
      isDashboardSession(session),
  );
}

/// Sessions grouped by the controller's projected project identity.
///
/// The controller publishes an opaque `project_key` and the same short
/// `project_label` the TUI uses. Keep those fields separate: labels can be
/// shared by different projects, while keys must never merge them. Group and
/// session ranks are seeded from activity, then frozen for this document.
function byProject(list) {
  const groups = new Map();
  for (const session of list) {
    // `bundle_id` keeps older snapshots renderable; current snapshots always
    // provide the opaque project key. The session id is only a last-resort
    // boundary for malformed legacy data, never a project label.
    const key = projectKeyFor(session);
    if (!groups.has(key)) groups.set(key, { key, label: session.project_label || key, sessions: [] });
    groups.get(key).sessions.push(session);
  }
  const state = orderState(selectedWorkspaceId() || '', list);
  return [...groups.values()].sort((left, right) =>
    state.groups.get(left.key) - state.groups.get(right.key) || left.key.localeCompare(right.key),
  );
}

function renderSessions() {
  const groups = byProject(orderedSessions(liveSessions()));
  if (openSessionMenuId && !groups.some(group => group.sessions.some(session => session.id === openSessionMenuId))) {
    closeSessionMenu();
  }
  if (!groups.length) {
    sessions.replaceChildren(el('p', 'dim', 'No live sessions or operations in this workspace.'));
    return;
  }
  const renderedGroups = groups.map(group => {
    const groupId = `${selectedWorkspaceId() || ''}\u001f${group.key}`;
    let section = sessionGroups.get(groupId);
    if (!section) {
      section = el('section', 'project');
      const heading = el('h2', 'project-heading');
      const label = el('span');
      const count = el('span', 'dim');
      heading.append(label, count);
      const list = el('div', 'project-sessions');
      list.setAttribute('role', 'list');
      section.append(heading, list);
      section._headingLabel = label;
      section._headingCount = count;
      section._sessionList = list;
      sessionGroups.set(groupId, section);
    }
    section._headingLabel.textContent = group.label;
    section._headingCount.textContent = ` ${group.sessions.length}`;
    const items = group.sessions.map(session => {
      let card = sessionCards.get(session.id);
      if (!card) {
        card = sessionCard(session);
        sessionCards.set(session.id, card);
      } else {
        updateSessionCard(card, session);
      }
      let item = sessionItems.get(session.id);
      if (!item) {
        item = el('div');
        item.setAttribute('role', 'listitem');
        sessionItems.set(session.id, item);
      }
      if (item.firstChild !== card) item.replaceChildren(card);
      return item;
    });
    reconcileChildren(section._sessionList, items);
    return section;
  });
  reconcileChildren(sessions, renderedGroups);
}

/// One session row.
///
/// Every control here appears because a capability the daemon published says
/// it may. Nothing on this page infers what is legal from a status string.
function sessionCard(session) {
  const card = el('article', 'card session');
  card.dataset.sessionId = session.id;
  const titleRow = el('div', 'session-title-row');
  const heading = el('h3');
  const attention = el('span', 'session-attention');
  const menuTrigger = button('', 'session-menu-trigger', { sessionMenu: session.id });
  menuTrigger.type = 'button';
  menuTrigger.setAttribute('aria-haspopup', 'menu');
  menuTrigger.setAttribute('aria-expanded', 'false');
  const menu = el('div', 'session-menu hidden');
  menu.setAttribute('role', 'menu');
  menu.dataset.sessionId = session.id;
  titleRow.append(heading, attention, menuTrigger, menu);

  const meta = el('div', 'session-meta');
  const location = el('span', 'session-location');
  const profile = el('span', 'session-profile');
  meta.append(location, profile);
  const activity = el('p', 'session-activity');
  card.append(titleRow, meta, activity);
  card._heading = heading;
  card._attention = attention;
  card._menuTrigger = menuTrigger;
  card._menu = menu;
  card._location = location;
  card._profile = profile;
  card._activity = activity;
  card._sessionMenuSignature = '';
  updateSessionCard(card, session);
  return card;
}

function attentionParts(session) {
  const parts = [];
  if (session.operation?.kind === 'move') parts.push(['', 'Moving']);
  if (session.has_error) parts.push(['!', 'Error']);
  if (session.pending_elicitations?.length) parts.push(['?', 'Input needed']);
  const queued = (session.queued_prompts || []).length;
  if (queued) parts.push([String(queued), `${queued} queued prompt${queued === 1 ? '' : 's'}`]);
  return parts;
}

function sessionMenuActions(session) {
  const can = session.capabilities || {};
  const actions = [];
  if (can.rename) actions.push(['Rename', 'secondary', 'rename']);
  if (can.cancel_operation) actions.push(['Cancel operation', 'danger', 'cancel']);
  if (can.stop) actions.push(['Stop session', 'danger', 'close']);
  if (can.resume) actions.push(['Resume', '', 'resume']);
  if (can.move_session) actions.push(['Move…', '', 'move']);
  return actions;
}

function updateSessionCard(card, session) {
  card._session = session;
  const can = session.capabilities || {};
  const openable = can.open === true || isTransitioningSession(session);
  card.dataset.openable = String(openable);
  if (openable) {
    card.setAttribute('role', 'link');
    card.setAttribute('tabindex', '0');
  } else {
    card.removeAttribute('role');
    card.removeAttribute('tabindex');
  }
  const attention = attentionParts(session);
  const attentionText = attention.map(([, label]) => label.toLowerCase()).join(', ');
  card.setAttribute(
    'aria-label',
    `${can.open === true ? 'Open session' : openable ? 'View session status' : 'Session'} ${session.title || session.id}${attentionText ? `; needs attention: ${attentionText}` : ''}`,
  );
  renderSessionTitle(card._heading, session);
  card._attention.replaceChildren(
    ...attention.map(([glyph, label]) => {
      const node = el('span', `session-attention-item ${label === 'Error' || label === 'Input needed' ? 'alert' : ''}`, glyph);
      node.setAttribute('aria-label', label);
      node.setAttribute('role', 'img');
      node.title = label;
      return node;
    }),
  );
  card._location.textContent = session.display_location || session.target_id || '';
  card._location.title = card._location.textContent;
  card._profile.textContent = session.profile_id || '';
  card._profile.title = card._profile.textContent;
  updateSessionActivity(card, session);
  updateSessionMenu(card, session);
}

function updateSessionMenu(card, session) {
  const actions = sessionMenuActions(session);
  const signature = actions.map(action => action[2]).join('|');
  const menuChanged = card._sessionMenuSignature !== signature;
  if (menuChanged) {
    const activeAction = card._menu?.ownerDocument?.activeElement?.dataset?.action;
    card._menu.replaceChildren(
      ...actions.map(([label, className, actionName]) => {
        const control = action(label, className, {
          action: actionName,
          id: session.id,
          profile: session.profile_id,
          target: session.target_id,
        });
        control.setAttribute('role', 'menuitem');
        return control;
      }),
    );
    card._sessionMenuSignature = signature;
    if (activeAction && card._menu.classList && !card._menu.classList.contains('hidden')) {
      const next = card._menu.querySelector(`button[data-action="${activeAction}"]:not(:disabled)`)
        || card._menu.querySelector('button:not(:disabled)');
      next?.focus({ preventScroll: true });
    }
  } else {
    for (const control of card._menu.querySelectorAll?.('button[data-action]') || []) {
      control.dataset.profile = session.profile_id || '';
      control.dataset.target = session.target_id || '';
      control.disabled = pendingActions.has(`${control.dataset.action}:${session.id}`);
    }
  }
  card._menuTrigger.disabled = actions.length === 0;
  card._menuTrigger.setAttribute('aria-label', `Actions for ${session.title || session.id}`);
  card._menuTrigger.setAttribute('aria-expanded', String(openSessionMenuId === session.id));
  if (openSessionMenuId === session.id && !actions.length) closeSessionMenu(false);
}

function serverClockMs() {
  const server = epochMs(snapshot?.server_time_ms);
  if (server == null || !snapshotReceivedAtMs) return Date.now();
  return server + (Date.now() - snapshotReceivedAtMs);
}

function formatClock(milliseconds) {
  const seconds = Math.max(0, Math.floor(Number(milliseconds || 0) / 1000));
  if (seconds < 60) return `${seconds}s`;
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;
  if (minutes < 60) return `${minutes}m${String(remainingSeconds).padStart(2, '0')}s`;
  const hours = Math.floor(minutes / 60);
  const remainingMinutes = minutes % 60;
  if (hours < 24) return `${hours}h${String(remainingMinutes).padStart(2, '0')}m`;
  const days = Math.floor(hours / 24);
  const remainingHours = hours % 24;
  return `${days}d${String(remainingHours).padStart(2, '0')}h`;
}

function localClock(milliseconds) {
  const date = new Date(milliseconds);
  return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
}

function idleSinceLabel(startedAt, now) {
  const date = new Date(startedAt);
  const today = new Date(now);
  const startDay = new Date(date.getFullYear(), date.getMonth(), date.getDate());
  const todayDay = new Date(today.getFullYear(), today.getMonth(), today.getDate());
  const days = Math.round((todayDay - startDay) / 86400000);
  if (days === 0) return `Idle since ${localClock(startedAt)}`;
  if (days === 1) return `Idle since yesterday ${localClock(startedAt)}`;
  const dateLabel = date.toLocaleDateString([], {
    month: 'short',
    day: 'numeric',
    ...(date.getFullYear() === today.getFullYear() ? {} : { year: 'numeric' }),
  });
  return `Idle since ${dateLabel} ${localClock(startedAt)}`;
}

function operationLabel(operation, now) {
  if (!operation) return '';
  const stages = [...(operation.stages || [])]
    .filter(stage => stage && stage.label)
    .sort((left, right) => (left.started_at_epoch_seconds || 0) - (right.started_at_epoch_seconds || 0));
  const oldestStage = stages[0] && epochSecondsMs(stages[0].started_at_epoch_seconds);
  const started = oldestStage ?? epochSecondsMs(operation.started_at_epoch_seconds);
  const clock = started == null ? '' : ` ${formatClock(now - started)}`;
  const labels = stages.map(stage => stage.label).join(' · ');
  const kind = {
    create: 'Starting',
    resume: 'Resuming',
    move: 'Moving',
    stop: 'Stopping',
    destroy: 'Destroying',
    cleanup: 'Cleaning up',
    checkpoint: 'Checkpointing',
  }[operation.kind] || String(operation.kind || 'Operation').replace(/-/g, ' ');
  return `${labels || kind}${clock}`;
}

function sessionActivityLabel(session, now = serverClockMs()) {
  if (session.operation) return operationLabel(session.operation, now);
  if (session.has_error && isTransitioningSession(session)) return 'Needs recovery';
  if (['starting', 'stopping', 'failed'].includes(session.lifecycle)) {
    return sessionLifecycleLabel(session);
  }
  const details = session.activity_details || {};
  const kind = details.kind;
  const turnStarted = epochMs(details.turn_started_at_ms);
  const stepStarted = epochMs(details.step_started_at_ms);
  const backgroundStarted = epochMs(details.background_started_at_ms);
  const idleStarted = epochMs(details.idle_since_ms);
  if (kind === 'step') {
    return `Step${stepStarted == null ? '' : ` ${formatClock(now - stepStarted)}`}`;
  }
  if (kind === 'turn') {
    const turn = turnStarted == null ? null : formatClock(now - turnStarted);
    const stepElapsed = stepStarted == null ? null : Math.max(0, now - stepStarted);
    const stepBaseElapsed = stepStarted == null && turnStarted != null
      ? Math.max(0, now - turnStarted)
      : stepElapsed;
    const clampedStep = stepBaseElapsed == null || turnStarted == null
      ? stepBaseElapsed
      : Math.min(stepBaseElapsed, Math.max(0, now - turnStarted));
    const step = clampedStep == null ? null : formatClock(clampedStep);
    return `Turn${turn ? ` ${turn}` : ''} · Step${step ? ` ${step}` : ''}`;
  }
  if (kind === 'background') {
    return `${details.label || 'Background'}${backgroundStarted == null ? '' : ` ${formatClock(now - backgroundStarted)}`}`;
  }
  if (kind === 'idle') return idleStarted == null ? 'Idle' : idleSinceLabel(idleStarted, now);
  if (kind === 'lifecycle') return details.label || sessionLifecycleLabel(session);
  if (kind) return details.label || kind;
  if (session.activity) return session.activity;
  if (session.is_idle && idleStarted != null) return idleSinceLabel(idleStarted, now);
  return sessionLifecycleLabel(session);
}

function updateSessionActivity(card, session) {
  card._activity.textContent = sessionActivityLabel(session);
  card._activity.title = card._activity.textContent;
}

function updateSessionClocks() {
  for (const card of sessionCards.values()) {
    if (card.isConnected === false || !card._session) continue;
    // This is intentionally the only per-tick mutation: card identity and
    // all controls stay put while a clock advances.
    card._activity.textContent = sessionActivityLabel(card._session);
  }
  const selected = snapshot?.sessions.find(session => session.id === currentSession);
  if (isTransitioningSession(selected)) {
    conversationTransitionStage.textContent = sessionActivityLabel(selected);
  }
}

function closeSessionMenu(restoreFocus = true) {
  if (!openSessionMenuId) return;
  const card = sessionCards.get(openSessionMenuId);
  const trigger = openSessionMenuTrigger || card?._menuTrigger;
  if (card?._menu) {
    card._menu.classList?.add('hidden');
    card._menuTrigger?.setAttribute('aria-expanded', 'false');
  }
  openSessionMenuId = null;
  openSessionMenuTrigger = null;
  if (restoreFocus && trigger?.isConnected !== false) trigger.focus?.({ preventScroll: true });
}

function openSessionMenu(sessionId, trigger, toggle = false) {
  const card = sessionCards.get(sessionId) || trigger?.closest?.('.session');
  if (!card || !card._menu || !card._menu.children.length) return false;
  if (openSessionMenuId === sessionId) {
    if (toggle) {
      closeSessionMenu();
      return false;
    }
    return true;
  }
  closeSessionMenu(false);
  card._menu.classList.remove('hidden');
  card._menuTrigger.setAttribute('aria-expanded', 'true');
  openSessionMenuId = sessionId;
  openSessionMenuTrigger = trigger || card._menuTrigger;
  card._menu.querySelector('button:not(:disabled)')?.focus({ preventScroll: true });
  return true;
}

function sessionCardFromTarget(target) {
  return target?.closest?.('.session[data-session-id]');
}

function cancelSessionPress() {
  if (!activeSessionPress) return;
  clearTimeout(activeSessionPress.timer);
  activeSessionPress = null;
}

function beginSessionPress(event) {
  // A completed long press may not produce the synthetic click on every
  // touch browser. A new pointer gesture is unambiguously a fresh action.
  suppressedSessionClickId = null;
  if (event.isPrimary === false) {
    cancelSessionPress();
    return;
  }
  if (event.button !== undefined && event.button !== 0) return;
  if (event.target?.closest?.('button, a, input, select, textarea')) return;
  const card = sessionCardFromTarget(event.target);
  if (!card || !card._session || !sessionMenuActions(card._session).length) return;
  if (activeSessionPress && activeSessionPress.pointerId !== event.pointerId) {
    cancelSessionPress();
    return;
  }
  cancelSessionPress();
  activeSessionPress = {
    id: card.dataset.sessionId,
    pointerId: event.pointerId,
    x: event.clientX,
    y: event.clientY,
    timer: setTimeout(() => {
      const current = sessionCards.get(card.dataset.sessionId);
      if (
        !activeSessionPress ||
        activeSessionPress.id !== card.dataset.sessionId ||
        current !== card ||
        card.isConnected === false ||
        !snapshot?.sessions.some(session => session.id === card.dataset.sessionId && session.workspace_id === selectedWorkspaceId()) ||
        !sessionMenuActions(card._session).length
      ) {
        cancelSessionPress();
        return;
      }
      suppressedSessionClickId = card.dataset.sessionId;
      activeSessionPress = null;
      openSessionMenu(card.dataset.sessionId, card._menuTrigger);
    }, 500),
  };
}

function moveSessionPress(event) {
  if (!activeSessionPress) return;
  if (activeSessionPress.pointerId !== event.pointerId) {
    cancelSessionPress();
    return;
  }
  const dx = event.clientX - activeSessionPress.x;
  const dy = event.clientY - activeSessionPress.y;
  if (Math.hypot(dx, dy) > 10) cancelSessionPress();
}

// Durable "running" means the session is alive, not that a turn or background
// command is running. Leave activity to the separate turn/BG/idle indicator.
function sessionLifecycleLabel(session) {
  const labels = {
    live: 'Live',
    starting: 'Starting',
    stopping: 'Stopping',
    stopped: 'Stopped',
    failed: 'Failed',
  };
  if (session.lifecycle && labels[session.lifecycle]) return labels[session.lifecycle];
  return session.state === 'running' ? 'Live' : session.state || 'Unknown';
}

function action(label, className, data) {
  const node = button(label, className, data);
  node.disabled = pendingActions.has(`${data.action}:${data.id}`);
  return node;
}

/// Find a session card for an event without treating one of its controls as
/// a request to open the conversation. Card summaries remain ordinary text:
/// selecting text is not a separate interaction the card needs to preserve.
function sessionCardFromEvent(event) {
  const target = event.target;
  if (!target || target.closest('button')) return null;
  const card = target.closest('.session[data-session-id]');
  return card?.dataset.openable === 'true' ? card : null;
}

function openSessionCard(event) {
  const card = sessionCardFromEvent(event);
  if (!card) return false;
  if (event.type && event.type !== 'click') suppressedSessionClickId = null;
  if (suppressedSessionClickId === card.dataset.sessionId) {
    suppressedSessionClickId = null;
    return false;
  }
  closeSessionMenu(false);
  navigate({ name: 'conversation', sessionId: card.dataset.sessionId });
  return true;
}

function handleSessionCardKeydown(event) {
  const trigger = event.target?.closest?.('button[data-session-menu]');
  if (trigger && ((event.key === 'F10' && event.shiftKey) || event.key === 'ContextMenu')) {
    event.preventDefault();
    openSessionMenu(trigger.dataset.sessionMenu, trigger);
    return;
  }
  if ((event.key === 'F10' && event.shiftKey) || event.key === 'ContextMenu') {
    const card = sessionCardFromTarget(event.target);
    if (!card || !card._session || !sessionMenuActions(card._session).length) return;
    event.preventDefault();
    openSessionMenu(card.dataset.sessionId, card._menuTrigger);
    return;
  }
  if (event.key !== 'Enter' && event.key !== ' ') return;
  if (!openSessionCard(event)) return;
  event.preventDefault();
}

function handleSessionMenuKeydown(event) {
  const menu = event.target?.closest?.('.session-menu');
  if (!menu) return;
  const controls = [...menu.querySelectorAll('button:not(:disabled)')];
  if (event.key === 'Escape') {
    event.preventDefault();
    closeSessionMenu();
    return;
  }
  if (event.key === 'Tab') {
    // Let the browser's normal tab order continue from the menu item. The
    // trigger is restored only for Escape and pointer dismissal.
    closeSessionMenu(false);
    return;
  }
  if (!controls.length) return;
  const index = controls.indexOf(event.target);
  let next = null;
  if (event.key === 'ArrowDown') next = controls[(index + 1) % controls.length];
  if (event.key === 'ArrowUp') next = controls[(index - 1 + controls.length) % controls.length];
  if (event.key === 'Home') next = controls[0];
  if (event.key === 'End') next = controls.at(-1);
  if (next) {
    event.preventDefault();
    next.focus({ preventScroll: true });
  }
}

// ---------------------------------------------------------------------------
// The other pages
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// The New wizard
// ---------------------------------------------------------------------------
//
// One decision per screen, in the order the terminal asks them, ending in a
// review that names every choice before anything is committed. A phone keyboard
// covering a modal is how the previous single flat form became unusable, so
// this is a route rather than a dialog.

/// The steps, in order. `applies` lets a step drop out — a container target has
/// no project directory to name, and a bundle with nothing dirty has nothing to
/// confirm.
const NEW_STEPS = [
  { key: 'profile', title: 'Profile', applies: () => true },
  { key: 'target', title: 'Target', applies: () => true },
  { key: 'project', title: 'Project', applies: () => true },
  { key: 'dirty', title: 'Uncommitted changes', applies: draft => draft.dirty.length > 0 },
  { key: 'review', title: 'Review', applies: () => true },
];

let newDraft = null;
let pendingNewPreflight = null;
let renderedNewDraft = null;
let renderedNewSignature = null;

function freshDraft() {
  return {
    workspaceId: selectedWorkspaceId(),
    step: 0,
    profileId: snapshot?.profiles[0]?.id || '',
    targetId: snapshot?.targets[0]?.id || '',
    bundleId: snapshot?.bundles[0]?.id || '',
    projectDirectory: '',
    title: '',
    dirty: [],
    acknowledged: false,
    preflighted: false,
    bundleSource: '',
    creatingBundle: false,
    showBundleSource: false,
    projectDirectories: {},
  };
}

function targetIsBare(targetId) {
  return (
    snapshot?.targets.find(target => target.id === targetId)?.requires_project_directory === true
  );
}

function visibleSteps() {
  return NEW_STEPS.filter(step => step.applies(newDraft));
}

/// The title the daemon would derive, shown on review so the person sees the
/// name before committing rather than discovering it afterwards.
function derivedTitle() {
  const project = targetIsBare(newDraft.targetId)
    ? newDraft.projectDirectory.replace(/\/+$/, '').split('/').pop() || newDraft.projectDirectory
    : newDraft.bundleId;
  return `${project} via ${newDraft.profileId}`;
}

function renderNewForm() {
  if (!newDraft || newDraft.workspaceId !== selectedWorkspaceId()) {
    newDraft = freshDraft();
    newError.textContent = '';
  }
  const steps = visibleSteps();
  newDraft.step = Math.min(newDraft.step, steps.length - 1);
  const step = steps[newDraft.step];
  // A snapshot often only changes another session. Keep the actual controls
  // mounted so it cannot interrupt a touch gesture or dismiss a native picker.
  const signature = JSON.stringify({
    step: step.key,
    profiles: step.key === 'profile' ? snapshot.profiles.map(p => [p.id, p.harness_kind]) : null,
    targets: step.key === 'target' ? snapshot.targets.map(t => [t.id, t.kind]) : null,
    project: step.key === 'project' ? [newDraft.targetId, snapshot.bundles, snapshot.targets.find(t => t.id === newDraft.targetId)?.recent_project_directories, newDraft.showBundleSource] : null,
    dirty: step.key === 'dirty' || step.key === 'review' ? newDraft.dirty : null,
    checking: pendingNewPreflight === newDraft,
    committing: Boolean(newDraft.committing),
    creating: newDraft.creatingBundle,
  });
  if (renderedNewDraft === newDraft && renderedNewSignature === signature) return;
  const focused = newStep.contains(document.activeElement) ? document.activeElement : null;
  const caret = focused?.id && focused.type === 'text'
    ? { id: focused.id, start: focused.selectionStart, end: focused.selectionEnd }
    : null;
  renderedNewDraft = newDraft;
  renderedNewSignature = signature;
  newProgress.textContent = `Step ${newDraft.step + 1} of ${steps.length} · ${step.title}`;
  newBackButton.disabled = newDraft.step === 0;
  newNextButton.textContent = step.key === 'review' ? 'Start' : 'Next';

  const body = document.createDocumentFragment();
  switch (step.key) {
    case 'profile': {
      body.append(
        pickerField('Profile', 'new-profile', snapshot.profiles, newDraft.profileId, value => {
          newDraft.profileId = value;
        }),
      );
      break;
    }
    case 'target': {
      body.append(
        pickerField('Target', 'new-target', snapshot.targets, newDraft.targetId, value => {
          newDraft.projectDirectories[newDraft.targetId] = newDraft.projectDirectory;
          newDraft.targetId = value;
          newDraft.projectDirectory = newDraft.projectDirectories[value] ?? snapshot.targets.find(t => t.id === value)?.recent_project_directories?.[0] ?? '';
          // Changing the target changes which project question is asked, and
          // invalidates anything the previous project answer was checked for.
          newDraft.preflighted = false;
          newDraft.dirty = [];
          newDraft.acknowledged = false;
        }),
      );
      break;
    }
    case 'project': {
      if (targetIsBare(newDraft.targetId)) {
        body.append(el('p', 'dim', 'Raw hosts open an existing checkout directly. Bundles are used for container targets.'));
        const recents = snapshot.targets.find(t => t.id === newDraft.targetId)?.recent_project_directories || [];
        if (!newDraft.projectDirectory && !Object.hasOwn(newDraft.projectDirectories, newDraft.targetId)) {
          newDraft.projectDirectory = recents[0] || '';
        }
        if (recents.length) {
          const recentList = el('div', 'recent-projects');
          recentList.append(el('p', 'dim', 'Recent projects on this host'));
          for (const directory of recents) {
            const pick = el('button', 'secondary recent-project', directory);
            pick.type = 'button';
            pick.onclick = () => {
              newDraft.projectDirectory = directory;
              newDraft.projectDirectories[newDraft.targetId] = directory;
              newDraft.preflighted = false;
              document.querySelector('#new-project-directory').value = directory;
            };
            recentList.append(pick);
          }
          body.append(recentList);
        }
        body.append(
          textField(
            'Project directory',
            'new-project-directory',
            newDraft.projectDirectory,
            value => {
              newDraft.projectDirectory = value;
              newDraft.projectDirectories[newDraft.targetId] = value;
              newDraft.preflighted = false;
            },
          ),
        );
      } else {
        body.append(
          pickerField('Bundle', 'new-bundle', snapshot.bundles, newDraft.bundleId, value => {
            newDraft.bundleId = value;
            newDraft.preflighted = false;
            newDraft.dirty = [];
            newDraft.acknowledged = false;
          }),
        );
        const create = el('button', 'secondary', 'Create bundle');
        create.type = 'button';
        create.onclick = () => {
          newDraft.showBundleSource = !newDraft.showBundleSource;
          renderNewForm();
          document.querySelector('#new-bundle-source')?.focus();
        };
        body.append(create);
        if (newDraft.showBundleSource || !snapshot.bundles.length) {
          body.append(textField('Repository source', 'new-bundle-source', newDraft.bundleSource, value => { newDraft.bundleSource = value; }));
          body.append(el('p', 'dim', 'GitHub owner/repository or URL, or an existing repository path on the controller host. Creates a reusable bundle in your shared configuration.'));
          const save = el('button', '', newDraft.creatingBundle ? 'Creating bundle…' : 'Save bundle');
          save.type = 'button';
          save.onclick = createNewBundle;
          body.append(save);
        }
      }
      body.append(
        textField('Title (optional)', 'new-title', newDraft.title, value => {
          newDraft.title = value;
        }),
      );
      break;
    }
    case 'dirty': {
      body.append(
        el(
          'p',
          '',
          'These repositories have uncommitted changes. Starting a session copies them as they are.',
        ),
      );
      const list = el('ul');
      for (const repository of newDraft.dirty) list.append(el('li', '', repository));
      body.append(list);
      const label = el('label', 'field-inline');
      const box = el('input');
      box.type = 'checkbox';
      box.id = 'new-dirty-ack';
      box.checked = newDraft.acknowledged;
      box.onchange = () => {
        newDraft.acknowledged = box.checked;
      };
      label.append(box, el('span', '', 'Start anyway'));
      body.append(label);
      break;
    }
    default: {
      const review = el('dl', 'review');
      const rows = [
        ['Profile', newDraft.profileId],
        ['Target', newDraft.targetId],
        targetIsBare(newDraft.targetId)
          ? ['Project directory', newDraft.projectDirectory]
          : ['Bundle', newDraft.bundleId],
        ['Name', newDraft.title.trim() || derivedTitle()],
      ];
      if (newDraft.dirty.length) rows.push(['Uncommitted changes', newDraft.dirty.join(', ')]);
      for (const [term, value] of rows) {
        review.append(el('dt', '', term), el('dd', '', value));
      }
      body.append(review);
    }
  }
  newStep.replaceChildren(body);
  const checking = pendingNewPreflight === newDraft;
  if (checking) {
    newNextButton.textContent = 'Checking…';
    newBackButton.disabled = true;
  }
  const busy = checking || newDraft.committing === true || newDraft.creatingBundle;
  newNextButton.disabled = busy;
  newBackButton.disabled ||= busy;
  for (const input of newStep.querySelectorAll('input, select, button')) input.disabled = busy;
  if (caret && !busy) {
    const input = document.getElementById(caret.id);
    input?.focus({ preventScroll: true });
    input?.setSelectionRange(caret.start, caret.end);
  }
}

function pickerField(label, id, items, value, onChange) {
  const field = choiceControl({
    label,
    options: items.map(item => ({ value: item.id, title: item.label ?? item.id, description: item.kind || item.harness_kind })),
    values: [value],
    onChange: () => onChange(field.querySelector('input:checked')?.value || ''),
  });
  field.id = id;
  if (!items.length) field.append(el('p', 'dim', `No ${label.toLowerCase()}s configured.`));
  return field;
}

async function createNewBundle() {
  const draft = newDraft;
  if (!draft || draft.creatingBundle) return;
  const source = draft.bundleSource.trim();
  if (!source) {
    newError.textContent = 'Enter a repository source for the bundle.';
    return;
  }
  draft.creatingBundle = true;
  newError.textContent = '';
  renderNewForm();
  try {
    const result = await request('/api/bundles', { method: 'POST', body: JSON.stringify({ source }) });
    if (newDraft !== draft) return;
    draft.bundleId = result.bundle_id;
    draft.showBundleSource = false;
    draft.bundleSource = '';
    draft.preflighted = false;
    draft.dirty = [];
    draft.acknowledged = false;
    await refresh();
  } catch (error) {
    if (newDraft === draft) newError.textContent = error.message;
  } finally {
    draft.creatingBundle = false;
    if (newDraft === draft) renderNewForm();
  }
}

function textField(label, id, value, onInput) {
  const field = el('label', 'field');
  field.append(el('span', '', label));
  const input = el('input');
  input.id = id;
  input.value = value;
  input.oninput = () => onInput(input.value);
  field.append(input);
  return field;
}

/// Ask the daemon whether this combination would launch, and what to warn
/// about, before the person commits to it.
async function preflightNew() {
  const draft = newDraft;
  if (pendingNewPreflight === draft) return false;
  const bare = targetIsBare(draft.targetId);
  pendingNewPreflight = draft;
  renderNewForm();
  try {
    const answer = await request('/api/preflight/new', {
      method: 'POST',
      body: JSON.stringify({
        workspace_id: selectedWorkspaceId(),
        profile_id: draft.profileId,
        bundle_id: draft.bundleId,
        target_id: draft.targetId,
        project_directory: bare ? draft.projectDirectory : null,
      }),
    });
    if (newDraft !== draft) return false;
    draft.dirty = answer.dirty_repositories || [];
    draft.preflighted = true;
    // A set the person has not seen cannot already be acknowledged.
    draft.acknowledged = false;
    return true;
  } catch (error) {
    if (newDraft !== draft) return false;
    throw error;
  } finally {
    if (pendingNewPreflight === draft) pendingNewPreflight = null;
    if (newDraft === draft) renderNewForm();
  }
}

async function advanceNew() {
  if (!newDraft || newDraft.creatingBundle || newDraft.committing || pendingNewPreflight === newDraft) return;
  const steps = visibleSteps();
  const step = steps[newDraft.step];
  newError.textContent = '';
  if (step.key === 'profile' && !snapshot.profiles.some(p => p.id === newDraft.profileId)) {
    newError.textContent = 'Choose an available profile before continuing.';
    return;
  }
  if (step.key === 'target' && !snapshot.targets.some(t => t.id === newDraft.targetId)) {
    newError.textContent = 'Choose an available target before continuing.';
    return;
  }

  if (step.key === 'project') {
    if (!targetIsBare(newDraft.targetId) && !snapshot.bundles.some(b => b.id === newDraft.bundleId)) {
      newError.textContent = 'Choose or create a bundle before continuing.';
      return;
    }
    if (targetIsBare(newDraft.targetId) && !newDraft.projectDirectory.trim()) {
      newError.textContent = 'Name the project directory to open.';
      return;
    }
    if (!(await preflightNew())) return;
    newDraft.step = Math.min(newDraft.step + 1, visibleSteps().length - 1);
    renderNewForm();
    return;
  }
  if (step.key === 'dirty' && !newDraft.acknowledged) {
    newError.textContent = 'Confirm before starting over uncommitted changes.';
    return;
  }
  if (step.key !== 'review') {
    newDraft.step += 1;
    renderNewForm();
    return;
  }
  await commitNew();
}

async function commitNew() {
  const draft = newDraft;
  if (draft.committing) return;
  const bare = targetIsBare(newDraft.targetId);
  const body = {
    action: 'new',
    workspace_id: draft.workspaceId,
    profile_id: newDraft.profileId,
    bundle_id: newDraft.bundleId,
    target_id: newDraft.targetId,
    project_directory: bare ? newDraft.projectDirectory : null,
    dirty_ack: newDraft.acknowledged ? newDraft.dirty : [],
  };
  if (newDraft.title.trim()) body.title = newDraft.title.trim();
  draft.committing = true;
  renderNewForm();
  try {
    await request('/api/actions', { method: 'POST', body: JSON.stringify(body) });
    if (newDraft !== draft) return;
    await refresh();
    if (newDraft !== draft) return;
    navigate({ name: 'dashboard', workspaceId: draft.workspaceId });
  } catch (err) {
    if (newDraft === draft) newError.textContent = err.message;
  } finally {
    draft.committing = false;
    if (newDraft === draft) renderNewForm();
  }
}

/// Sessions that are not live and that Mjolnir owns, which is what "resume" means.
///
/// A session that cannot resume anywhere is still listed, with one plain
/// sentence saying why and where to finish it. Hiding it would leave a person
/// looking for a session they know exists.
const resumableCards = new Map();
function renderResumable() {
  const list = (snapshot.sessions || []).filter(session => session.capabilities?.resume);
  for (const id of resumableCards.keys()) if (!list.some(session => session.id === id)) resumableCards.delete(id);
  if (!list.length) {
    resumable.replaceChildren(el('p', 'dim', 'No sessions to resume.'));
    return;
  }
  const cards = list.map(session => {
    const signature = JSON.stringify([session, snapshot.profiles.map(p => [p.id, p.harness_kind])]);
    let cached = resumableCards.get(session.id);
    if (!cached || cached.signature !== signature) {
      cached = { signature, card: resumableCard(session) };
      resumableCards.set(session.id, cached);
    }
    const resume = cached.card.querySelector('button[data-action="resume"]');
    if (resume) resume.disabled = pendingActions.has(`resume:${session.id}`);
    return cached.card;
  });
  if (cards.length !== resumable.children.length || cards.some((card, index) => resumable.children[index] !== card))
    resumable.replaceChildren(...cards);
}

function resumableCard(session) {
  const card = el('article', 'card session');
  const recovery = session.move_recovery;
  const sourceProfile = recovery?.source_profile_id || session.profile_id;
  const sourceTarget = recovery?.source_target_template_id || session.target_id;
  card.dataset.sessionId = session.id;
  card.append(el('h3', '', session.title));
  card.append(el('p', 'dim', `${sessionLifecycleLabel(session)} · ${sourceProfile}`));
  if (session.has_error) {
    card.append(el('p', '', 'The previous operation failed. The verified checkpoint remains available; resume with the source settings or retry the move from the dashboard recovery card.'));
  }
  if (recovery) {
    card.append(el('p', 'dim', `Previous Move source: ${sourceProfile} / ${sourceTarget}. The recovery controls use these settings and do not promise to revive the old process.`));
    if (recovery.queue_admission_started && !recovery.queue_admission_finished) {
      card.append(el('p', 'dim', 'Queued work already began on the destination; retry Move there before considering any other recovery.'));
      return card;
    }
  }

  if (!session.compatible_resume_targets?.length) {
    card.append(
      el(
        'p',
        '',
        'This session cannot resume on any target configured here. Finish it in the terminal, where the repair and import options live.',
      ),
    );
    return card;
  }

  const profilePicker = pickerField('Profile', `resume-profile-${session.id}`, snapshot.profiles, sourceProfile, () => {});
  profilePicker.dataset.role = 'resume-profile';
  card.append(profilePicker);

  const targetPicker = pickerField(
    'Target', `resume-target-${session.id}`,
    session.compatible_resume_targets.map(id => ({ id })),
    session.compatible_resume_targets.includes(sourceTarget) ? sourceTarget : session.compatible_resume_targets[0],
    () => {},
  );
  targetPicker.dataset.role = 'resume-target';
  card.append(targetPicker);

  const queued = (session.queued_prompts || []).length;
  if (queued) {
    const picker = pickerField(
      `${queued} queued prompt${queued === 1 ? '' : 's'}`, `resume-queue-${session.id}`,
      [
        { id: 'start', label: 'Run them after resuming' },
        { id: 'discard', label: 'Discard them' },
      ],
      'start',
      () => {},
    );
    picker.dataset.role = 'resume-queue';
    card.append(picker);
  }

  const row = el('div', 'row');
  const resume = action('Resume', '', {
    action: 'resume',
    id: session.id,
    profile: sourceProfile,
    target: sourceTarget,
  });
  // Keep the recorded source settings with this authenticated action. They
  // are user-selected mounts/resource sizing, not diagnostics; the server
  // still validates them before handing them to the daemon.
  resume._resumeRecovery = recovery;
  row.append(resume);
  card.append(row);
  return card;
}

// ---------------------------------------------------------------------------
// Move confirmation
// ---------------------------------------------------------------------------
//
// Moving is deliberately a two-step route. The first request is read-only and
// returns a fingerprinted preparation from the daemon; only the second request
// can interrupt the source. Keeping the preparation in this route also makes a
// browser reconnect harmless: it cannot accidentally submit a changed target
// under an old confirmation.

function freshMoveDraft(session) {
  const compatible = session.compatible_resume_targets || [];
  const recovery = session.move_recovery;
  const recoveryTarget = recovery?.destination_target_template_id;
  return {
    workspaceId: session.workspace_id || selectedWorkspaceId(),
    sessionId: session.id,
    profileId: recovery?.destination_profile_id || session.profile_id || snapshot.profiles[0]?.id || '',
    targetId: compatible.includes(recoveryTarget)
      ? recoveryTarget
      : compatible.includes(session.target_id) ? session.target_id : compatible[0] || '',
    clearResourceAllocation: recovery?.clear_resource_allocation === true,
    destinationAdditionalMounts: recovery ? (recovery.destination_additional_mounts || []) : null,
    destinationResourceAllocation: recovery ? (recovery.destination_resource_allocation ?? null) : null,
    queueLocked: recovery?.queue_admission_started === true && recovery?.queue_admission_finished !== true,
    preparation: null,
    preparing: false,
    committing: false,
    acknowledge: false,
    queue: recovery?.queue || 'discard',
  };
}

function moveQueueItemText(item) {
  if (item?.kind && typeof item.kind === 'object') {
    const [kind, details] = Object.entries(item.kind)[0] || [];
    if (kind === 'set_config') return `/${details?.key || 'config'} ${details?.value || ''}`.trim();
  }
  const content = Array.isArray(item?.content) ? item.content : [];
  const text = content.find(block => block?.type === 'text')?.text;
  const image = content.find(block => block?.type === 'image');
  if (typeof text === 'string' && text) {
    if (image) return `${text} [Image attachment: ${image.mimeType || image.mime_type || 'image'}]`;
    return text;
  }
  if (image) return `[Image attachment: ${image.mimeType || image.mime_type || 'image'}]`;
  try {
    return JSON.stringify(item?.content || item).slice(0, 400);
  } catch (_) {
    return 'Queued command';
  }
}

function renderMoveForm() {
  if (!moveStep || route.name !== 'move') return;
  const session = snapshot.sessions.find(item => item.id === route.sessionId);
  if (!session) return;
  const recoveryTarget = session.move_recovery?.destination_target_template_id;
  if (!moveDraft || moveDraft.sessionId !== session.id) moveDraft = freshMoveDraft(session);
  const draft = moveDraft;
  const preparation = draft.preparation;
  moveProgress.textContent = preparation ? 'Review the destination and confirm the interruption.' : 'Choose a compatible destination. The source is not changed during preparation.';
  moveStep.replaceChildren();

  if (!preparation) {
    moveStep.append(el('p', '', `Move ${session.title || session.id} while keeping its session identity, transcript, and recoverable workspace state.`));
    const profilePicker = pickerField('Profile', `move-profile-${session.id}`, snapshot.profiles, draft.profileId, value => {
      if (draft.queueLocked) return;
      draft.profileId = value;
      draft.preparation = null;
    });
    moveStep.append(profilePicker);
    const targetIds = [...new Set([
      ...(session.compatible_resume_targets || []),
      recoveryTarget,
    ].filter(Boolean))];
    const targets = targetIds.map(id => snapshot.targets.find(target => target.id === id) || { id });
    const targetPicker = pickerField('Target', `move-target-${session.id}`, targets, draft.targetId, value => {
      if (draft.queueLocked) return;
      draft.targetId = value;
      draft.preparation = null;
    });
    if (draft.queueLocked) {
      for (const input of [...profilePicker.querySelectorAll('input'), ...targetPicker.querySelectorAll('input')]) {
        input.disabled = true;
      }
    }
    moveStep.append(targetPicker);
    moveStep.append(el('p', 'dim', 'Move rebuilds a fresh environment. Existing resource sizing and attached directories are retained. Installed packages and files outside the declared workspace are not migrated.'));
    const clearResources = el('label', 'field-inline');
    const clearResourcesInput = document.createElement('input');
    clearResourcesInput.type = 'checkbox';
    clearResourcesInput.checked = draft.clearResourceAllocation;
    clearResourcesInput.disabled = draft.queueLocked;
    clearResourcesInput.onchange = () => {
      draft.clearResourceAllocation = clearResourcesInput.checked;
      draft.preparation = null;
    };
    clearResources.append(clearResourcesInput, el('span', '', 'Clear inherited resource sizing and use destination defaults'));
    moveStep.append(clearResources);
    if (draft.queueLocked) {
      moveStep.append(el('p', 'dim', 'The destination and resource settings are locked to the existing destination because queue admission already began.'));
    }
    moveStep.append(el('p', 'dim', 'Use this only when intentionally removing the current container or host sizing. Attached directories stay fixed to this workspace in the web viewer.'));
    moveNextButton.textContent = 'Prepare move';
  } else {
    const target = snapshot.targets.find(item => item.id === (preparation.selection.target_template_id || session.target_id));
    const profile = snapshot.profiles.find(item => item.id === (preparation.selection.profile_id || session.profile_id));
    moveStep.append(el('p', '', `From ${preparation.source_profile_id} / ${preparation.source_target_template_id} to ${profile?.id || preparation.selection.profile_id || session.profile_id} / ${target?.id || preparation.selection.target_template_id || session.target_id}.`));
    moveStep.append(el('p', 'dim', preparation.selection.clear_resource_allocation
      ? 'Resource sizing: use destination defaults. Attached directories remain fixed to this workspace.'
      : 'Resource sizing and attached directories: retain the source workspace settings.'));
    moveStep.append(el('p', 'dim', preparation.cross_harness ? 'This is a cross-harness handoff. Harness-private state is rebuilt from the canonical transcript.' : 'The same harness session state will be restored when supported.'));
    if (preparation.active) {
      const warning = el('label', 'move-warning');
      const check = document.createElement('input');
      check.type = 'checkbox';
      check.checked = draft.acknowledge;
      check.onchange = () => {
        draft.acknowledge = check.checked;
        renderMoveForm();
      };
      warning.append(check, el('span', '', 'Interrupt the active turn and checkpoint the session before rebuilding it.'));
      moveStep.append(warning);
    }
    const queued = preparation.queued_commands || [];
    if (queued.length) {
      moveStep.append(el('h3', '', `${queued.length} queued command${queued.length === 1 ? '' : 's'}`));
      const list = el('div', 'move-queue');
      list.append(...queued.map((item, index) => el('div', 'queue-item', `${index + 1}. ${moveQueueItemText(item)}`)));
      moveStep.append(list);
      const queuePicker = choiceControl({
        label: 'After the destination is ready',
        options: draft.queueLocked
          ? [{
            value: draft.queue,
            title: draft.queue === 'start' ? 'Continue queued work on this destination' : 'Keep queued work discarded',
            description: 'The previous destination already admitted this choice; retrying with another choice could replay work.',
          }]
          : [
            { value: 'discard', title: 'Discard queued work', description: 'Start idle on the destination (default).' },
            { value: 'start', title: 'Run queued work', description: 'Accept the existing commands in order after readiness.' },
          ],
        values: [draft.queue],
        onChange: () => {
          draft.queue = queuePicker.querySelector('input:checked')?.value || 'discard';
        },
      });
      moveStep.append(queuePicker);
    } else {
      moveStep.append(el('p', 'dim', draft.queueLocked
        ? `Queue admission already began with ${draft.queue}; retrying must use the same choice on this destination.`
        : 'No queued work is waiting; the destination will open idle.'));
    }
    moveNextButton.textContent = 'Confirm move';
  }
  const busy = draft.preparing || draft.committing;
  moveNextButton.disabled = busy || (preparation?.active === true && !draft.acknowledge);
  moveBackButton.disabled = busy;
  for (const input of moveStep.querySelectorAll('input, select, button')) input.disabled = busy;
}

async function prepareMove() {
  const draft = moveDraft;
  if (!draft || draft.preparing) return;
  if (!draft.profileId && !draft.targetId) {
    moveError.textContent = 'Choose a profile, a target, or both.';
    return;
  }
  draft.preparing = true;
  moveError.textContent = '';
  renderMoveForm();
  try {
    draft.preparation = await request('/api/moves/prepare', {
      method: 'POST',
      body: JSON.stringify({
        session_id: draft.sessionId,
        profile_id: draft.profileId || null,
        target_template_id: draft.targetId || null,
        clear_resource_allocation: draft.clearResourceAllocation,
        additional_mounts: draft.destinationAdditionalMounts,
        resource_allocation: draft.destinationResourceAllocation,
      }),
    });
  } catch (error) {
    moveError.textContent = error.message;
  } finally {
    draft.preparing = false;
    if (moveDraft === draft) renderMoveForm();
  }
}

async function commitMove() {
  const draft = moveDraft;
  if (!draft || !draft.preparation || draft.committing) return;
  draft.committing = true;
  moveError.textContent = '';
  renderMoveForm();
  try {
    await request('/api/actions', {
      method: 'POST',
      body: JSON.stringify({
        action: 'move',
        request: {
          preparation: draft.preparation,
          queue: (draft.preparation.queued_commands || []).length || draft.queueLocked ? draft.queue : null,
          acknowledge_interruption: draft.acknowledge,
        },
      }),
    });
    await refresh();
    announce(`Moving ${draft.sessionId}`);
    navigate({ name: 'dashboard', workspaceId: draft.workspaceId });
  } catch (error) {
    moveError.textContent = error.message;
  } finally {
    draft.committing = false;
    if (moveDraft === draft) renderMoveForm();
  }
}

async function advanceMove() {
  if (!moveDraft?.preparation) return prepareMove();
  return commitMove();
}

/// Bytes as a person reads them.
function formatBytes(bytes) {
  if (bytes === undefined || bytes === null) return null;
  const units = ['B', 'KiB', 'MiB', 'GiB', 'TiB'];
  let value = Number(bytes);
  let unit = 0;
  while (value >= 1024 && unit < units.length - 1) {
    value /= 1024;
    unit += 1;
  }
  return `${value < 10 && unit > 0 ? value.toFixed(1) : Math.round(value)} ${units[unit]}`;
}

/// The band a percentage falls in, matching the terminal's thresholds.
///
/// The terminal colours quota by headroom remaining and target load by the
/// inverse, so a busy machine and an exhausted limit both read red.
function band(percentRemaining) {
  if (percentRemaining === null || percentRemaining === undefined) return '';
  if (percentRemaining <= 20) return 'reading-low';
  if (percentRemaining <= 50) return 'reading-mid';
  return 'reading-high';
}

/// The freshness of one reading, as a word.
///
/// Four states, and each is said rather than implied: there has never been a
/// reading, one is being taken now, the last one is older than it should be,
/// or the last probe failed and the previous reading is what is on screen.
function freshness(reading) {
  if (reading.has_error) return { word: 'probe failed', className: 'reading-low' };
  if (reading.refreshing && reading.sampled_at_epoch_seconds === undefined) {
    return { word: 'loading', className: '' };
  }
  if (reading.refreshing) return { word: 'refreshing', className: '' };
  if (reading.stale) return { word: 'stale', className: 'reading-mid' };
  return null;
}

function renderTargets() {
  const readings = snapshot.capacity || [];
  if (!readings.length) {
    targetsPanel.replaceChildren(el('p', 'dim', 'No hosts or fleets are configured to be probed.'));
    return;
  }
  targetsPanel.replaceChildren(
    ...readings.map(reading => {
      const card = el('article', 'card');
      const heading = el('h3');
      heading.append(el('span', '', reading.label));
      const state = freshness(reading);
      if (state) heading.append(el('span', `pill ${state.className}`, state.word));
      card.append(heading);
      card.append(el('p', 'dim', reading.target_ids.join(', ')));

      const rows = [];
      if (reading.cpu_percent !== undefined) {
        // CPU is load, so its band is the inverse of the headroom bands.
        rows.push(['CPU', `${reading.cpu_percent}%`, band(100 - reading.cpu_percent)]);
      }
      if (reading.memory_total_bytes) {
        const used = reading.memory_used_bytes ?? 0;
        const percent = Math.min(100, Math.round((used / reading.memory_total_bytes) * 100));
        rows.push([
          'Memory',
          `${percent}% of ${formatBytes(reading.memory_total_bytes)}`,
          band(100 - percent),
        ]);
      }
      if (reading.logical_cores) rows.push(['Cores', String(reading.logical_cores), '']);
      if (reading.disk_total_bytes) {
        rows.push(['Disk', formatBytes(reading.disk_total_bytes), '']);
      }
      if (reading.virtual_machines !== undefined) {
        rows.push([
          'Machines',
          `${reading.virtual_machines} VM${reading.virtual_machines === 1 ? '' : 's'}`,
          '',
        ]);
      }
      if (!rows.length) {
        card.append(el('p', 'dim', 'No reading yet.'));
      } else {
        const list = el('dl', 'readings');
        for (const [term, value, className] of rows) {
          list.append(el('dt', '', term), el('dd', className, value));
        }
        card.append(list);
      }
      card.append(refreshRow('refresh-capacity', { target_id: reading.id }));
      return card;
    }),
  );
}

function renderQuota() {
  const focused = document.activeElement;
  const focusedProfile = focused?.closest('.quota-profile')?.dataset.profileId;
  const focusedControl = focused?.matches('summary') ? 'summary' : focused?.matches('button[data-refresh]') ? 'button[data-refresh]' : null;
  const expanded = new Set(
    [...quotaPanel.querySelectorAll('details[open]')].map(row => row.dataset.profileId),
  );
  const profiles = snapshot.profiles || [];
  if (!profiles.length) {
    quotaPanel.replaceChildren(el('p', 'dim', 'No profiles configured.'));
    return;
  }
  // Keep the provider's actual period labels. Missing windows are not zero,
  // and an unfamiliar provider must not disappear from the overview.
  const labels = [...new Set(profiles.flatMap(profile =>
    (profile.quota?.windows || []).map(window => window.label),
  ))].sort((a, b) => {
    // Match the TUI: weekly quota first, then the five-hour window.
    const rank = label => label === 'Week' ? 0 : label === '5H' ? 1 : 2;
    return rank(a) - rank(b) || a.localeCompare(b);
  });
  quotaPanel.style.setProperty('--quota-columns', Math.max(1, labels.length));
  const heading = el('div', 'quota-overview-heading');
  heading.append(el('span', '', '% left'));
  for (const label of labels) heading.append(el('span', '', label));
  const hint = el('p', 'dim quota-hint', 'Tap a profile for resets and details.');
  quotaPanel.replaceChildren(
    hint,
    heading,
    ...profiles.map(profile => {
      const disclosure = el('details', 'quota-profile');
      disclosure.dataset.profileId = profile.id;
      disclosure.open = expanded.has(profile.id);
      const summary = el('summary', 'quota-overview-row');
      const quota = profile.quota;
      const name = el('span', 'quota-profile-name', profile.id);
      if (quota?.has_error) name.append(el('small', 'reading-low', 'probe failed'));
      else if (quota?.stale) name.append(el('small', 'reading-mid', 'stale'));
      summary.append(name);
      const spoken = [profile.id, quota?.has_error ? 'probe failed; last reading' : quota?.stale ? 'stale reading' : ''];
      if (quota?.windows?.length) {
        for (const label of labels) {
          const window = quota.windows.find(window => window.label === label);
          const used = window?.percent_used;
          const remaining = used == null ? null : 100 - used;
          const warning = window?.projects_exhaustion_before_reset;
          const value = window ? remaining === null ? '?' : `${remaining}%` : '';
          const cell = el('span', `quota-value ${band(remaining)}`, value + (warning ? ' !' : ''));
          const description = `${label}: ${window ? remaining === null ? 'unknown' : `${remaining}% left` : 'not reported'}${warning ? ', projected to run out before reset' : ''}`;
          cell.title = description;
          summary.append(cell);
          spoken.push(description);
        }
      } else {
        const state = el('span', 'quota-no-windows dim', quota?.has_error ? 'Unavailable' : quota?.summary || 'No reading yet');
        summary.append(state);
        spoken.push(state.textContent);
      }
      summary.append(el('span', 'quota-chevron', ''));
      summary.lastChild.setAttribute('aria-hidden', 'true');
      summary.setAttribute('aria-label', spoken.filter(Boolean).join('. '));
      disclosure.append(summary);
      const card = el('div', 'quota-details');
      disclosure.append(card);
      card.append(el('p', 'dim', profile.harness_kind));
      const error = el('p', 'quota-error');
      error.setAttribute('role', 'alert');
      card.append(error);

      if (!quota) {
        card.append(el('p', 'dim', 'No reading yet.'));
        card.append(refreshRow('refresh-quota', { profile_id: profile.id }));
        return disclosure;
      }
      const windows = quota.windows || [];
      if (!windows.length) {
        card.append(el('p', 'dim', quota.summary || 'No windows reported.'));
      }
      for (const window of windows) {
        const row = el('div', 'quota-window');
        const label = el('div', 'quota-label');
        label.append(el('span', '', window.label));
        const used = window.percent_used;
        label.append(
          el(
            'span',
            band(used === undefined ? undefined : 100 - used),
            used === undefined ? 'unknown' : `${used}% used`,
          ),
        );
        row.append(label);
        if (used !== undefined) {
          // A bar and a number say the same thing, so a reader who cannot see
          // the bar has not lost anything.
          const meter = el('div', 'meter');
          meter.setAttribute('role', 'img');
          meter.setAttribute('aria-label', `${window.label}: ${used}% used`);
          const fill = el('div', `meter-fill ${band(100 - used)}`);
          fill.style.setProperty('--fill', `${used}%`);
          meter.append(fill);
          row.append(meter);
        }
        const notes = [];
        if (window.resets_at) notes.push(`resets ${window.resets_at}`);
        if (window.projects_exhaustion_before_reset) notes.push('on course to run out first');
        if (notes.length) row.append(el('p', 'dim', notes.join(' · ')));
        card.append(row);
      }
      if (quota.refreshed_at_epoch_seconds) {
        card.append(
          el(
            'p',
            'dim',
            `Last refreshed ${new Date(quota.refreshed_at_epoch_seconds * 1000).toLocaleTimeString()}`,
          ),
        );
      }
      card.append(refreshRow('refresh-quota', { profile_id: profile.id }));
      return disclosure;
    }),
  );
  if (focusedProfile && focusedControl) {
    [...quotaPanel.querySelectorAll('.quota-profile')]
      .find(row => row.dataset.profileId === focusedProfile)
      ?.querySelector(focusedControl)?.focus({ preventScroll: true });
  }
}

/// The refresh control both pages carry.
function refreshRow(actionName, payload) {
  const row = el('div', 'row');
  const control = button('Refresh', 'secondary', { refresh: actionName });
  control.dataset.payload = JSON.stringify(payload);
  row.append(control);
  return row;
}

async function runRefresh(target, errorNode) {
  const body = { action: target.dataset.refresh, ...JSON.parse(target.dataset.payload) };
  if (errorNode) errorNode.textContent = '';
  target.disabled = true;
  try {
    await request('/api/actions', { method: 'POST', body: JSON.stringify(body) });
    await refresh();
  } catch (err) {
    if (errorNode) errorNode.textContent = err.message;
  } finally {
    target.disabled = false;
  }
}

// ---------------------------------------------------------------------------
// Data
// ---------------------------------------------------------------------------

function startEvents() {
  if (eventSource) eventSource.close();
  eventSource = new EventSource('/api/events');
  eventSource.addEventListener('open', () => setConnection('online'));
  eventSource.addEventListener('revision', () => {
    setConnection('online');
    refresh().then(ok => {
      if (!ok || !currentSession) return;
      const session = snapshot?.sessions.find(item => item.id === currentSession);
      if (session?.capabilities?.open && !isTransitioningSession(session)) {
        loadConversation(true);
      }
    });
  });
  // The browser reconnects a stream on its own; saying so is what stops the
  // page looking current while it is not.
  eventSource.addEventListener('error', () => {
    if (navigator.onLine) setConnection('reconnecting');
    else setConnection('offline');
  });
}

function showLogin() {
  snapshot = undefined;
  currentSession = null;
  if (eventSource) {
    eventSource.close();
    eventSource = undefined;
  }
  // Nothing from the previous viewer may survive a sign-out in this tab.
  pendingActions.clear();
  pendingReviewSessions.clear();
  entryNodes.clear();
  elicitationCards.clear();
  sentElicitations.clear();
  promptImages = [];
  login.classList.remove('hidden');
  app.classList.add('hidden');
  menuButton.classList.add('hidden');
  backButton.classList.add('hidden');
  closeMenu();
}

async function refresh() {
  try {
    snapshot = await request('/api/snapshot');
    snapshotReceivedAtMs = Date.now();
    seedDashboardOrders(snapshot);
    login.classList.add('hidden');
    app.classList.remove('hidden');
    menuButton.classList.remove('hidden');
    if (currentSession) {
      const session = snapshot.sessions.find(x => x.id === currentSession);
      if (!session
        || (!session.capabilities?.open
          && !isTransitioningSession(session)
          && !isLoadingConversationSession(session))) {
        navigate({ name: 'dashboard', workspaceId: selectedWorkspaceId() });
        return true;
      }
      syncConversationMode(session);
      renderQueue(session);
      renderElicitations(session);
      renderTurnReview(session);
      renderAttachments();
      renderConversationHeader(session);
    }
    renderRoute();
    if (!eventSource) startEvents();
    return true;
  } catch (e) {
    if (e.message === 'unauthorized') showLogin();
    return false;
  }
}

/// Load the snapshot first, then honour the URL.
///
/// A protected route must stay a login page while the snapshot request is
/// unauthorized: rendering it first would dereference a snapshot that is not
/// there.
async function restoreRoute() {
  if (!(await refresh())) return;
  applyRoute();
}

function renderQueue(session) {
  const prompts = session.queued_prompts || [];
  queue.replaceChildren(
    ...prompts.map((prompt, index) => {
      const row = el('div', 'queue-item');
      row.append(el('span', '', `${index + 1}. ${prompt.text}`));
      const controls = el('div', 'row');
      // The newest queued prompt can be taken back into the composer, the
      // way the terminal's edit-latest does, because the last thing you
      // queued is the one you most often want to change.
      if (index === prompts.length - 1) {
        controls.append(button('Edit', 'secondary', { editQueueId: prompt.id }));
      }
      controls.append(button('Remove', 'danger', { queueId: prompt.id }));
      row.append(controls);
      return row;
    }),
  );
  queue.hidden = prompts.length === 0;
  if (queueHeading) queueHeading.hidden = prompts.length === 0;

  const running = session.active_user_shells || [];
  shells.replaceChildren(
    ...running.map(shell => {
      const row = el('div', 'queue-item');
      row.append(el('span', '', `$ ${shell.command}`));
      row.append(button('Cancel', 'danger', { shellId: shell.id }));
      return row;
    }),
  );
  shells.hidden = running.length === 0;
  if (shellsHeading) shellsHeading.hidden = running.length === 0;
  if (conversationSummary) {
    conversationSummary.textContent =
      prompts.length && running.length
        ? 'Queue and shells'
        : prompts.length
          ? 'Queued prompts'
          : 'Shell commands';
  }
  conversationSide.hidden = prompts.length === 0 && running.length === 0;
}
// Every snapshot revision re-renders the conversation. Rebuilding a card the
// user is answering would wipe the half-filled form and steal focus, so each
// pending request keeps its live DOM until the request itself changes or
// leaves the snapshot.
/// The review last drawn, so the card is rebuilt only when it changes.
let reviewSignature = null;
const pendingReviewSessions = new Set();
const elicitationCards = new Map(),
  sentElicitations = new Set();
function elicitationKey(sessionId, id) {
  return `${sessionId}\u001f${id}`;
}

let choiceControlSequence = 0;

/// A native radio/checkbox group whose complete rows are touch targets.
///
/// The inputs remain ordinary browser controls, so arrow keys, Tab, and
/// assistive technology keep their platform semantics. The surrounding label
/// makes the title and description part of the same target as the control.
function choiceControl({
  label,
  options,
  multiple = false,
  values = [],
  required = false,
  onChange = () => {},
}) {
  const fieldset = el('fieldset', 'choice-control');
  fieldset.append(el('legend', '', label));
  const selected = new Set(
    (Array.isArray(values) ? values : [values])
      .filter(value => value != null)
      .map(value => String(value)),
  );
  // A name is needed for native radio keyboard behaviour. It must not be
  // shared by two independently-rendered groups on the same page.
  const name = `choice-${++choiceControlSequence}`;
  for (const option of options || []) {
    const row = el('label', 'choice-option');
    const input = el('input');
    input.type = multiple ? 'checkbox' : 'radio';
    input.name = name;
    input.value = String(option.value ?? '');
    input.checked = selected.has(input.value);
    // `required` on every checkbox would require every option. Multi-select
    // required/min/max rules are applied by the form's validator instead.
    input.required = Boolean(required && !multiple);

    const text = el('span', 'choice-option-text');
    text.append(el('span', 'choice-option-title', String(option.title ?? option.value ?? '')));
    if (option.description) {
      text.append(el('span', 'choice-option-description dim', String(option.description)));
    }
    row.append(input, text);
    fieldset.append(row);
    input.addEventListener('change', event => onChange(event));
  }
  return fieldset;
}

function elicitationOptionLabel(option) {
  return option.title ?? String(option.value ?? '');
}
function elicitationControl(field) {
  const input = document.createElement('input');
  input.type =
    field.kind === 'boolean'
      ? 'checkbox'
      : field.kind === 'integer' || field.kind === 'number'
        ? 'number'
        : field.secret
          ? 'password'
          : 'text';
  if (field.kind === 'integer') input.step = '1';
  if (field.kind === 'number') input.step = 'any';
  if (field.minimum != null) input.min = field.minimum;
  if (field.maximum != null) input.max = field.maximum;
  if (field.min_length != null) input.minLength = field.min_length;
  if (field.max_length != null) input.maxLength = field.max_length;
  if (field.pattern) input.pattern = field.pattern;
  if (field.kind === 'boolean') input.checked = field.default === true;
  else if (field.default != null) input.value = String(field.default);
  return input;
}
function elicitationFieldValue(field, control) {
  if (field.kind === 'multi_select') {
    const values = [...control.querySelectorAll('input:checked')].map(input => input.value);
    return values.length || field.required ? values : undefined;
  }
  if (field.kind === 'single_select') {
    const value = control.querySelector('input:checked')?.value || '';
    return value === '' && !field.required ? undefined : value;
  }
  if (field.kind === 'boolean') return control.checked;
  if (control.value === '')
    return field.required && (field.kind === 'text' || field.kind === 'single_select')
      ? ''
      : undefined;
  if (field.kind === 'integer') return Number.parseInt(control.value, 10);
  if (field.kind === 'number') return Number(control.value);
  return control.value;
}
// Builds the controls and returns collect(), which reads them back as ACP
// content. A custom answer replaces the choice group it belongs to unless the
// request pairs it with one specific option, which is how Mjolnir's chat form
// submits the same request.
function buildElicitationForm(form, request, register) {
  const entries = [],
    customByOwner = new Map();
  for (const field of request.fields || []) {
    const isChoice = field.kind === 'single_select' || field.kind === 'multi_select';
    // A fieldset contains its own option labels. Keeping its outer wrapper a
    // div avoids invalid nested labels and preserves one target per option.
    const wrapper = document.createElement(isChoice ? 'div' : 'label');
    wrapper.className = 'elicitation-field';
    let control,
      validateChoices = () => {};
    if (isChoice) {
      control = choiceControl({
        label: `${field.title}${field.required ? ' *' : ''}`,
        options: (field.kind === 'single_select' && !field.required
          ? [{ value: '', title: 'No answer' }, ...(field.options || [])]
          : field.options || []).map(option => ({
          value: option.value,
          title: elicitationOptionLabel(option),
          description: option.description,
        })),
        multiple: field.kind === 'multi_select',
        values:
          field.kind === 'multi_select'
            ? field.default || []
            : field.default == null
              ? field.required
                ? [field.options?.[0]?.value]
                : []
              : [field.default],
        required: Boolean(field.required),
        onChange: () => validateChoices(),
      });
      const validateTarget = control.querySelector('input');
      validateChoices = () => {
        if (field.kind !== 'multi_select' || !validateTarget) return;
        const custom = customByOwner.get(field.id);
        // An unpaired free-text answer replaces this choice field. Its value
        // must be able to satisfy a required group without a phantom native
        // selection, while a cleared value puts the constraints back.
        if (custom && custom.control.value.trim() !== '' && custom.field.custom_answer_option == null) {
          validateTarget.setCustomValidity('');
          return;
        }
        const count = control.querySelectorAll('input:checked').length;
        const minimum = field.required ? Math.max(1, field.min_items ?? 1) : field.min_items;
        const few = minimum != null && (field.required || count > 0) && count < minimum;
        const many = field.max_items != null && count > field.max_items;
        validateTarget.setCustomValidity(
          few
            ? `Select at least ${minimum} option(s).`
            : many
              ? `Select at most ${field.max_items} option(s).`
              : '',
        );
      };
      for (const input of control.querySelectorAll('input')) register(input);
      register(control);
      validateChoices();
      wrapper.append(control);
    } else {
      const label = document.createElement('span');
      label.textContent = `${field.title}${field.required ? ' *' : ''}`;
      control = elicitationControl(field);
      control.required = Boolean(field.required) && field.kind !== 'boolean';
      register(control);
      wrapper.append(label, control);
    }
    if (field.description) {
      const description = document.createElement('span');
      description.className = 'dim';
      description.textContent = field.description;
      wrapper.append(description);
    }
    form.append(wrapper);
    entries.push({ field, control, validateChoices });
  }
  for (const entry of entries) {
    const owner = entry.field.custom_answer_for;
    if (!owner || entry.field.kind !== 'text' || customByOwner.has(owner)) continue;
    const target = entries.find(candidate => candidate.field.id === owner);
    if (!target || !Array.isArray(target.field.options)) continue;
    customByOwner.set(owner, entry);
  }
  // Custom text changes can make the owner group valid or invalid before the
  // user submits it. Keep browser validity and the visible choices in sync.
  for (const entry of entries) {
    if (entry.field.kind === 'multi_select') entry.validateChoices();
    const owner = entry.field.custom_answer_for;
    if (!owner || entry.field.kind !== 'text') continue;
    const target = entries.find(candidate => candidate.field.id === owner);
    if (target?.field.kind === 'multi_select') {
      entry.control.addEventListener('input', target.validateChoices);
      entry.control.addEventListener('change', target.validateChoices);
    }
  }
  return () => {
    for (const entry of entries)
      if (entry.field.kind === 'text') entry.control.value = entry.control.value.trim();
    for (const entry of entries)
      if (entry.field.kind === 'multi_select') entry.validateChoices();
    const active = new Map();
    for (const [owner, entry] of customByOwner)
      if (entry.control.value !== '') active.set(owner, entry);
    if (!form.reportValidity()) return null;
    const content = {};
    for (const entry of entries) {
      const { field, control } = entry;
      if (customByOwner.get(field.custom_answer_for) === entry) {
        if (active.has(field.custom_answer_for)) content[field.id] = control.value;
        continue;
      }
      const custom = active.get(field.id);
      if (custom && custom.field.custom_answer_option == null) continue;
      const value = elicitationFieldValue(field, control);
      if (value !== undefined) content[field.id] = value;
    }
    return content;
  };
}
function buildElicitationCard(session, request) {
  const card = document.createElement('section');
  card.className = 'card elicitation';
  const heading = document.createElement('strong');
  heading.textContent = request.title || 'Input needed';
  const message = document.createElement('pre');
  message.className = 'elicitation-message';
  message.textContent = request.message;
  const form = document.createElement('form');
  const status = document.createElement('p');
  status.className = 'dim';
  const gated = [],
    register = control => {
      gated.push(control);
      return control;
    };
  const collect = buildElicitationForm(form, request, register);
  const actions = document.createElement('div');
  actions.className = 'row';
  const send = document.createElement('button');
  send.type = 'submit';
  send.textContent = 'Send answer';
  register(send);
  const decline = document.createElement('button');
  decline.type = 'button';
  decline.className = 'secondary';
  decline.textContent = 'Decline';
  register(decline);
  const cancel = document.createElement('button');
  cancel.type = 'button';
  cancel.className = 'danger';
  cancel.textContent = 'Cancel';
  register(cancel);
  decline.addEventListener('click', () => {
    submitElicitation(session.id, request.id, { action: 'decline' });
  });
  cancel.addEventListener('click', () => {
    submitElicitation(session.id, request.id, { action: 'cancel' });
  });
  actions.append(send, decline, cancel);
  form.append(actions);
  form.addEventListener('submit', event => {
    event.preventDefault();
    const content = collect();
    if (content) submitElicitation(session.id, request.id, { action: 'accept', content });
  });
  const nodes = [heading];
  if (request.description) {
    const description = document.createElement('p');
    description.className = 'dim';
    description.textContent = request.description;
    nodes.push(description);
  }
  nodes.push(message, form, status);
  card.append(...nodes);
  return {
    card,
    setSent(sent) {
      for (const control of gated) control.disabled = sent;
      status.textContent = sent ? 'Answer sent \u2014 waiting for the session to apply it.' : '';
    },
  };
}
// ---------------------------------------------------------------------------
// Turn review
// ---------------------------------------------------------------------------
//
// The review runs in the daemon; this renders what it published and sends the
// resolution back. Both surfaces show the same review, and either can end it,
// which is what keeps a review from ever locking a phone out of its session.

/// Draws the review card, or takes it down when no review is open.
///
/// Rebuilt only when the published review actually changed, so a thumb resting
/// on a button does not lose it every two seconds.
function renderTurnReview(session) {
  const review = session?.turn_review || null;
  // The session belongs in the identity too. Two sessions can publish an
  // identical review, but their controls must still close over different ids.
  const signature = JSON.stringify([session?.id || null, review]);
  if (reviewSignature === signature) return;
  reviewSignature = signature;
  if (!review) {
    reviewHost.replaceChildren();
    return;
  }
  const card = el('section', 'card turn-review');
  card.append(el('strong', '', `Reviewing this turn (${review.tier})`));
  if (review.roles.length) {
    const strip = el('p', 'dim turn-review-roles');
    strip.textContent = review.roles
      .map(role => `${role.label}: ${role.state}`)
      .join('  ·  ');
    card.append(strip);
  }
  const verdict = review.verdict || null;
  if (verdict && verdict.text) {
    const findings = el('pre', 'turn-review-findings');
    findings.textContent = verdict.text;
    card.append(findings);
  }
  card.append(el('p', 'dim', review.status));
  const actions = el('div', 'row');
  for (const [resolution, label, className] of [
    ['forward', 'Forward findings', ''],
    ['dismiss', 'Dismiss', 'secondary'],
    ['cancel', 'Cancel', 'danger'],
  ]) {
    const button = document.createElement('button');
    button.type = 'button';
    button.textContent = label;
    if (className) button.className = className;
    // Cancel always works; the rest wait for the verdict the daemon
    // published, and the daemon refuses anything else anyway.
    button.disabled =
      pendingReviewSessions.has(session.id) ||
      (resolution !== 'cancel' && !(verdict?.allowed || []).includes(resolution));
    button.addEventListener('click', async () => {
      if (pendingReviewSessions.has(session.id)) return;
      pendingReviewSessions.add(session.id);
      // One resolution owns the whole card while it is in flight. Otherwise a
      // second tap can race a different answer into the same review.
      for (const control of actions.children) control.disabled = true;
      try {
        await sendAction({
          action: 'resolve-review',
          session_id: session.id,
          resolution,
        });
      } finally {
        pendingReviewSessions.delete(session.id);
        // A failed request leaves the review open. Rebuild the still-current
        // card from its published gates so every valid action becomes usable
        // again; never revive controls from a conversation already left behind.
        if (currentSession === session.id) {
          reviewSignature = null;
          renderTurnReview(activeSession());
        }
      }
    });
    actions.append(button);
  }
  card.append(actions);
  reviewHost.replaceChildren(card);
}

function renderElicitations(session) {
  const pending = (session && session.pending_elicitations) || [];
  if (session)
    for (const key of [...sentElicitations])
      if (
        key.startsWith(`${session.id}\u001f`) &&
        !pending.some(request => elicitationKey(session.id, request.id) === key)
      )
        sentElicitations.delete(key);
  const live = new Set(),
    cards = [];
  for (const request of pending) {
    const key = elicitationKey(session.id, request.id),
      signature = JSON.stringify(request);
    live.add(key);
    let entry = elicitationCards.get(key);
    if (!entry || entry.signature !== signature) {
      entry = buildElicitationCard(session, request);
      entry.signature = signature;
      elicitationCards.set(key, entry);
    }
    entry.setSent(sentElicitations.has(key));
    cards.push(entry.card);
  }
  for (const key of [...elicitationCards.keys()]) if (!live.has(key)) elicitationCards.delete(key);
  const mounted = [...elicitations.children];
  if (mounted.length !== cards.length || cards.some((card, index) => mounted[index] !== card))
    elicitations.replaceChildren(...cards);
}
async function submitElicitation(sessionId, elicitationId, response) {
  const key = elicitationKey(sessionId, elicitationId);
  if (sentElicitations.has(key)) return;
  sentElicitations.add(key);
  const rerender = () => {
    const session = snapshot?.sessions.find(x => x.id === sessionId);
    if (session && sessionId === currentSession) renderElicitations(session);
  };
  rerender();
  try {
    await request('/api/actions', {
      method: 'POST',
      body: JSON.stringify({
        action: 'respond-elicitation',
        session_id: sessionId,
        elicitation_id: elicitationId,
        response,
      }),
    });
    document.querySelector('#conversation-error').textContent = '';
    await refresh();
  } catch (err) {
    sentElicitations.delete(key);
    document.querySelector('#conversation-error').textContent = err.message;
    rerender();
  }
}
// The composer is a contenteditable rather than a textarea so a pasted or
// dropped image can be intercepted where it lands, and so the box grows with
// its content without a layout read on every keystroke. Rich content is
// refused at beforeinput, which keeps the box plain text however it arrives.
const MAX_PROMPT_REQUEST_BYTES = 32 * 1024 * 1024;
let composerRevision = 0,
  composerPreserveEmptyBreak = false,
  promptImages = [];
function composerText() {
  let text = '';
  const blocks = new Set(['DIV', 'P']);
  const append = node => {
    if (node.nodeType === Node.TEXT_NODE) {
      text += node.nodeValue || '';
      return;
    }
    if (node.nodeName === 'BR') {
      if (!node.dataset.composerFiller) text += '\n';
      return;
    }
    const block = node !== promptText && blocks.has(node.nodeName);
    if (block && text && !text.endsWith('\n')) text += '\n';
    node.childNodes.forEach(append);
    if (block && node.nextSibling && !text.endsWith('\n')) text += '\n';
  };
  append(promptText);
  return text.replace(/\r\n?/g, '\n');
}
function setComposerText(text) {
  promptText.textContent = text;
}
function placeComposerCaretAtEnd() {
  const selection = window.getSelection();
  if (!selection) return;
  const range = document.createRange();
  range.selectNodeContents(promptText);
  range.collapse(false);
  selection.removeAllRanges();
  selection.addRange(range);
}
function placeComposerCaretAtPoint(x, y) {
  let range = document.caretRangeFromPoint?.(x, y) || null;
  if (!range && document.caretPositionFromPoint) {
    const position = document.caretPositionFromPoint(x, y);
    if (position) {
      range = document.createRange();
      range.setStart(position.offsetNode, position.offset);
      range.collapse(true);
    }
  }
  if (!range || !promptText.contains(range.startContainer)) return;
  const selection = window.getSelection();
  if (!selection) return;
  selection.removeAllRanges();
  selection.addRange(range);
}
function insertComposerFallback(node, filler = null) {
  const selection = window.getSelection();
  const range = selection && selection.rangeCount ? selection.getRangeAt(0) : null;
  if (!range || !promptText.contains(range.commonAncestorContainer)) {
    promptText.append(node);
    if (filler) promptText.append(filler);
    placeComposerCaretAtEnd();
    return;
  }
  range.deleteContents();
  range.insertNode(node);
  if (filler) node.after(filler);
  range.setStartAfter(node);
  range.collapse(true);
  selection.removeAllRanges();
  selection.addRange(range);
}
// execCommand keeps the browser's own undo stack, so it is tried first; the
// fallback covers engines that refuse it, and the revision check covers those
// that run it without emitting the input event that keeps state in step.
function runComposerEdit(command, value, fallback) {
  promptText.focus();
  const revision = composerRevision;
  if (document.execCommand(command, false, value)) {
    if (composerRevision === revision) composerInputChanged();
    return;
  }
  fallback();
  composerInputChanged();
}
function insertComposerText(text) {
  const normalized = text.replace(/\r\n?/g, '\n');
  runComposerEdit('insertText', normalized, () => {
    insertComposerFallback(document.createTextNode(normalized));
  });
}
function insertComposerLineBreak() {
  composerPreserveEmptyBreak = true;
  try {
    runComposerEdit('insertLineBreak', null, () => {
      const filler = document.createElement('br');
      filler.dataset.composerFiller = 'true';
      insertComposerFallback(document.createElement('br'), filler);
    });
    let last = promptText;
    while (last.lastChild) last = last.lastChild;
    if (last.nodeName === 'BR' && last.previousSibling?.nodeName === 'BR') {
      last.dataset.composerFiller = 'true';
    }
  } finally {
    composerPreserveEmptyBreak = false;
  }
}
// A cleared box can keep a stray break behind it, which leaves the placeholder
// hidden and the box looking occupied when it holds nothing.
function composerInputChanged() {
  composerRevision += 1;
  if (!composerPreserveEmptyBreak && !promptText.textContent && promptText.childNodes.length)
    promptText.replaceChildren();
}
function readFileAsDataUrl(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => resolve(String(reader.result || '')), { once: true });
    reader.addEventListener('error', () => reject(reader.error || new Error('file read failed')), {
      once: true,
    });
    reader.readAsDataURL(file);
  });
}
function imageDimensions(file) {
  return new Promise((resolve, reject) => {
    const url = URL.createObjectURL(file);
    const image = new Image();
    image.addEventListener(
      'load',
      () => {
        const size = { width: image.naturalWidth, height: image.naturalHeight };
        URL.revokeObjectURL(url);
        resolve(size);
      },
      { once: true },
    );
    image.addEventListener(
      'error',
      () => {
        URL.revokeObjectURL(url);
        reject(new Error('the browser could not decode this image'));
      },
      { once: true },
    );
    image.src = url;
  });
}
async function promptImageFromFile(file) {
  if (!file.type.startsWith('image/'))
    throw new Error(`${file.name || 'That file'} is not an image`);
  if (file.size >= MAX_PROMPT_REQUEST_BYTES)
    throw new Error(`${file.name || 'That image'} is too large for the 32 MiB request limit`);
  const [dataUrl, size] = await Promise.all([readFileAsDataUrl(file), imageDimensions(file)]);
  const comma = dataUrl.indexOf(',');
  if (comma < 0 || !dataUrl.slice(comma + 1))
    throw new Error(`Could not read ${file.name || 'that image'}`);
  return {
    data_base64: dataUrl.slice(comma + 1),
    mime_type: file.type,
    width: size.width,
    height: size.height,
    name: file.name || 'Pasted image',
  };
}
async function attachImageFiles(files) {
  const session = snapshot?.sessions.find(x => x.id === currentSession);
  if (!currentSession || !session?.prompt_images_supported || !files.length) return;
  const sessionId = currentSession;
  try {
    const added = [];
    for (const file of files) added.push(await promptImageFromFile(file));
    if (currentSession !== sessionId) return;
    promptImages = promptImages.concat(added);
    renderAttachments();
    document.querySelector('#conversation-error').textContent = '';
  } catch (err) {
    document.querySelector('#conversation-error').textContent = err.message;
  }
}
function renderAttachments() {
  // The draft the daemon keeps is text. An attachment lives in this browser
  // only, and a photograph that quietly disappears on reload is worse than one
  // somebody was told about.
  const session = snapshot?.sessions.find(x => x.id === currentSession);
  attachImage.hidden = !session?.prompt_images_supported;
  attachments.replaceChildren();
  if (promptImages.length) {
    attachments.append(
      el('p', 'dim', 'Images stay on this device until sent; a draft keeps only the text.'),
    );
  }
  for (const [index, image] of promptImages.entries()) {
    const chip = document.createElement('div');
    chip.className = 'attachment';
    const thumb = document.createElement('img');
    thumb.alt = '';
    thumb.src = `data:${image.mime_type};base64,${image.data_base64}`;
    const caption = document.createElement('span');
    caption.textContent = `${image.name} \u00b7 ${image.width}\u00d7${image.height}`;
    const remove = document.createElement('button');
    remove.type = 'button';
    remove.className = 'danger';
    remove.setAttribute('aria-label', `Remove ${image.name}`);
    remove.textContent = '\u00d7';
    remove.onclick = () => {
      promptImages.splice(index, 1);
      renderAttachments();
    };
    chip.append(thumb, caption, remove);
    attachments.append(chip);
  }
}
// ---------------------------------------------------------------------------
// Drafts and history
// ---------------------------------------------------------------------------
//
// A draft is stored by the daemon against this viewer and this session, so it
// survives a reload, a closed tab and a new phone. Unsent image attachments are
// not: they live in this browser's memory only, and the composer says so, since
// a photograph that quietly disappears is worse than one you were told about.

const DRAFT_DEBOUNCE_MS = 400;
let draftTimer = null;
let draftSaving = false;

function scheduleDraftSave() {
  if (draftTimer) clearTimeout(draftTimer);
  draftTimer = setTimeout(saveDraft, DRAFT_DEBOUNCE_MS);
}

async function saveDraft() {
  draftTimer = null;
  if (!currentSession || draftSaving) return;
  const sessionId = currentSession;
  const draft = composerText();
  draftSaving = true;
  try {
    await request(`/api/sessions/${encodeURIComponent(sessionId)}/draft`, {
      method: 'PUT',
      body: JSON.stringify({ draft }),
    });
  } catch {
    // A draft that could not be stored is still in the composer, which is the
    // copy that matters. Saying so on every keystroke would be noise.
  } finally {
    draftSaving = false;
  }
}

/// Put back what this viewer last typed here and did not send.
async function restoreDraft(sessionId, generation) {
  try {
    const stored = await request(`/api/sessions/${encodeURIComponent(sessionId)}/client-state`);
    if (generation !== conversationGeneration) return;
    // Anything typed while the request was in flight belongs to the person,
    // not to the server.
    if (stored.draft && !composerText()) {
      setComposerText(stored.draft);
      updateCommandPalette();
    }
    if (stored.through_event_ordinal > acknowledged) {
      acknowledged = stored.through_event_ordinal;
    }
  } catch {
    // An unavailable draft is not worth a message: the composer is empty and
    // the person can type.
  }
}

let historyOpen = false;

/// Search this project's earlier prompts and offer them in the palette.
async function searchHistory(query) {
  if (!currentSession) return;
  const generation = conversationGeneration;
  try {
    const found = await request(
      `/api/sessions/${encodeURIComponent(currentSession)}/history?q=${encodeURIComponent(query)}&scope=project`,
    );
    if (generation !== conversationGeneration || !historyOpen) return;
    paletteMatches = found.entries.map(text => ({
      insert: text,
      label: text.length > 80 ? `${text.slice(0, 79)}` : text,
      hint: '',
    }));
    if (found.truncated) {
      // Saying the answer is partial is the whole reason the bound reports it.
      paletteMatches.push({
        insert: composerText(),
        label: `More matches than ${paletteMatches.length}  narrow the search`,
        hint: '',
      });
    }
    paletteSelected = 0;
    if (!paletteMatches.length) {
      commandPalette.replaceChildren(el('p', 'dim palette-row', 'No earlier prompts match.'));
      commandPalette.classList.remove('hidden');
      return;
    }
    commandPalette.replaceChildren(
      ...paletteMatches.map((match, index) => {
        const row = el('button', 'palette-row');
        row.type = 'button';
        row.setAttribute('role', 'option');
        row.setAttribute('aria-selected', String(index === paletteSelected));
        row.dataset.insert = match.insert;
        row.append(el('span', 'palette-name', match.label));
        return row;
      }),
    );
    commandPalette.classList.remove('hidden');
  } catch (err) {
    document.querySelector('#conversation-error').textContent = err.message;
  }
}

// ---------------------------------------------------------------------------
// Slash commands
// ---------------------------------------------------------------------------
//
// The rules behind these live in Rust and are published in the session
// projection. Whether fast mode exists, whether plan mode can be driven, and
// which values `model` and `effort` accept are facts about the harness, so the
// browser reads the published answer rather than deciding again. Where a check
// here and a check there ever disagree, the Rust one is right and this one is
// the bug.

function activeSession() {
  return snapshot?.sessions.find(session => session.id === currentSession);
}

function configOption(key) {
  return activeSession()?.config_options?.find(option => option.key === key);
}

/// The commands offered for what has been typed so far.
///
/// The list is the daemon's: it knows what this session's harness advertised
/// and what Mjolnir itself offers, and publishing it is what keeps the phone from
/// missing a command the terminal has.
function availableCommands() {
  return activeSession()?.available_commands || [];
}

let paletteMatches = [];
let paletteSelected = 0;

/// What the palette should offer, given the composer's text.
///
/// After a complete `/model ` the palette offers values rather than commands,
/// and a fully typed advertised value closes it so Enter submits instead of
/// accepting the text again.
function paletteState(text) {
  for (const key of ['model', 'effort']) {
    const prefix = `/${key} `;
    if (!text.startsWith(prefix)) continue;
    const option = configOption(key);
    if (!option) return null;
    const query = text.slice(prefix.length);
    if (option.choices.some(choice => choice.value === query)) return null;
    const matches = option.choices
      .filter(
        choice =>
          choice.value.toLowerCase().startsWith(query.toLowerCase()) ||
          choice.name.toLowerCase().includes(query.toLowerCase()),
      )
      .map(choice => ({
        insert: `/${key} ${choice.value}`,
        label: choice.value,
        hint: choice.name,
      }));
    return matches.length ? matches : null;
  }
  if (!text.startsWith('/') || /\s/.test(text)) return null;
  const query = text.slice(1).toLowerCase();
  const matches = availableCommands()
    .filter(
      command =>
        command.name.startsWith(query) || command.description.toLowerCase().includes(query),
    )
    .map(command => ({
      insert: `/${command.name} `,
      label: `/${command.name}${command.argument ? ` <${command.argument}>` : ''}`,
      hint: command.description,
    }));
  return matches.length ? matches : null;
}

function updateCommandPalette() {
  const matches = paletteState(composerText());
  if (!matches) {
    paletteMatches = [];
    commandPalette.classList.add('hidden');
    commandPalette.replaceChildren();
    return;
  }
  // Keep the highlighted entry by name across a re-render, so typing another
  // character does not silently move the selection under the reader.
  const previous = paletteMatches[paletteSelected]?.insert;
  paletteMatches = matches;
  paletteSelected = Math.max(
    0,
    matches.findIndex(match => match.insert === previous),
  );
  commandPalette.replaceChildren(
    ...matches.map((match, index) => {
      const row = el('button', 'palette-row');
      row.type = 'button';
      row.setAttribute('role', 'option');
      row.setAttribute('aria-selected', String(index === paletteSelected));
      row.dataset.insert = match.insert;
      row.append(el('span', 'palette-name', match.label), el('span', 'dim', match.hint));
      return row;
    }),
  );
  commandPalette.classList.remove('hidden');
}

function moveCommandSelection(delta) {
  if (!paletteMatches.length) return false;
  paletteSelected = (paletteSelected + delta + paletteMatches.length) % paletteMatches.length;
  updateCommandPaletteSelection();
  return true;
}

function updateCommandPaletteSelection() {
  [...commandPalette.children].forEach((row, index) => {
    row.setAttribute('aria-selected', String(index === paletteSelected));
  });
}

function acceptCommandSelection() {
  const match = paletteMatches[paletteSelected];
  if (!match) return false;
  setComposerText(match.insert);
  placeComposerCaretAtEnd();
  historyOpen = false;
  updateCommandPalette();
  scheduleDraftSave();
  return true;
}

/// Everything Mjolnir and the agent offer, as a system note in the transcript.
function showHelp() {
  const lines = ['Available commands:', '!<command> — run a shell command in this session [mj]'];
  for (const command of availableCommands()) {
    const argument = command.argument ? ` <${command.argument}>` : '';
    lines.push(
      `/${command.name}${argument}  ${command.description} [${command.source || 'mj'}]`,
    );
  }
  const note = el('article', 'entry tone-system');
  const heading = el('strong');
  const glyph = el('span', 'entry-glyph', '');
  glyph.setAttribute('aria-hidden', 'true');
  heading.append(glyph, el('span', 'entry-label', 'Mjolnir'));
  note.append(heading, el('pre', 'entry-body', lines.join('\n')));
  feed.append(note);
  scrollToTail();
}

/// The shared `/review status` sentence, from the bounded config projection.
///
/// Keep this byte-for-byte aligned with `hel_chat::review_status_line`: the
/// same configuration should answer the same way on the terminal and phone.
function reviewStatusLine(review, open) {
  const enabled = review?.enabled === true;
  const profile = review?.profile;
  const tier = review?.tier || 'quick';
  let armed;
  if (enabled && profile) {
    armed = `Reviewing every completed turn with [review] profile ${JSON.stringify(profile)} (${tier} tier)`;
  } else if (enabled) {
    armed = '[review] enabled = true but no profile is named, so nothing can review';
  } else if (profile) {
    armed = `Automatic review is off; /review reviews one turn with ${JSON.stringify(profile)} (${tier} tier)`;
  } else {
    armed = 'Turn review needs a reviewer: set [review] profile in config.toml';
  }
  return open ? `${armed}. A review is open now.` : armed;
}

/// Run a local command, or report that nothing here can.
///
/// Returns true when the text was a command this surface handled, so the
/// caller knows not to send it to the agent as a prompt.
async function runLocalCommand(text) {
  const match = /^\/([a-zA-Z][\w-]*)\s*(.*)$/.exec(text);
  if (!match) return false;
  const [, name, argument] = match;
  const error = document.querySelector('#conversation-error');
  const session = activeSession();

  switch (name) {
    case 'help':
      setComposerText('');
      showHelp();
      return true;
    case 'detach':
      setComposerText('');
      navigate({ name: 'dashboard', workspaceId: selectedWorkspaceId() });
      return true;
    case 'model':
    case 'effort': {
      if (!argument) {
        error.textContent = `usage: /${name} <value>`;
        return true;
      }
      await sendAction({
        action: 'set-config',
        session_id: currentSession,
        key: name,
        value: argument,
      });
      return true;
    }
    case 'fast': {
      const option = configOption('model');
      const current = option?.current || '';
      if (!option) {
        error.textContent = 'Fast mode is unavailable for this agent.';
        return true;
      }
      // Fast mode is a model, so the toggle is between the current model and
      // its fast counterpart, both of which the harness advertised.
      const fast = option.choices.find(choice => /fast/i.test(choice.value));
      if (!fast) {
        error.textContent = 'Fast mode is unavailable for the active model.';
        return true;
      }
      const target = /fast/i.test(current)
        ? option.choices.find(choice => !/fast/i.test(choice.value))?.value
        : fast.value;
      if (!target) {
        error.textContent = 'Fast mode is unavailable for the active model.';
        return true;
      }
      await sendAction({
        action: 'set-config',
        session_id: currentSession,
        key: 'model',
        value: target,
      });
      return true;
    }
    case 'review': {
      const scope = argument.trim().toLowerCase();
      if (scope === 'status') {
        error.textContent = reviewStatusLine(
          snapshot?.review_config,
          Boolean(session?.turn_review),
        );
        setComposerText('');
        return true;
      }
      if (scope) {
        // Arming review is configuration, not a session gesture.
        error.textContent =
          'automatic review is configured in config.toml: [review] enabled, tier';
        setComposerText('');
        return true;
      }
      await sendAction({ action: 'start-review', session_id: currentSession });
      return true;
    }
    case 'plan':
    case 'implement': {
      if (!session?.capabilities?.set_plan_mode) {
        error.textContent = 'Plan mode is only available while the agent is idle.';
        return true;
      }
      const active = name === 'plan' ? !session.plan_mode_active : false;
      await sendAction({ action: 'set-plan-mode', session_id: currentSession, active });
      // A trailing instruction is a prompt to send once the mode has changed.
      if (argument) {
        await sendAction({
          action: 'prompt',
          session_id: currentSession,
          text: argument,
          images: [],
        });
      }
      return true;
    }
    default:
      // Anything else is the agent's own command, and the agent is the one
      // that knows what to do with it.
      return false;
  }
}

/// Post one action and report its failure where the composer can be seen.
async function sendAction(body) {
  const error = document.querySelector('#conversation-error');
  const sessionId = body.session_id;
  try {
    await request('/api/actions', { method: 'POST', body: JSON.stringify(body) });
    // Do not let an action that completed after navigation clear the next
    // conversation's draft or error state.
    if (!sessionId || currentSession === sessionId) {
      setComposerText('');
      error.textContent = '';
    }
    await refresh();
    return true;
  } catch (err) {
    if (!sessionId || currentSession === sessionId) error.textContent = err.message;
    return false;
  }
}

/// Guard against sending twice.
///
/// Enter calls submit directly, so it bypasses the disabled button entirely;
/// without this a fast double press sends the same prompt twice.
let promptInFlight = false;

async function submitPrompt() {
  if (!currentSession || promptInFlight) return;
  const value = composerText();
  const images = promptImages;
  if (!value.trim() && !images.length) return;
  const error = document.querySelector('#conversation-error');

  promptInFlight = true;
  sendButton.disabled = true;
  try {
    if (value.startsWith('/') && (await runLocalCommand(value.trim()))) return;

    if (value.startsWith('!') && images.length) {
      error.textContent = 'Shell commands cannot carry images.';
      return;
    }
    const body = value.startsWith('!')
      ? { action: 'run-shell', session_id: currentSession, command: value.slice(1) }
      : {
          action: 'prompt',
          session_id: currentSession,
          text: value,
          images: images.map(image => ({
            data_base64: image.data_base64,
            mime_type: image.mime_type,
            width: image.width,
            height: image.height,
          })),
        };
    const payload = JSON.stringify(body);
    if (new TextEncoder().encode(payload).byteLength > MAX_PROMPT_REQUEST_BYTES) {
      error.textContent = 'Prompt attachments exceed the 32 MiB request limit.';
      return;
    }
    await request('/api/actions', { method: 'POST', body: payload });
    // The composer is cleared only once the daemon has taken the prompt, so a
    // refusal leaves the text where it can be edited and sent again.
    setComposerText('');
    promptImages = [];
    renderAttachments();
    updateCommandPalette();
    // The stored copy goes with the one on screen, so reopening does not put
    // back a prompt that has already run.
    saveDraft();
    error.textContent = '';
    await refresh();
  } catch (err) {
    error.textContent = err.message;
  } finally {
    promptInFlight = false;
    sendButton.disabled = false;
  }
}

const PROSE_ROLES = new Set(['user', 'agent', 'thought']);

/// How close to the bottom still counts as reading the tail.
const TAIL_SLACK_PX = 48;

/// Whether the reader is at the tail, and so wants to be carried along.
function atTail() {
  const distance = feedScroll.scrollHeight - feedScroll.scrollTop - feedScroll.clientHeight;
  return distance <= TAIL_SLACK_PX;
}

function scrollToTail() {
  feedScroll.scrollTop = feedScroll.scrollHeight;
  jumpToLatest.classList.add('hidden');
}

function entryBody(entry) {
  const body = el('div', 'entry-body');
  if (PROSE_ROLES.has(entry.role)) {
    body.append(renderMarkdown(entry.lines.join('\n')));
  } else {
    body.append(renderToolOutput(entry.lines.join('\n')));
  }
  if (entry.diffstats?.length) {
    body.append(renderDiffStats(entry.diffstats));
  }
  return body;
}

/// The files a tool changed, from the projection's own numbers.
function renderDiffStats(diffstats) {
  const list = el('ul', 'diffstat');
  for (const stat of diffstats) {
    const item = el('li');
    item.append(el('span', 'diffstat-path', stat.path));
    item.append(el('span', 'diffstat-added', `+${stat.insertions}`));
    item.append(el('span', 'diffstat-removed', `${stat.deletions}`));
    list.append(item);
  }
  return list;
}

function entryTimestamp(entry) {
  if (!entry.recorded_at_ms) return null;
  const node = el('time', 'entry-time', new Date(entry.recorded_at_ms).toLocaleTimeString());
  node.setAttribute('datetime', new Date(entry.recorded_at_ms).toISOString());
  return node;
}

/// Rewrite one entry's row.
///
/// Thinking and tool detail are collapsed by default, and which folds the
/// reader had opened is recorded and restored, so an update does not snap shut
/// something they were part way through reading.
function paintEntry(node, entry) {
  const openFolds = new Set(
    [...node.querySelectorAll('details.block-fold[open] > summary')].map(
      summary => summary.textContent,
    ),
  );
  node.className = `entry tone-${entry.tone}`;
  const heading = el('strong');
  const glyph = el('span', 'entry-glyph', entry.glyph || '');
  glyph.setAttribute('aria-hidden', 'true');
  heading.append(glyph, el('span', 'entry-label', entry.label));
  const time = entryTimestamp(entry);
  if (time) heading.append(time);

  const body = entryBody(entry);
  // Thinking is background: it is there for someone who wants it, and closed
  // for everyone else.
  if (entry.role === 'thought') {
    const fold = el('details', 'block-fold');
    const summary = el('summary', '', entry.label);
    fold.append(summary, body);
    node.replaceChildren(heading, fold);
  } else {
    node.replaceChildren(heading, body);
  }
  for (const summary of node.querySelectorAll('details.block-fold > summary')) {
    if (openFolds.has(summary.textContent)) summary.parentElement.open = true;
  }
}

function renderEntries(entries, replace) {
  const wasAtTail = atTail();
  if (replace) {
    feed.replaceChildren();
    entryNodes.clear();
  }
  let appended = false;
  for (const entry of entries) {
    let node = entryNodes.get(entry.id);
    if (!node) {
      node = el('article');
      node.dataset.entryId = entry.id;
      entryNodes.set(entry.id, node);
      feed.append(node);
      appended = true;
    }
    // An entry that has not moved is left alone: rewriting it would collapse
    // its folds and drop any text the reader had selected.
    if (node.dataset.updatedSeq === String(entry.updated_seq)) continue;
    node.dataset.updatedSeq = entry.updated_seq;
    paintEntry(node, entry);
  }
  if (wasAtTail) scrollToTail();
  else if (appended) jumpToLatest.classList.remove('hidden');
}

/// A counter that retires an in-flight request when the conversation changes.
///
/// Switching sessions quickly is how one session's text arrives under
/// another's header: the older fetch resolves last and wins. Every request
/// carries the generation it was issued in and drops itself if that generation
/// has moved on.
let conversationGeneration = 0;
let conversationInFlight = false;
let conversationPending = false;

function clearConversationContents() {
  entryNodes.clear();
  feed.replaceChildren();
  jumpToLatest.classList.add('hidden');
  elicitations.replaceChildren();
  elicitationCards.clear();
  reviewHost.replaceChildren();
  reviewSignature = null;
}

/// A lifecycle snapshot retires every transcript request issued under the
/// previous mode. This is independent of navigation: a late response from a
/// still-valid session is just as stale once its operation owns the session.
function syncConversationMode(session) {
  const transition = isTransitioningSession(session);
  const loading = !transition && isLoadingConversationSession(session);
  const operationId = session?.operation?.id || session?.state || session?.lifecycle || '';
  const next = transition ? `transition:${operationId}` : loading ? 'loading' : 'conversation';
  if (next === conversationMode) return;
  conversationMode = next;
  conversationGeneration += 1;
  conversationPending = false;
  cursor = 0;
  acknowledged = 0;
  conversationTransitionError.textContent = '';
  clearConversationContents();
}

function renderConversationTransition(session) {
  const transition = isTransitioningSession(session);
  const loading = !transition && isLoadingConversationSession(session);
  const unavailable = transition || loading;
  conversationTransition.hidden = !unavailable;
  feedScroll.hidden = unavailable;
  jumpToLatest.hidden = unavailable;
  elicitations.hidden = unavailable;
  reviewHost.hidden = unavailable;
  if (unavailable) conversationSide.hidden = true;
  else conversationSide.hidden = (queue.children.length === 0 && shells.children.length === 0);
  document.querySelector('#prompt-form').hidden = unavailable;
  cancelTurnButton.classList.toggle('hidden', unavailable || !session?.capabilities?.cancel_turn);
  if (!unavailable) return;
  conversationTransitionTitle.textContent = loading ? 'Loading conversation' : session.title || session.id;
  conversationTransitionStage.textContent = loading ? 'Waiting for the conversation…' : sessionActivityLabel(session);
  const notice = loading
    ? ''
    : session.operation?.notice
      || (session.has_error ? 'The operation needs recovery. Use the available action to try again.' : '');
  conversationTransitionNotice.textContent = notice;
  conversationTransitionNotice.hidden = !notice;
  conversationTransitionCancel.dataset.id = session.id;
  conversationTransitionCancel.disabled = !session.capabilities?.cancel_operation
    || pendingActions.has(`cancel:${session.id}`);
  conversationTransitionCancel.classList.toggle(
    'hidden',
    !session.capabilities?.cancel_operation,
  );
}

async function loadConversation(delta = false) {
  if (!currentSession) return;
  const current = snapshot?.sessions.find(session => session.id === currentSession);
  if (!current?.capabilities?.open || isTransitioningSession(current)) {
    if (isTransitioningSession(current) || isLoadingConversationSession(current)) {
      renderConversationTransition(current);
    }
    return;
  }
  // Revisions arrive in bursts. One load runs at a time and remembers that
  // another was asked for, so a burst costs one extra fetch rather than one
  // fetch each.
  if (conversationInFlight) {
    conversationPending = true;
    return;
  }
  conversationInFlight = true;
  const generation = conversationGeneration;
  const sessionId = currentSession;
  try {
    const result = await request(
      `/api/conversations/${encodeURIComponent(sessionId)}${delta && cursor ? `?after_seq=${cursor}` : ''}`,
    );
    const latest = snapshot?.sessions.find(session => session.id === sessionId);
    if (
      generation !== conversationGeneration
      || !latest?.capabilities?.open
      || isTransitioningSession(latest)
    ) return;
    renderEntries(result.entries, !delta || result.reset);
    cursor = result.latest_seq;
    if (cursor > acknowledged) {
      const through = cursor;
      await request(`/api/conversations/${encodeURIComponent(sessionId)}/read`, {
        method: 'POST',
        body: JSON.stringify({ through }),
      });
      const latest = snapshot?.sessions.find(session => session.id === sessionId);
      if (
        generation !== conversationGeneration
        || !latest?.capabilities?.open
        || isTransitioningSession(latest)
      ) return;
      acknowledged = through;
    }
  } catch (err) {
    const latest = snapshot?.sessions.find(session => session.id === sessionId);
    if (
      generation !== conversationGeneration
      || !latest?.capabilities?.open
      || isTransitioningSession(latest)
    ) return;
    if (err.message === 'unauthorized') {
      showLogin();
      return;
    }
    document.querySelector('#conversation-error').textContent = err.message;
  } finally {
    conversationInFlight = false;
    if (conversationPending) {
      conversationPending = false;
      const latest = snapshot?.sessions.find(session => session.id === sessionId);
      if (
        currentSession === sessionId
        && latest?.capabilities?.open
        && !isTransitioningSession(latest)
      ) {
        loadConversation(generation === conversationGeneration);
      }
    }
  }
}

async function openConversation(id) {
  if (currentSession === id) return;
  const session = snapshot?.sessions.find(x => x.id === id);
  if (!session || (!session.capabilities?.open && !isTransitioningSession(session))) return;
  currentSession = id;
  conversationGeneration += 1;
  conversationMode = null;
  conversationPending = false;
  cursor = 0;
  acknowledged = 0;
  clearConversationContents();
  document.querySelector('#conversation-title').textContent = session.title;
  document.querySelector('#conversation-state').textContent = sessionLifecycleLabel(session);
  syncConversationMode(session);
  renderQueue(session);
  renderElicitations(session);
  renderTurnReview(session);
  renderConversationHeader(session);
  promptImages = [];
  renderAttachments();
  restoreDraft(id, conversationGeneration);
  if (!isTransitioningSession(session)) await loadConversation(false);
}

/// The header, the turn control and the composer, all from what the daemon
/// published about this session.
///
/// The placeholder says whether Send will send or queue, because a person
/// pressing it deserves to know which of those is about to happen.
function renderSessionTitle(node, session) {
  node.textContent = session.title;
  node.classList.toggle('idle-title', session.is_idle === true);
}

function renderConversationHeader(session) {
  syncConversationMode(session);
  renderSessionTitle(document.querySelector('#conversation-title'), session);
  const state = document.querySelector('#conversation-state');
  state.textContent = sessionLifecycleLabel(session);
  state.className = `pill state-${session.lifecycle}`;
  renderConversationTransition(session);
  cancelTurnButton.classList.toggle(
    'hidden',
    isTransitioningSession(session)
      || isLoadingConversationSession(session)
      || !session.capabilities?.cancel_turn,
  );

  const running = session.chat_phase === 'running';
  const queued = (session.queued_prompts || []).length;
  promptText.dataset.placeholder = running
    ? 'The agent is working; this will queue'
    : 'Message the agent or use !command';
  sendButton.textContent = running || queued ? 'Queue' : 'Send';
  // A review holds the turn it reviewed: the daemon refuses prompts for this
  // session until it resolves, so the composer says so rather than letting a
  // person type into a refusal.
  const reviewing = Boolean(session.turn_review);
  if (reviewing) {
    promptText.dataset.placeholder =
      'A review of the last turn is open \u2014 forward, dismiss or cancel it';
  }
  const canPrompt = session.capabilities?.prompt !== false && !reviewing;
  promptText.setAttribute('contenteditable', String(canPrompt));
  sendButton.disabled = !canPrompt || promptInFlight;
  if (session.plan_mode_active) {
    state.textContent = `${sessionLifecycleLabel(session)} · plan`;
  }
}

/// Drop everything the conversation view was holding.
///
/// Leaving has to clear the keyed nodes and the pending elicitation cards, or
/// the next conversation opens on top of the last one's rows.
function leaveConversation() {
  currentSession = null;
  conversationMode = null;
  conversationGeneration += 1;
  conversationPending = false;
  cursor = 0;
  acknowledged = 0;
  clearConversationContents();
  promptImages = [];
  renderAttachments();
}

document.querySelector('#login-form').onsubmit = async e => {
  e.preventDefault();
  try {
    await request('/auth/session', {
      method: 'POST',
      body: JSON.stringify({ code: document.querySelector('#code').value }),
    });
    document.querySelector('#login-error').textContent = '';
    await restoreRoute();
  } catch (err) {
    document.querySelector('#login-error').textContent = err.message;
  }
};
// ---------------------------------------------------------------------------
// Wiring
// ---------------------------------------------------------------------------

function closeMenu() {
  menu.classList.add('hidden');
  menuButton.setAttribute('aria-expanded', 'false');
}

menuButton.onclick = () => {
  const open = menu.classList.toggle('hidden');
  menuButton.setAttribute('aria-expanded', String(!open));
};

// A tap outside the menu closes it, and so does Escape. Both are capture-phase
// so a control inside the menu still receives its own click first.
document.addEventListener('pointerdown', event => {
  if (activeSessionPress && activeSessionPress.pointerId !== event.pointerId) cancelSessionPress();
  if (!menu.classList.contains('hidden') && !menu.contains(event.target) && !menuButton.contains(event.target)) {
    closeMenu();
  }
  if (openSessionMenuId) {
    const card = sessionCards.get(openSessionMenuId);
    if (!card?.contains(event.target)) closeSessionMenu();
  }
});
document.addEventListener('keydown', event => {
  if (event.key === 'Escape') {
    closeMenu();
    closeSessionMenu();
  }
});

menu.onclick = event => {
  const target = event.target.closest('button[data-route]');
  if (!target) return;
  closeMenu();
  navigate({ name: target.dataset.route });
};

logout.onclick = async () => {
  await request('/auth/session', { method: 'DELETE' });
  location.hash = '';
  location.reload();
};

backButton.onclick = () => {
  // Back means the page behind this one, which is the dashboard for the
  // workspace this route belongs to.
  navigate({ name: 'dashboard', workspaceId: selectedWorkspaceId() });
};

workspaceStrip.onclick = event => {
  const tab = event.target.closest('button[data-workspace-id]');
  if (!tab) return;
  navigate({ name: 'dashboard', workspaceId: tab.dataset.workspaceId });
};

for (const node of document.querySelectorAll(
  '.page-actions button[data-route], #new-form button[data-route]',
)) {
  node.onclick = event => {
    event.preventDefault();
    navigate({ name: node.dataset.route, workspaceId: selectedWorkspaceId() });
  };
}

window.addEventListener('hashchange', applyRoute);

for (const panel of [targetsPanel, quotaPanel]) {
  panel.onclick = async event => {
    const target = event.target.closest('button[data-refresh]');
    if (target) await runRefresh(target, target.closest('.quota-profile')?.querySelector('.quota-error'));
  };
}

newBackButton.onclick = () => {
  if (!newDraft || newDraft.step === 0) return;
  newDraft.step -= 1;
  newError.textContent = '';
  renderNewForm();
};

newForm.onsubmit = async event => {
  event.preventDefault();
  try {
    if (document.activeElement?.id === 'new-bundle-source') {
      await createNewBundle();
      return;
    }
    await advanceNew();
  } catch (err) {
    newError.textContent = err.message;
  }
};

moveBackButton.onclick = () => {
  if (!moveDraft) return;
  if (moveDraft.preparation) {
    moveDraft.preparation = null;
    moveDraft.acknowledge = false;
    moveDraft.queue = 'discard';
    moveError.textContent = '';
    renderMoveForm();
  } else {
    navigate({ name: 'dashboard', workspaceId: moveDraft.workspaceId });
  }
};

moveForm.onsubmit = async event => {
  event.preventDefault();
  await advanceMove();
};

/// One session action, from the row that carries it.
///
/// The pending set is checked at entry and released in a `finally`, so a
/// double tap cannot send twice and a failure cannot leave the control dead.
async function runSessionAction(dataset, errorNode, extra) {
  const key = `${dataset.action}:${dataset.id}`;
  if (pendingActions.has(key)) return;
  if (dataset.action === 'open') {
    navigate({ name: 'conversation', sessionId: dataset.id });
    return;
  }
  if (dataset.action === 'move') {
    const session = snapshot.sessions.find(item => item.id === dataset.id);
    if (!session) return;
    closeSessionMenu();
    navigate({
      name: 'move',
      workspaceId: session.workspace_id || selectedWorkspaceId(),
      sessionId: session.id,
    });
    return;
  }
  if (dataset.action === 'close') {
    const session = snapshot.sessions.find(item => item.id === dataset.id);
    const active = session?.chat_phase === 'running';
    const question = active
      ? 'Stop active session?\n\nThe current turn will be interrupted. Mjolnir will then save a recovery copy and destroy the target.'
      : 'Stop session?\n\nMjolnir will save a recovery copy and destroy the target.';
    if (!confirm(question)) return;
  }
  const body = { action: dataset.action, session_id: dataset.id, ...extra };
  if (dataset.action === 'rename') {
    const session = snapshot.sessions.find(x => x.id === dataset.id);
    const title = prompt('New session name', session?.title || '');
    if (title === null || !title.trim()) return;
    body.title = title.trim();
  }
  if (dataset.action === 'resume') {
    // The resume page asks these as labelled controls; a row elsewhere falls
    // back to what the session last used.
    body.profile_id = extra?.profile_id || dataset.profile;
    body.target_id = extra?.target_id || dataset.target;
    body.workspace_id = selectedWorkspaceId();
    body.queue = extra?.queue || 'start';
    if (extra && Object.prototype.hasOwnProperty.call(extra, 'additional_mounts')) {
      body.additional_mounts = extra.additional_mounts;
      body.resource_allocation = extra.resource_allocation ?? null;
    }
  }
  pendingActions.add(key);
  renderRoute();
  try {
    await request('/api/actions', { method: 'POST', body: JSON.stringify(body) });
    errorNode.textContent = '';
    await refresh();
  } catch (err) {
    errorNode.textContent = err.message;
  } finally {
    pendingActions.delete(key);
    renderRoute();
  }
}

sessions.onclick = async e => {
  const menuTrigger = e.target.closest('button[data-session-menu]');
  if (menuTrigger) {
    e.preventDefault();
    e.stopPropagation?.();
    openSessionMenu(menuTrigger.dataset.sessionMenu, menuTrigger, true);
    return;
  }
  const target = e.target.closest('button[data-action]');
  if (target) {
    closeSessionMenu();
    await runSessionAction(target.dataset, actionError);
    return;
  }
  openSessionCard(e);
};

sessions.onkeydown = handleSessionCardKeydown;
sessions.addEventListener('keydown', handleSessionMenuKeydown);
sessions.addEventListener('pointerdown', beginSessionPress);
sessions.addEventListener('pointerup', cancelSessionPress);
sessions.addEventListener('pointercancel', cancelSessionPress);
sessions.addEventListener('scroll', cancelSessionPress, { passive: true });
document.addEventListener('scroll', cancelSessionPress, { capture: true, passive: true });
document.addEventListener('pointermove', moveSessionPress, { capture: true });
document.addEventListener('pointerup', cancelSessionPress, { capture: true });
document.addEventListener('pointercancel', cancelSessionPress, { capture: true });
sessions.addEventListener('contextmenu', event => {
  const card = sessionCardFromTarget(event.target);
  if (!card || !card._session || !sessionMenuActions(card._session).length) return;
  event.preventDefault();
  openSessionMenu(card.dataset.sessionId, card._menuTrigger);
});

resumable.onclick = async e => {
  const target = e.target.closest('button[data-action]');
  if (!target) return;
  const card = target.closest('.session');
  const pick = role => card?.querySelector(`[data-role="${role}"] input:checked`)?.value;
  const recovery = target._resumeRecovery;
  const settings = recovery ? {
    additional_mounts: recovery.source_additional_mounts || [],
    resource_allocation: recovery.source_resource_allocation ?? null,
  } : {};
  await runSessionAction(target.dataset, resumeError, {
    target_id: pick('resume-target'),
    profile_id: pick('resume-profile'),
    queue: pick('resume-queue'),
    ...settings,
  });
};

document.querySelector('#prompt-form').onsubmit = e => {
  e.preventDefault();
  submitPrompt();
};
promptText.addEventListener('input', () => {
  composerInputChanged();
  if (historyOpen) {
    searchHistory(composerText());
    return;
  }
  updateCommandPalette();
  scheduleDraftSave();
});

// Ctrl-R opens the reverse lookup, the way the terminal's history search does.
promptText.addEventListener('keydown', event => {
  if ((event.ctrlKey || event.metaKey) && event.key === 'r') {
    event.preventDefault();
    historyOpen = !historyOpen;
    if (historyOpen) searchHistory(composerText());
    else updateCommandPalette();
  }
});

commandPalette.onclick = event => {
  const row = event.target.closest('button[data-insert]');
  if (!row) return;
  setComposerText(row.dataset.insert);
  placeComposerCaretAtEnd();
  promptText.focus();
  updateCommandPalette();
};

jumpToLatest.onclick = scrollToTail;
feedScroll.addEventListener('scroll', () => {
  if (atTail()) jumpToLatest.classList.add('hidden');
});

cancelTurnButton.onclick = async () => {
  await sendAction({ action: 'cancel-turn', session_id: currentSession });
};
conversationTransitionCancel.onclick = async () => {
  const id = conversationTransitionCancel.dataset.id || currentSession;
  if (!id) return;
  conversationTransitionCancel.disabled = true;
  try {
    await runSessionAction(
      { action: 'cancel', id },
      conversationTransitionError,
    );
  } finally {
    const session = snapshot?.sessions.find(item => item.id === id);
    if (session && currentSession === id) renderConversationHeader(session);
  }
};
// Rich text, and anything a paste or drop would inject as markup, never
// belongs in a prompt: refuse it here and re-insert the plain text instead.
promptText.addEventListener('beforeinput', e => {
  const kind = e.inputType || '';
  if (
    kind === 'insertHTML' ||
    kind.startsWith('insertFromDrop') ||
    kind.startsWith('insertFromPaste') ||
    kind.startsWith('format')
  )
    e.preventDefault();
});
promptText.addEventListener('paste', e => {
  const files = Array.from(e.clipboardData?.items || [])
    .filter(item => item.kind === 'file' && item.type.startsWith('image/'))
    .map(item => item.getAsFile())
    .filter(Boolean);
  if (files.length) {
    e.preventDefault();
    const session = snapshot?.sessions.find(x => x.id === currentSession);
    if (session?.prompt_images_supported) attachImageFiles(files);
    else
      document.querySelector('#conversation-error').textContent =
        'This session does not support image prompts.';
    return;
  }
  const text = e.clipboardData?.getData('text/plain');
  if (text === undefined) return;
  e.preventDefault();
  insertComposerText(text);
});
promptText.addEventListener('dragover', e => {
  e.preventDefault();
  const types = Array.from(e.dataTransfer?.types || []);
  if (e.dataTransfer)
    e.dataTransfer.dropEffect = types.some(type => type === 'text/plain' || type === 'Files')
      ? 'copy'
      : 'none';
});
promptText.addEventListener('drop', e => {
  e.preventDefault();
  placeComposerCaretAtPoint(e.clientX, e.clientY);
  const files = Array.from(e.dataTransfer?.files || []).filter(file =>
    file.type.startsWith('image/'),
  );
  if (files.length) {
    const session = snapshot?.sessions.find(x => x.id === currentSession);
    if (session?.prompt_images_supported) attachImageFiles(files);
    else
      document.querySelector('#conversation-error').textContent =
        'This session does not support image prompts.';
    return;
  }
  const text = e.dataTransfer?.getData('text/plain') || '';
  if (text) insertComposerText(text);
});
// An active IME composition steers its candidate with Enter and the arrows,
// so the composer must not read those keys until the composition ends.
promptText.addEventListener('keydown', e => {
  if (e.isComposing || e.keyCode === 229) return;
  // The palette owns the arrows, Tab and Enter while it is open, and gives
  // them back the moment it closes.
  if (paletteMatches.length) {
    if (e.key === 'ArrowDown' && moveCommandSelection(1)) return e.preventDefault();
    if (e.key === 'ArrowUp' && moveCommandSelection(-1)) return e.preventDefault();
    if ((e.key === 'Tab' || e.key === 'Enter') && !e.shiftKey && acceptCommandSelection()) {
      return e.preventDefault();
    }
    if (e.key === 'Escape') {
      paletteMatches = [];
      commandPalette.classList.add('hidden');
      return e.preventDefault();
    }
  }
  if (e.key === 'Enter' && !e.shiftKey && !e.metaKey && !e.ctrlKey && !e.altKey) {
    e.preventDefault();
    submitPrompt();
    return;
  }
  if (e.key === 'Enter' && e.shiftKey && !e.metaKey && !e.ctrlKey && !e.altKey) {
    e.preventDefault();
    insertComposerLineBreak();
    return;
  }
  if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') {
    e.preventDefault();
    submitPrompt();
  }
});
attachImage.onclick = () => imagePicker.click();
imagePicker.onchange = () => {
  const files = Array.from(imagePicker.files || []);
  imagePicker.value = '';
  attachImageFiles(files);
};
queue.onclick = async e => {
  const edit = e.target.closest('button[data-edit-queue-id]');
  const remove = e.target.closest('button[data-queue-id]');
  const target = edit || remove;
  if (!target) return;
  const id = edit ? edit.dataset.editQueueId : remove.dataset.queueId;
  const session = activeSession();
  const queued = session?.queued_prompts?.find(prompt => prompt.id === id);
  const error = document.querySelector('#conversation-error');
  try {
    await request('/api/actions', {
      method: 'POST',
      body: JSON.stringify({
        action: 'remove-queued-prompt',
        session_id: currentSession,
        queue_id: id,
      }),
    });
    if (edit && queued) {
      setComposerText(queued.text);
      placeComposerCaretAtEnd();
      promptText.focus();
      updateCommandPalette();
    }
    error.textContent = '';
    await refresh();
  } catch (err) {
    // A removal that failed leaves the prompt queued, so the composer must not
    // be filled with a copy of something that is still going to run.
    error.textContent = err.message;
  }
};

shells.onclick = async e => {
  const button = e.target.closest('button[data-shell-id]');
  if (!button) return;
  try {
    await request('/api/actions', {
      method: 'POST',
      body: JSON.stringify({
        action: 'cancel-shell',
        session_id: currentSession,
        shell_command_id: button.dataset.shellId,
      }),
    });
    await refresh();
  } catch (err) {
    document.querySelector('#conversation-error').textContent = err.message;
  }
};
// ---------------------------------------------------------------------------
// Keyboard inset
// ---------------------------------------------------------------------------
//
// How much of the window the on-screen keyboard is covering, as a custom
// property the layout reads. The `offsetTop` term is the one naive versions
// miss: on iOS the visual viewport scrolls within the layout viewport, and
// without it the composer drifts by exactly that offset.
function syncKeyboardInset() {
  const viewport = window.visualViewport;
  const inset = viewport
    ? Math.max(0, window.innerHeight - viewport.height - viewport.offsetTop)
    : 0;
  document.documentElement.style.setProperty('--keyboard-inset', `${Math.round(inset)}px`);
}

if (window.visualViewport) {
  window.visualViewport.addEventListener('resize', syncKeyboardInset);
  window.visualViewport.addEventListener('scroll', syncKeyboardInset);
}
window.addEventListener('resize', syncKeyboardInset);
syncKeyboardInset();
document.body.dataset.connection = navigator.onLine ? 'online' : 'offline';

// ---------------------------------------------------------------------------
// Connection
// ---------------------------------------------------------------------------

/// What the viewer believes about its link to the daemon.
let connection = 'online';

function setConnection(next) {
  if (connection === next) return;
  connection = next;
  document.body.dataset.connection = next;
  if (next === 'offline') announce('Offline. Showing the last state received.');
  if (next === 'reconnecting') announce('Reconnecting.');
  if (next === 'online') announce('Connected.');
}

function reconnect() {
  setConnection('reconnecting');
  startEvents();
  // A reconnect reconciles by full snapshot rather than assuming the deltas
  // missed while offline line up with the cursor.
  cursor = 0;
  refresh().then(ok => {
    if (ok) setConnection('online');
    const session = snapshot?.sessions.find(item => item.id === currentSession);
    if (ok && session?.capabilities?.open && !isTransitioningSession(session)) {
      loadConversation(false);
    }
  });
}

window.addEventListener('online', reconnect);
window.addEventListener('offline', () => setConnection('offline'));

// A backgrounded progressive web app gets no `online` event, so the first
// signal that it is back is somebody unlocking the screen.
document.addEventListener('visibilitychange', () => {
  if (document.visibilityState === 'visible' && navigator.onLine) reconnect();
});
// Clocks are presentation-only updates.  The keyed card nodes remain mounted
// so focus, an open menu, and an in-progress pointer gesture survive each
// tick.
window.setInterval(updateSessionClocks, 1000);
if ('serviceWorker' in navigator) {
  // A registration that fails means the application is not installable, and
  // nothing more. Left uncaught it is an unhandled rejection, which is exactly
  // the page error the reliability suite refuses to see.
  navigator.serviceWorker.register('/service-worker.js').catch(() => {});
}
restoreRoute();