brokk-mj-controller 2.0.0

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
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'),
  actionError = document.querySelector('#action-error'),
  resumeError = document.querySelector('#resume-error'),
  feed = document.querySelector('#conversation-feed'),
  feedScroll = document.querySelector('#conversation-scroll'),
  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'),
  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'),
  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,
  cursor = 0,
  acknowledged = 0,
  eventSource;

/// 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})$`), ([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 '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() {
  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?.capabilities?.open) {
      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',
      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;
  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;
  renderWorkspaces();
  switch (route.name) {
    case 'new':
      renderNewForm();
      break;
    case 'resume':
      renderResumable();
      break;
    case 'targets':
      renderTargets();
      break;
    case 'quota':
      renderQuota();
      break;
    case 'conversation':
      break;
    default:
      renderSessions();
  }
}

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

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
// ---------------------------------------------------------------------------

/// The state word and its icon. Colour alone never says what a session is
/// doing, because colour is the one channel a reader may not have.
const LIFECYCLE_ICON = {
  live: '',
  starting: '',
  stopping: '',
  stopped: '',
  failed: '×',
};

function liveSessions() {
  const workspaceId = selectedWorkspaceId();
  return (snapshot.sessions || []).filter(
    session =>
      session.workspace_id === workspaceId &&
      ['live', 'starting', 'stopping'].includes(session.lifecycle),
  );
}

/// Sessions grouped by project, in the order the projects first appear.
function byProject(list) {
  const groups = new Map();
  for (const session of list) {
    const key = session.project_key || session.bundle_id;
    if (!groups.has(key)) groups.set(key, { label: session.project_label || key, sessions: [] });
    groups.get(key).sessions.push(session);
  }
  return [...groups.values()];
}

function renderSessions() {
  const groups = byProject(liveSessions());
  if (!groups.length) {
    sessions.replaceChildren(el('p', 'dim', 'No live sessions in this workspace.'));
    return;
  }
  sessions.replaceChildren(
    ...groups.map(group => {
      const section = el('section', 'project');
      const heading = el('h2', 'project-heading');
      heading.append(el('span', '', group.label), el('span', 'dim', ` ${group.sessions.length}`));
      section.append(heading);
      const list = el('div', 'project-sessions');
      list.setAttribute('role', 'list');
      for (const session of group.sessions) {
        const row = sessionCard(session);
        row.setAttribute('role', 'listitem');
        list.append(row);
      }
      section.append(list);
      return section;
    }),
  );
}

/// 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 heading = el('h3', '', session.title);
  card.append(heading);

  const status = el('p', 'session-status');
  const state = el('span', `pill state-${session.lifecycle}`);
  state.append(
    withHiddenGlyph(LIFECYCLE_ICON[session.lifecycle] || ''),
    el('span', '', session.state),
  );
  status.append(state);
  if (session.has_error) status.append(el('span', 'pill alert', 'needs attention'));
  if (session.pending_elicitations?.length) {
    status.append(el('span', 'pill alert', 'input needed'));
  }
  const queued = (session.queued_prompts || []).length;
  if (queued) status.append(el('span', 'pill', `${queued} queued`));
  if (session.activity) status.append(el('span', 'pill', session.activity));
  card.append(status);

  if (session.operation) {
    const stage = session.operation.stages.map(entry => entry.label).join(' · ');
    card.append(
      el(
        'p',
        'session-operation',
        stage ? `${session.operation.kind}  ${stage}` : session.operation.kind,
      ),
    );
  }

  card.append(el('p', 'dim', `${session.target_id} · ${session.profile_id}`));

  if (session.preview?.length) {
    card.append(el('p', 'preview', session.preview.join('\n')));
  }

  const actions = el('div', 'row');
  const can = session.capabilities || {};
  if (can.open) actions.append(action('Open', '', { action: 'open', id: session.id }));
  if (can.rename)
    actions.append(action('Rename', 'secondary', { action: 'rename', id: session.id }));
  if (can.cancel_operation) {
    actions.append(action('Cancel', 'danger', { action: 'cancel', id: session.id }));
  }
  if (can.stop) actions.append(action('Stop', 'danger', { action: 'close', id: session.id }));
  if (can.resume) {
    actions.append(
      action('Resume', '', {
        action: 'resume',
        id: session.id,
        profile: session.profile_id,
        target: session.target_id,
      }),
    );
  }
  card.append(actions);
  return card;
}

/// A glyph that repeats what an adjacent word already says, so it is
/// decoration to a screen reader rather than a second reading of the same fact.
function withHiddenGlyph(glyph) {
  const node = el('span', 'state-glyph', glyph);
  node.setAttribute('aria-hidden', 'true');
  return node;
}

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

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

function fillOptions(select, items, selected) {
  select.replaceChildren(
    ...items.map(item => {
      const option = el('option', '', item.label ?? item.id);
      option.value = item.id;
      if (item.id === selected) option.selected = true;
      return option;
    }),
  );
}

// ---------------------------------------------------------------------------
// 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;

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

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 = freshDraft();
  const steps = visibleSteps();
  newDraft.step = Math.min(newDraft.step, steps.length - 1);
  const step = steps[newDraft.step];
  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.targetId = value;
          // 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;
          renderNewForm();
        }),
      );
      break;
    }
    case 'project': {
      if (targetIsBare(newDraft.targetId)) {
        body.append(
          textField(
            'Project directory',
            'new-project-directory',
            newDraft.projectDirectory,
            value => {
              newDraft.projectDirectory = 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;
          }),
        );
      }
      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);
}

function pickerField(label, id, items, value, onChange) {
  const field = el('label', 'field');
  field.append(el('span', '', label));
  const select = el('select');
  select.id = id;
  fillOptions(select, items, value);
  select.onchange = () => onChange(select.value);
  field.append(select);
  return field;
}

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 bare = targetIsBare(newDraft.targetId);
  const answer = await request('/api/preflight/new', {
    method: 'POST',
    body: JSON.stringify({
      workspace_id: selectedWorkspaceId(),
      profile_id: newDraft.profileId,
      bundle_id: newDraft.bundleId,
      target_id: newDraft.targetId,
      project_directory: bare ? newDraft.projectDirectory : null,
    }),
  });
  newDraft.dirty = answer.dirty_repositories || [];
  newDraft.preflighted = true;
  // A set the person has not seen cannot already be acknowledged.
  if (!newDraft.dirty.length) newDraft.acknowledged = false;
}

async function advanceNew() {
  const steps = visibleSteps();
  const step = steps[newDraft.step];
  newError.textContent = '';

  if (step.key === 'project') {
    if (targetIsBare(newDraft.targetId) && !newDraft.projectDirectory.trim()) {
      newError.textContent = 'Name the project directory to open.';
      return;
    }
    await preflightNew();
    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 bare = targetIsBare(newDraft.targetId);
  const body = {
    action: 'new',
    workspace_id: selectedWorkspaceId(),
    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();
  newNextButton.disabled = true;
  try {
    await request('/api/actions', { method: 'POST', body: JSON.stringify(body) });
    newDraft = null;
    await refresh();
    navigate({ name: 'dashboard', workspaceId: selectedWorkspaceId() });
  } catch (err) {
    newError.textContent = err.message;
  } finally {
    newNextButton.disabled = false;
  }
}

/// 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.
function renderResumable() {
  const list = (snapshot.sessions || []).filter(session => session.capabilities?.resume);
  if (!list.length) {
    resumable.replaceChildren(el('p', 'dim', 'No sessions to resume.'));
    return;
  }
  resumable.replaceChildren(...list.map(resumableCard));
}

function resumableCard(session) {
  const card = el('article', 'card session');
  card.dataset.sessionId = session.id;
  card.append(el('h3', '', session.title));
  card.append(el('p', 'dim', `${session.state} · ${session.profile_id}`));

  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 profiles = el('label', 'field');
  profiles.append(el('span', '', 'Profile'));
  const profilePicker = el('select');
  profilePicker.dataset.role = 'resume-profile';
  fillOptions(profilePicker, snapshot.profiles, session.profile_id);
  profiles.append(profilePicker);
  card.append(profiles);

  const targets = el('label', 'field');
  targets.append(el('span', '', 'Target'));
  const targetPicker = el('select');
  targetPicker.dataset.role = 'resume-target';
  fillOptions(
    targetPicker,
    session.compatible_resume_targets.map(id => ({ id })),
    session.compatible_resume_targets.includes(session.target_id) ? session.target_id : undefined,
  );
  targets.append(targetPicker);
  card.append(targets);

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

  const row = el('div', 'row');
  row.append(
    action('Resume', '', {
      action: 'resume',
      id: session.id,
      profile: session.profile_id,
      target: session.target_id,
    }),
  );
  card.append(row);
  return card;
}

/// 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() {
  quotaPanel.replaceChildren(
    ...(snapshot.profiles || []).map(profile => {
      const card = el('article', 'card');
      const heading = el('h3');
      heading.append(el('span', '', profile.id));
      const quota = profile.quota;
      if (quota?.has_error) heading.append(el('span', 'pill reading-low', 'unavailable'));
      else if (quota?.stale) heading.append(el('span', 'pill reading-mid', 'stale'));
      card.append(heading);
      card.append(el('p', 'dim', profile.harness_kind));

      if (!quota) {
        card.append(el('p', 'dim', 'No reading yet.'));
        card.append(refreshRow('refresh-quota', { profile_id: profile.id }));
        return card;
      }
      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 card;
    }),
  );
}

/// 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) };
  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();
    if (currentSession) 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');
    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?.capabilities?.open) {
        navigate({ name: 'dashboard', workspaceId: selectedWorkspaceId() });
        return true;
      }
      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.length
      ? 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;
        })
      : [el('p', 'dim', 'No queued prompts.')]),
  );
  const running = session.active_user_shells || [];
  shells.replaceChildren(
    ...(running.length
      ? 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;
        })
      : [el('p', 'dim', 'No running shells.')]),
  );
}
// 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}`;
}
function elicitationOptionLabel(option) {
  return option.description ? `${option.title} \u2014 ${option.description}` : option.title;
}
function elicitationControl(field) {
  if (field.kind === 'single_select' || field.kind === 'multi_select') {
    const select = document.createElement('select');
    select.multiple = field.kind === 'multi_select';
    if (!select.multiple && !field.required) select.appendChild(new Option('', ''));
    for (const option of field.options || [])
      select.appendChild(new Option(elicitationOptionLabel(option), option.value));
    if (field.kind === 'single_select' && field.default != null) select.value = field.default;
    if (select.multiple && (field.default || []).length)
      for (const option of select.options) option.selected = field.default.includes(option.value);
    return select;
  }
  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.selectedOptions].map(option => option.value);
    return values.length || field.required ? values : undefined;
  }
  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 select 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 = [];
  for (const field of request.fields || []) {
    const wrapper = document.createElement('label');
    wrapper.className = 'elicitation-field';
    const label = document.createElement('span');
    label.textContent = `${field.title}${field.required ? ' *' : ''}`;
    const 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);
    }
    if (field.kind === 'multi_select') {
      const check = () => {
        const count = control.selectedOptions.length;
        const few =
          field.min_items != null && (count > 0 || field.required) && count < field.min_items;
        const many = field.max_items != null && count > field.max_items;
        control.setCustomValidity(
          few
            ? `Select at least ${field.min_items} option(s).`
            : many
              ? `Select at most ${field.max_items} option(s).`
              : '',
        );
      };
      control.addEventListener('change', check);
      check();
    }
    form.append(wrapper);
    entries.push({ field, control });
  }
  const customByOwner = new Map();
  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);
  }
  return () => {
    for (const entry of entries)
      if (entry.field.kind === 'text') entry.control.value = entry.control.value.trim();
    if (!form.reportValidity()) return null;
    const active = new Map();
    for (const [owner, entry] of customByOwner)
      if (entry.control.value !== '') active.set(owner, entry);
    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;

async function loadConversation(delta = false) {
  if (!currentSession) 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}` : ''}`,
    );
    if (generation !== conversationGeneration) 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 }),
      });
      if (generation !== conversationGeneration) return;
      acknowledged = through;
    }
  } catch (err) {
    if (generation !== conversationGeneration) return;
    if (err.message === 'unauthorized') {
      showLogin();
      return;
    }
    document.querySelector('#conversation-error').textContent = err.message;
  } finally {
    conversationInFlight = false;
    if (conversationPending && generation === conversationGeneration) {
      conversationPending = false;
      loadConversation(true);
    }
  }
}

async function openConversation(id) {
  if (currentSession === id) return;
  const session = snapshot?.sessions.find(x => x.id === id);
  if (!session?.capabilities?.open) return;
  currentSession = id;
  conversationGeneration += 1;
  conversationPending = false;
  cursor = 0;
  acknowledged = 0;
  entryNodes.clear();
  feed.replaceChildren();
  document.querySelector('#conversation-title').textContent = session.title;
  document.querySelector('#conversation-state').textContent = session.state;
  renderQueue(session);
  renderElicitations(session);
  renderTurnReview(session);
  renderConversationHeader(session);
  promptImages = [];
  renderAttachments();
  restoreDraft(id, conversationGeneration);
  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 renderConversationHeader(session) {
  document.querySelector('#conversation-title').textContent = session.title;
  const state = document.querySelector('#conversation-state');
  state.textContent = session.state;
  state.className = `pill state-${session.lifecycle}`;
  cancelTurnButton.classList.toggle('hidden', !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 = `${session.state} · 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;
  conversationGeneration += 1;
  conversationPending = false;
  cursor = 0;
  acknowledged = 0;
  entryNodes.clear();
  feed.replaceChildren();
  elicitations.replaceChildren();
  elicitationCards.clear();
  reviewHost.replaceChildren();
  reviewSignature = null;
  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 (menu.classList.contains('hidden')) return;
  if (menu.contains(event.target) || menuButton.contains(event.target)) return;
  closeMenu();
});
document.addEventListener('keydown', event => {
  if (event.key === 'Escape') closeMenu();
});

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);
  };
}

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

newForm.onsubmit = async event => {
  event.preventDefault();
  try {
    await advanceNew();
  } catch (err) {
    newError.textContent = err.message;
  }
};

/// 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 === 'close' &&
    !confirm(
      'Save a recovery copy, stop, and destroy this session target? Queued prompts will be preserved.',
    )
  ) {
    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';
  }
  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 target = e.target.closest('button[data-action]');
  if (!target) return;
  await runSessionAction(target.dataset, actionError);
};

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(`select[data-role="${role}"]`)?.value;
  await runSessionAction(target.dataset, resumeError, {
    target_id: pick('resume-target'),
    profile_id: pick('resume-profile'),
    queue: pick('resume-queue'),
  });
};

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 });
};
// 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');
    if (ok && currentSession) 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();
});
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();