eclipse-web 0.13.4

Local web dashboard for eclipse
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf" content="{{CSRF}}">
<link rel="icon" href="/favicon.ico" sizes="any">
<title>eclipse</title>
<style>
  {{PALETTE}}
  * { box-sizing: border-box; }
  body { margin:0; height:100vh; display:flex; background:var(--bg); color:var(--fg); font:15px/1.5 system-ui, sans-serif; }
  aside { width:260px; background:var(--panel); border-right:1px solid var(--line); display:flex; flex-direction:column; }
  aside h1 { font-size:16px; margin:0; padding:14px 16px; border-bottom:1px solid var(--line); }
  aside small { display:block; color:var(--dim); font-weight:normal; margin-top:2px; }
  #model { background:transparent; border:0; padding:0; font:inherit; color:var(--dim); cursor:pointer; text-align:left; max-width:100%; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
  /* The header: the mark, the word in the accent, the version faint — one mark, drawn from the
     palette, not a second copy of the brand (#247). */
  aside h1 { display:flex; align-items:center; gap:8px; font-size:17px; letter-spacing:.02em;
    color:var(--accent); }
  aside h1 #mark { display:block; width:22px; height:22px; flex:none; }
  aside h1 .version { color:var(--faint); font:11px ui-monospace, monospace; letter-spacing:0; }
  /* The model: a control in the stats row, flush right (#238). The panel drops upward from it,
     over the transcript, so it never reflows the column it is reporting on. */
  #statsrow { position:relative; display:flex; align-items:baseline; gap:10px; padding:6px 20px 0; }
  #statsrow #stats { flex:1; padding:0; }
  /* Approvals off, in the colour the UI reserves for "pay attention to this" (#285). Shown only
     while it is on: the attribute is the server's answer, not a class the page toggles on its own. */
  #statsrow #yolo { font:600 11px/1.4 ui-monospace, monospace; letter-spacing:.08em;
    text-transform:uppercase; color:var(--bad); border:1px solid var(--bad);
    border-radius:3px; padding:0 5px; }
  #statsrow #yolo[hidden] { display:none; }
  /* `#340`: `smart` approvals, in the same alert colour for the same reason — some calls run
     without a card, and the row has to say so before the first one does. */
  #statsrow #judge { font:600 11px/1.4 ui-monospace, monospace; letter-spacing:.08em;
    text-transform:uppercase; color:var(--bad); border:1px dashed var(--bad);
    border-radius:3px; padding:0 5px; }
  #statsrow #judge[hidden] { display:none; }
  /* The way back down (#339). Floated over the transcript's bottom corner like the model menu, in
     the accent while it is only activity and in the alert colour once an approval is waiting. */
  #jump { position:absolute; right:20px; bottom:calc(100% + 8px); z-index:19;
    background:var(--panel); color:var(--accent); border:1px solid var(--line); border-radius:999px;
    padding:5px 12px; font:600 12px/1.3 ui-monospace, monospace; cursor:pointer;
    box-shadow:0 6px 18px rgba(0,0,0,.45); }
  #jump:hover { color:var(--fg); border-color:var(--accent); }
  #jump.card { color:var(--bad); border-color:var(--bad); }
  #jump[hidden] { display:none; }
  #model { flex:none; background:transparent; color:var(--dim); border:1px solid var(--line);
    border-radius:999px; padding:1px 10px; font:11px/1.5 ui-monospace, monospace; cursor:pointer;
    max-width:40ch; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
  #model:hover, #model[aria-expanded="true"] { color:var(--fg); border-color:var(--accent); }
  /* The effort in force, quietly: faint while it is the file's level, accent while the session is
     the reason. Colouring it always would make the ordinary case shout. */
  #effort { flex:none; font:11px/1.5 ui-monospace, monospace; color:var(--faint);
    white-space:nowrap; }
  #effort.session { color:var(--accent); }
  #models { position:absolute; right:20px; bottom:calc(100% + 6px); z-index:20; min-width:280px;
    max-width:min(420px, 90vw); max-height:45vh; overflow-y:auto; background:var(--panel);
    border:1px solid var(--line); border-radius:8px; box-shadow:0 8px 24px rgb(0 0 0 / .45); }
  #models button { display:block; width:100%; text-align:left; background:transparent; color:var(--fg);
    border:0; border-radius:0; padding:6px 12px; font:12px/1.5 ui-monospace, monospace; cursor:pointer; }
  #models button:hover, #models button:focus-visible { background:var(--hover); outline:none; }
  #models button.current { color:var(--accent); }
  #models button.dim { color:var(--dim); }
  #models button:disabled { color:var(--faint); cursor:default; }
  #models button.head { color:var(--dim); font-size:10px; letter-spacing:.1em; text-transform:uppercase; }
  #modelnote { color:var(--dim); font-size:11px; padding:8px 12px; border-top:1px solid var(--line); }
  #modelnote:empty { display:none; }
  #models[hidden] { display:none; }
  /* The composer's `/` menu (#282): a render of the server's table, opening upward from a box that
     sits at the bottom — the same shape as the model picker, for the same reason. */
  #cmdmenu { position:absolute; left:0; bottom:calc(100% + 6px); z-index:21; min-width:340px;
    max-width:min(560px, 100%); max-height:280px; overflow-y:auto; background:var(--bg);
    border:1px solid var(--line); border-radius:10px; padding:5px; box-shadow:0 10px 28px rgba(0,0,0,.45); }
  #cmdmenu button { display:flex; gap:10px; align-items:baseline; width:100%; text-align:left;
    background:transparent; color:var(--fg); border:0; border-radius:6px; padding:5px 8px; cursor:pointer;
    font:12px/1.4 ui-monospace, monospace; }
  #cmdmenu button .label { color:var(--accent); white-space:nowrap; }
  #cmdmenu button .why { color:var(--dim); font-family:inherit; overflow:hidden;
    text-overflow:ellipsis; white-space:nowrap; }
  #cmdmenu button[aria-selected="true"] { background:var(--hover); }
  #cmdmenu .empty { color:var(--dim); font:12px/1.5 ui-monospace, monospace; padding:5px 8px; }
  #cmdmenu[hidden] { display:none; }
  #modellist button { display:block; width:100%; text-align:left; background:transparent; border:0; border-left:3px solid transparent; color:var(--fg); font:12px/1.5 ui-monospace, monospace; padding:5px 13px; cursor:pointer; overflow-wrap:anywhere; }
  #modellist button:hover:not(:disabled) { background:var(--hover); }
  #modellist button.current { border-left-color:var(--accent); color:var(--accent); }
  #modellist button.dim { color:var(--dim); }
  #settings { display:block; width:100%; margin:8px 0; background:transparent; color:var(--dim);
    border:1px solid var(--line); border-radius:6px; padding:5px 8px; cursor:pointer; }
  #settings:hover, #settings[aria-expanded="true"] { color:var(--fg); border-color:var(--accent); }
  /* The settings window (#267, reframed in #297): a dialog, because settings are not a sidebar.
     Sections down the left, one row per key on the right, and the row's words and type come from
     the server.
     The frame is a fixed size and the rows pane scrolls inside it (#297): a window that grew for
     `all` and shrank for a six-row section read as a page reload, which is the one thing a dialog
     must not do. The rest of it is room — a row carries a key, a sentence, a control and what the
     value is now, and those used to sit 12px apart with a hairline as the only grouping. */
  #settingswindow { width:min(1040px, 94vw); height:min(760px, 84vh); padding:0; background:var(--bg);
    color:var(--fg); border:1px solid var(--line); border-radius:12px; box-shadow:0 24px 60px rgba(0,0,0,.55); }
  /* `[open]` because a bare `display:flex` would draw the dialog before it is opened. */
  #settingswindow[open] { display:flex; flex-direction:column; }
  #settingswindow::backdrop { background:rgba(0,0,0,.55); }
  #settingswindow header { display:flex; gap:10px; align-items:center; padding:14px 18px;
    border-bottom:1px solid var(--line); flex:0 0 auto; }
  #settingswindow h2 { margin:0; font-size:13px; font-weight:600; letter-spacing:.06em;
    text-transform:uppercase; color:var(--dim); }
  #settingswindow header .grow { flex:1; }
  #setfind { width:240px; background:var(--panel); color:var(--fg); border:1px solid var(--line);
    border-radius:6px; padding:6px 9px; font:inherit; font-size:13px; }
  #setclose { background:transparent; border:1px solid var(--line); color:var(--dim); border-radius:6px;
    width:28px; height:28px; cursor:pointer; font-size:14px; line-height:1; }
  #setbody { display:flex; gap:0; flex:1; min-height:0; }
  #setsections { width:200px; flex:0 0 auto; border-right:1px solid var(--line); overflow-y:auto;
    padding:12px 8px; }
  #setsections button { display:flex; justify-content:space-between; gap:8px; width:100%;
    background:transparent; border:0; color:var(--dim); border-radius:6px; padding:7px 10px; cursor:pointer;
    font:inherit; font-size:13px; text-align:left; min-height:32px; align-items:center; }
  #setsections button:hover { background:var(--hover); color:var(--fg); }
  #setsections button[aria-current="true"] { background:var(--hover); color:var(--fg); }
  #setsections .count { color:var(--faint); font-size:12px; }
  /* `scrollbar-gutter` so a long section does not shove the rows sideways: the same "it must not
     move" rule as the frame itself. */
  #setrows { flex:1; min-width:0; overflow-y:auto; scrollbar-gutter:stable; padding:18px 24px 28px; }
  #setrows h3 { margin:24px 0 2px; font:11px/1.4 ui-monospace, monospace; color:var(--dim);
    letter-spacing:.08em; text-transform:uppercase; }
  #setrows h3:first-child { margin-top:0; }
  #setrows .sectionabout { color:var(--dim); font-size:13px; line-height:1.5; margin:0 0 12px;
    max-width:66ch; }
  .srow { padding:15px 0 17px; border-bottom:1px solid var(--line); }
  .srow:last-child { border-bottom:0; }
  .srow .what { display:flex; gap:8px; align-items:baseline; flex-wrap:wrap; }
  .srow code { font:13px/1.4 ui-monospace, monospace; color:var(--fg); }
  .srow .about { color:var(--dim); font-size:13px; line-height:1.5; margin:5px 0 10px;
    max-width:66ch; }
  /* One line of controls per row, with the value's provenance pushed to its right (#297): `now: …`
     was a fourth line under the control, which is what made five rows read as one block. */
  .srow .ctl { display:flex; gap:8px; align-items:center; flex-wrap:wrap; }
  .srow .ctl .where { margin-left:auto; text-align:right; }
  .srow input[type=text], .srow input[type=password], .srow input[type=number], .srow select,
  .srow textarea { background:var(--panel); color:var(--fg); border:1px solid var(--line);
    border-radius:6px; padding:5px 8px; font:13px/1.4 ui-monospace, monospace; min-width:170px; }
  .srow textarea { min-width:300px; resize:vertical; }
  .srow input:focus, .srow select:focus, .srow textarea:focus { outline:1px solid var(--accent); }
  .srow button { background:transparent; color:var(--dim); border:1px solid var(--line);
    border-radius:6px; padding:5px 10px; cursor:pointer; font:inherit; font-size:13px; }
  .srow button:hover:not(:disabled) { color:var(--fg); border-color:var(--accent); }
  .srow button:disabled { color:var(--faint); cursor:default; }
  /* A boolean is a switch (#297): the only control here whose state is a position, so `on` is told
     apart from `off` without reading the key — and it stops being a button shaped like `set`. */
  .srow .switch { display:inline-flex; align-items:center; gap:9px; background:transparent; border:0;
    padding:0; cursor:pointer; color:var(--dim); font:inherit; font-size:13px; }
  .srow .switch .track { position:relative; width:34px; height:18px; border-radius:9px;
    background:var(--panel); border:1px solid var(--line); transition:background .12s, border-color .12s; }
  .srow .switch .track::after { content:''; position:absolute; top:2px; left:2px; width:12px;
    height:12px; border-radius:50%; background:var(--dim); transition:transform .12s, background .12s; }
  .srow .switch[aria-checked="true"] { color:var(--fg); }
  .srow .switch[aria-checked="true"] .track { background:var(--accent); border-color:var(--accent); }
  .srow .switch[aria-checked="true"] .track::after { transform:translateX(16px); background:var(--bg); }
  .srow .where { color:var(--faint); font-size:11px; }
  .srow .where .restart { color:var(--warn); border:1px solid currentColor; border-radius:999px;
    padding:1px 7px; font-size:10.5px; letter-spacing:.02em; white-space:nowrap; }
  .srow .err { color:var(--bad); font-size:12px; margin-top:8px; }
  .srow .err:empty { display:none; }
  #setsections h4 { margin:14px 0 4px; padding:0 10px; font:10px/1.4 ui-monospace, monospace;
    color:var(--faint); letter-spacing:.1em; text-transform:uppercase; }
  #setsections h4:first-child { margin-top:2px; }
  #setrows .meter { display:flex; flex-direction:column; gap:5px; color:var(--dim); font-size:12px;
    margin:6px 0 12px; }
  #setrows .meter .bar { height:4px; background:var(--panel); border-radius:2px; overflow:hidden; }
  #setrows .meter .bar i { display:block; height:4px; background:var(--accent); }
  #setrows .meter .bar.over i { background:var(--bad); }
  #setrows .about.warn { color:var(--warn); }
  #filetext { width:100%; box-sizing:border-box; background:var(--panel); color:var(--fg);
    border:1px solid var(--line); border-radius:8px; padding:10px 12px; resize:vertical;
    min-height:320px; font:12.5px/1.5 ui-monospace, monospace; }
  #filetext:focus { outline:1px solid var(--accent); }
  .filebar { margin-top:8px; }
  .filebar .where { margin-left:auto; }
  .srow button.primary, .filebar button.primary { color:var(--accent); border-color:var(--accent); }
  .srow button.primary:disabled, .filebar button.primary:disabled { color:var(--faint);
    border-color:var(--line); }
  #setnote { color:var(--dim); font-size:11px; padding:8px 14px; border-top:1px solid var(--line); }
  #modelnote { color:var(--dim); font-size:11px; line-height:1.4; padding:4px 13px 8px; }
  #new { margin:10px; padding:8px; background:transparent; color:var(--accent); border:1px solid var(--line); border-radius:6px; cursor:pointer; }
  #logout { margin:10px; }
  #logout button { width:100%; padding:6px; background:transparent; color:var(--dim); border:1px solid var(--line); border-radius:6px; cursor:pointer; }
  #sessions { list-style:none; margin:0; padding:0; overflow-y:auto; flex:1; }
  #sessions li { padding:8px 16px; cursor:pointer; border-bottom:1px solid var(--line); font-size:13px; }
  #sessions li.group, #sessions li.session { border-bottom:0; }
  #sessions li:hover, #sessions li.active { background:var(--hover); }
  #sessions .meta { color:var(--dim); font-size:11px; }
  #sessions .name { overflow-wrap:anywhere; }
  /* One control per row. The four buttons this replaces were forty controls on screen at ten
     sessions, with the irreversible one at the same weight as the rest. The menu exists in the DOM
     whether or not it is open — a node built on hover cannot be reached by Tab — and the ⋮ stays
     faint until the row is hovered, focused, or the menu is open. */
  #sessions li.session { display:flex; align-items:flex-start; gap:6px; position:relative; }
  #sessions li.session .name { flex:1; min-width:0; }
  #sessions .dots { flex:none; background:transparent; border:0; color:var(--dim);
    font:14px/1 inherit; padding:0 2px; cursor:pointer; opacity:.35; }
  #sessions li.session:hover .dots, #sessions li.session:focus-within .dots,
  #sessions li.session.active .dots, #sessions .dots[aria-expanded="true"] { opacity:1; }
  #sessions .dots:hover { color:var(--fg); }
  #sessions .menu { position:absolute; right:8px; top:4px; z-index:6; min-width:150px;
    background:var(--panel); border:1px solid var(--line); border-radius:8px; padding:4px;
    box-shadow:0 10px 30px rgba(0,0,0,.45); }
  #sessions .menu[hidden] { display:none; }
  #sessions .menu button { display:block; width:100%; text-align:left; background:transparent;
    border:0; border-radius:5px; color:var(--fg); font:12px/1.5 inherit; padding:5px 9px;
    cursor:pointer; }
  #sessions .menu button:hover, #sessions .menu button:focus-visible { background:var(--hover); }
  #sessions .menu button.danger { color:var(--bad); }
  /* A section label: the day's name, the count, and a hairline running out to the edge of the list.
     The label is a button (#345) — it opens and closes the section — so the whole row is the
     control and the hairline lives on it, which keeps the row reading as "label - rule - edge". */
  #sessions li.group { display:flex; align-items:center; padding:0; border:0; }
  #sessions li.group > button { display:flex; align-items:center; gap:8px; flex:1; width:100%;
    padding:10px 16px 4px; border:0; background:transparent; cursor:pointer;
    font:10px/1.4 ui-monospace, monospace; letter-spacing:.12em; text-transform:uppercase;
    color:var(--dim); text-align:left; }
  #sessions li.group > button::after { content:''; flex:1; height:1px; background:var(--line); }
  #sessions li.group > button:hover { color:var(--fg); }
  #sessions li.group > button:focus-visible { outline:2px solid var(--accent); outline-offset:-3px;
    border-radius:6px; }
  #sessions li.group .chev { width:9px; flex:0 0 9px; }
  #sessions li.group .gcount { color:var(--dim); opacity:.7; letter-spacing:.06em; }
  /* The section holding the session being read, when that row is not on screen: the heading is the
     only place left to answer "where am I" (#345). */
  #sessions li.group > button.here .chev { color:var(--accent); }
  #sessions li.group > button.here .gname { color:var(--accent); }
  /* An archived row is only here because the filter asked for it (#240): the same row, quieter,
     so the list a person reads and the list they asked to see are still told apart at a glance. */
  #sessions li.session[data-archived="1"] .name { color:var(--dim); }
  #archtoggle { display:flex; align-items:center; gap:6px; margin:0 10px 6px; color:var(--dim);
    font:11px/1.4 ui-monospace, monospace; cursor:pointer; }
  #archtoggle input { margin:0; accent-color:var(--accent); }
  /* The `+` menu (#239): one round control at the left of the composer, its rows above it, and a
     chip per attached item saying what it is. Disabled rows keep their place in the list — a menu
     that hides `image` today and shows it tomorrow teaches nothing. */
  #plus { flex:0 0 auto; width:30px; height:30px; border-radius:50%; background:transparent;
    border:1px solid var(--line); color:var(--dim); font:16px/1 inherit; cursor:pointer;
    align-self:flex-end; margin-bottom:5px; }
  #plus:hover, #plus[aria-expanded="true"] { color:var(--fg); border-color:var(--accent); }
  /* The reasoning switch (#293): a label that never changes its verb, and a track with a knob. */
  .switchrow { display:flex; align-items:center; justify-content:space-between; gap:12px; width:100%; }
  .switchrow .track { position:relative; flex:0 0 auto; width:30px; height:16px; border-radius:999px;
    background:var(--line); transition:background .12s ease; }
  .switchrow .track .knob { position:absolute; top:2px; left:2px; width:12px; height:12px;
    border-radius:50%; background:var(--dim); transition:left .12s ease, background .12s ease; }
  .switchrow[aria-checked="true"] .track { background:var(--accent); }
  .switchrow[aria-checked="true"] .track .knob { left:16px; background:var(--bg); }
  .switchrow .switchlabel { color:var(--fg); }
  .switchrow.dim .switchlabel { color:var(--dim); }
  .switchrow:disabled { cursor:default; }
  .switchrow:disabled .track { opacity:.45; }
  #attachmenu { position:absolute; bottom:calc(100% + 8px); left:0; z-index:20; min-width:300px;
    background:var(--bg); border:1px solid var(--line); border-radius:10px; padding:6px;
    box-shadow:0 16px 40px rgba(0,0,0,.5); display:flex; flex-direction:column; gap:2px; }
  #attachmenu[hidden] { display:none; }
  #attachmenu button { display:flex; flex-direction:column; gap:1px; align-items:flex-start;
    background:transparent; border:0; border-radius:6px; padding:7px 10px; cursor:pointer;
    color:var(--fg); font:inherit; font-size:13px; text-align:left; }
  #attachmenu button span { color:var(--dim); font-size:11.5px; }
  #attachmenu button:hover:not(:disabled), #attachmenu button:focus-visible { background:var(--hover); }
  #attachmenu button:disabled { color:var(--faint); cursor:default; }
  #attachmenu button:disabled b { color:var(--faint); }
  #attached { display:flex; gap:8px; flex-wrap:wrap; padding:6px 20px 0; }
  #attached[hidden] { display:none; }
  #attached .chip { display:inline-flex; align-items:center; gap:8px; background:var(--panel);
    border:1px solid var(--line); border-radius:999px; padding:3px 4px 3px 10px;
    font:11.5px/1.4 ui-monospace, monospace; color:var(--fg); }
  #attached .chip .x { width:18px; height:18px; border-radius:50%; border:0; background:transparent;
    color:var(--dim); cursor:pointer; font:12px/1 inherit; }
  #attached .chip .x:hover { color:var(--bad); }
  #composer { position:relative; }
  #find { margin:0 10px 6px; padding:6px 8px; background:var(--bg); color:var(--fg); border:1px solid var(--line); border-radius:6px; font:12px/1.4 inherit; }
  #findinfo { color:var(--dim); font-size:11px; padding:0 10px 6px; min-height:14px; }
  main { flex:1; display:flex; flex-direction:column; min-width:0; }
  /* The update badge: a standing line at the top of the transcript column, opposite the header's
     version, shown only while the install is behind. The page never checks for itself — the
     gateway's schedule writes the cache and this reads it. */
  #notice { position:relative; display:flex; justify-content:flex-end; padding:8px 20px 0; }
  #notice[hidden] { display:none; }
  #updatebadge { background:transparent; border:1px solid var(--line); border-radius:999px;
    color:var(--warn); font:12px/1.4 ui-monospace, monospace; padding:2px 10px; cursor:pointer; }
  #updatebadge:hover, #updatebadge[aria-expanded="true"] { border-color:var(--warn); }
  #updatepop { position:absolute; right:20px; top:32px; z-index:5; width:min(340px, 86vw);
    background:var(--panel); border:1px solid var(--line); border-radius:8px; padding:12px 14px;
    box-shadow:0 10px 30px rgba(0,0,0,.45); }
  #updatepop[hidden] { display:none; }
  #updatepop p { margin:0 0 8px; }
  #updatepop code { display:block; font:12px/1.5 ui-monospace, monospace; background:var(--bg);
    border:1px solid var(--line); border-radius:4px; padding:5px 8px; margin-bottom:6px; }
  #updatepop .why { color:var(--dim); font-size:12px; margin:8px 0 0; }
  #log { flex:1; overflow-y:auto; padding:20px; }
  /* The column is the pane (#237). It used to be a letter-sized ribbon centred between two gutters
     while the sidebar ran to its own edge — two halves of one page, measured differently. There is
     no maximum width here on purpose: a cap is the thing that made the page read as a document in
     a window, and a wide one is the only place a long answer is comfortable. */
  .msg { margin:0 0 14px; white-space:pre-wrap; overflow-wrap:anywhere; }
  /* Only the person's turn is a block. The model's answer, its reasoning and its tool rows are the
     page talking, printed the way the terminal prints them — one bubble per turn down the page was
     a wall of panels that made the conversation look like a form. */
  /* The user's own words: the CLI's blue is the edge, not the fill — a filled block in a
     second colour competed with the answer for the eye. */
  /* `#346`: a picture the turn carried. Bounded so one screenshot cannot take the pane, and a
     max-height rather than a fixed size so a tall shot and a wide one both read. */
  .msg img.sent { display:block; margin-top:8px; max-width:100%; max-height:340px;
                  border:1px solid var(--line); border-radius:8px; }
  .msg.user { background:var(--panel); border-left:3px solid var(--user); border-radius:0 8px 8px 0; padding:10px 14px; }
  /* The line that was a command (#254): the person's own words, unboxed — it is not a turn, so
     it does not wear a turn's panel. */
  .msg.command { font:12px/1.5 ui-monospace, monospace; color:var(--dim); padding:2px 0; }
  .msg.assistant { padding:2px 0; }
  .msg.tool { font:12px/1.4 ui-monospace, monospace; color:var(--dim); border-left:3px solid var(--line); border-radius:0; padding:4px 10px; }
  .msg.approval { border:1px solid var(--accent); background:var(--panel); border-radius:8px; padding:10px 14px; }
  .msg.approval .meta { color:var(--dim); font-size:12px; margin-top:4px; }
  .msg.approval .actions { margin-top:8px; display:flex; gap:8px; }
  .msg.approval button { border:1px solid var(--line); border-radius:6px; padding:4px 14px; cursor:pointer; color:var(--fg); background:transparent; }
  .msg.approval button.yes { background:var(--accent); color:var(--ink); border:0; font-weight:600; }
  .msg.error { color:var(--bad); border:1px solid var(--bad); border-radius:8px; padding:10px 14px; }
  /* A command's answer (#254): the app talking, in columns that have to keep their alignment. */
  .msg.notice { font:12px/1.55 ui-monospace, monospace; color:var(--fg); background:transparent;
    border-left:3px solid var(--accent); border-radius:0; padding:6px 10px; white-space:pre-wrap;
    overflow-wrap:anywhere; }
  .msg.notice.refusal { color:var(--bad); border-left-color:var(--bad); }
  /* Folds. A reasoning model can think for a page and a half before it says anything, and a
     write_file carries a whole file in its arguments: both belong behind a summary row, with the
     text one click (or one Enter, on the focused summary) away. <details> gives the keyboard for
     free, which a click-only handler would not. */
  details.msg { padding:0; }
  /* The folded user turn: the same block as a short one (fill, blue left rule) with a summary row
     that says how big it is, and the text inside the fold rather than in the page. */
  details.msg.user.big { background:var(--panel); border-left:3px solid var(--user); border-radius:0 8px 8px 0; }
  details.msg.user.big > summary { color:var(--dim); font:12px/1.5 ui-monospace, monospace; padding:8px 14px; }
  details.msg.user.big > summary:hover { color:var(--fg); }
  details.msg.user.big .pasted { padding:0 14px 10px; white-space:pre-wrap; overflow-wrap:anywhere;
    max-height:60vh; overflow-y:auto; }
  details.msg > summary { cursor:pointer; padding:6px 12px; list-style:none; }
  details.msg > summary::-webkit-details-marker { display:none; }
  details.msg > summary::marker { content:''; }
  details.msg > summary:hover { color:var(--fg); }
  details.reasoning { font-size:13px; font-style:italic; color:var(--dim); border-left:3px solid var(--rule); border-radius:0; }
  details.reasoning > summary { font-style:normal; }
  details.reasoning .think { padding:0 12px 8px; white-space:pre-wrap; overflow-wrap:anywhere; }
  details.tool { font:12px/1.4 ui-monospace, monospace; color:var(--dim); border-left:3px solid var(--rule); border-radius:0; }
  details.tool > summary { overflow-wrap:anywhere; }
  /* The mark is the whole verdict — what the call printed belongs behind the row, not in the
     conversation, exactly as the terminal prints one line per call. */
  details.tool .mark { margin-right:6px; }
  details.tool.running .mark, details.tool.refused .mark { color:var(--warn); }
  details.tool.ok .mark { color:var(--ok); }
  details.tool.failed .mark { color:var(--bad); }
  details.tool.failed > summary { color:var(--bad); }
  details.tool .cap { color:var(--dim); font-size:10px; letter-spacing:.1em; text-transform:uppercase; padding:0 12px 2px; }
  details.tool .args, details.tool .out { margin:0; padding:0 12px 8px; color:var(--fg); font-size:11px; white-space:pre-wrap; overflow-wrap:anywhere; }
  details.tool .out { color:var(--dim); }
  #thinkbar { padding:8px 20px 0; }
  #thinkbar[hidden] { display:none; }
  #thinkall { background:transparent; border:1px solid var(--line); border-radius:999px;
    color:var(--dim); font:11px/1.4 ui-monospace, monospace; padding:1px 9px; cursor:pointer; }
  #thinkall:hover { color:var(--fg); border-color:var(--dim); }
  .msg.composing { opacity:.7; }
  #form { display:flex; flex-direction:column; gap:8px; padding:14px 20px; border-top:1px solid var(--line); width:100%; }
  #composer { display:flex; gap:8px; align-items:flex-start; }
  #pastes { display:flex; flex-wrap:wrap; gap:6px; }
  #pastes[hidden] { display:none; }
  /* A chip is a thing you can remove, so it is a button, not a label with a × painted on it. */
  .paste { display:inline-flex; align-items:center; gap:6px; background:var(--panel); color:var(--dim);
    border:1px solid var(--line); border-radius:999px; padding:2px 10px;
    font:11px/1.6 ui-monospace, monospace; cursor:pointer; }
  .paste:hover { color:var(--fg); border-color:var(--bad); }
  .paste .x { color:var(--faint); }
  textarea { flex:1; resize:none; background:var(--panel); color:var(--fg); border:1px solid var(--line); border-radius:8px; padding:10px; font:inherit; }
  /* One control, two states (#236). Two buttons for one job put a dead button on screen next to a
     live one; and neither had a height, so both stretched to the textarea and read as a slab.
     It is the height of one line of that textarea, not of the textarea. */
  button.go { align-self:center; height:34px; min-width:74px; padding:0 16px; border-radius:8px;
    background:var(--accent); color:var(--ink); border:0; font-weight:600; cursor:pointer; }
  button.go.stop { background:transparent; color:var(--dim); border:1px solid var(--line); }
  button.go.stop:hover { color:var(--fg); border-color:var(--bad); }
  button.go[data-state="starting"] { color:var(--dim); }
  button:disabled { opacity:.5; cursor:default; }
  #status { color:var(--dim); font-size:12px; text-align:center; padding-bottom:8px; }
  #open { display:flex; gap:10px; align-items:baseline; padding:2px 20px 8px; font-size:13px; color:var(--fg); }
  #open[hidden] { display:none; }
  #openname { font-weight:600; overflow-wrap:anywhere; }
  #openid { color:var(--faint); font:11px/1.4 ui-monospace, monospace; }
  #stats { font:12px/1.4 ui-monospace, monospace; color:var(--dim); padding:6px 20px 0; text-align:center; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
  /* A row describing a turn nobody is watching (#344): the suffix says so in words, and the
     dimming says it before the words are read. Opacity, not a colour — the palette owns colour. */
  #stats.last { opacity:.72; }
  /* `#509`: `#bots` is the same button as `#cron`, because it is the same kind of thing — a view
     that takes the column — and a second set of four declarations would drift from the first. */
  #cron, #bots { display:block; width:100%; margin:0 0 8px; background:transparent; color:var(--dim);
    border:1px solid var(--line); border-radius:8px; padding:5px 0; cursor:pointer; }
  #cron:hover, #cron.on, #bots:hover, #bots.on { color:var(--fg); border-color:var(--accent); }
  main.cron #log, main.cron #stats, main.cron #status, main.cron #form,
  main.cron #thinkbar, main.cron #notice, main.cron #open { display:none; }
  #cronpane { display:none; flex:1; overflow-y:auto; padding:16px 20px; }
  main.cron #cronpane { display:block; }
  #cronpane h2 { font-size:15px; margin:0 0 2px; font-weight:600; }
  #cronpane header { display:flex; align-items:baseline; gap:10px; flex-wrap:wrap; margin-bottom:12px; }
  #cronpane header small { color:var(--dim); font:11px ui-monospace, monospace; overflow-wrap:anywhere; }
  #cronpane header .grow { flex:1; }
  #cronpane button { background:transparent; color:var(--dim); border:1px solid var(--line);
    border-radius:6px; padding:3px 9px; cursor:pointer; font:12px/1.4 inherit; }
  #cronpane button:hover:not(:disabled) { color:var(--fg); border-color:var(--accent); }
  #cronpane button:disabled { opacity:.45; cursor:default; }
  #cronpane button.go { color:var(--accent); }
  #cronpane button.bad:hover { color:var(--bad); border-color:var(--bad); }
  #crontable { width:100%; border-collapse:collapse; font-size:13px; }
  #crontable th { text-align:left; color:var(--dim); font-weight:normal; font-size:11px;
    text-transform:uppercase; letter-spacing:.06em; border-bottom:1px solid var(--rule); padding:4px 8px 4px 0; }
  #crontable td { border-bottom:1px solid var(--line); padding:6px 8px 6px 0; vertical-align:top; }
  #crontable td.name { font-family:ui-monospace, monospace; color:var(--accent); overflow-wrap:anywhere; }
  #crontable td.when { color:var(--dim); white-space:nowrap; }
  #crontable td.acts { text-align:right; white-space:nowrap; }
  #crontable td.acts button { margin-left:4px; padding:2px 7px; }
  #crontable tr.off td.name, #crontable tr.off td.when { color:var(--dim); text-decoration:line-through; }
  #crontable td.last.ok { color:var(--ok); }
  #crontable td.last.failed { color:var(--bad); }
  #cronmsg { font-size:12px; min-height:1.2em; margin:0 0 10px; color:var(--dim); }
  #cronmsg.bad { color:var(--bad); }
  #cronform { border:1px solid var(--line); border-radius:8px; padding:12px; margin:14px 0; }
  #cronform label { display:block; color:var(--dim); font-size:12px; margin-bottom:8px; }
  #cronform input, #cronform textarea { display:block; width:100%; margin-top:3px; background:var(--bg);
    color:var(--fg); border:1px solid var(--line); border-radius:6px; padding:5px 8px;
    font:13px/1.5 ui-monospace, monospace; }
  #cronform input:focus, #cronform textarea:focus { outline:1px solid var(--accent); }
  #cronform .row { display:flex; gap:8px; margin-top:8px; }
  #cronlogs { margin-top:16px; }
  #cronlogs h3 { font-size:13px; margin:0 0 6px; }
  #cronlogs article { border-left:2px solid var(--line); padding:2px 0 2px 10px; margin-bottom:10px; }
  #cronlogs .at { color:var(--dim); font:11px ui-monospace, monospace; }
  #cronlogs pre { margin:4px 0 0; white-space:pre-wrap; overflow-wrap:anywhere;
    font:12px/1.5 ui-monospace, monospace; color:var(--fg); }
  #cronlogs .more { color:var(--warn); font-size:11px; }
  #mcp { display:block; width:100%; margin:0 0 8px; background:transparent; color:var(--dim);
    border:1px solid var(--line); border-radius:8px; padding:5px 0; cursor:pointer; }
  #mcp:hover, #mcp.on { color:var(--fg); border-color:var(--accent); }
  main.mcp #log, main.mcp #stats, main.mcp #status, main.mcp #form,
  main.mcp #thinkbar, main.mcp #notice, main.mcp #open { display:none; }
  #mcppane { display:none; flex:1; overflow-y:auto; padding:16px 20px; }
  main.mcp #mcppane { display:block; }
  #mcppane h2 { font-size:15px; margin:0 0 2px; font-weight:600; }
  #mcppane header { display:flex; align-items:baseline; gap:10px; flex-wrap:wrap; margin-bottom:12px; }
  #mcppane header small { color:var(--dim); font:11px ui-monospace, monospace; overflow-wrap:anywhere; }
  #mcppane header .grow { flex:1; }
  #mcppane button { background:transparent; color:var(--dim); border:1px solid var(--line);
    border-radius:6px; padding:3px 9px; cursor:pointer; font:12px/1.4 inherit; }
  #mcppane button:hover:not(:disabled) { color:var(--fg); border-color:var(--accent); }
  #mcppane button:disabled { opacity:.45; cursor:default; }
  #mcppane button.go { color:var(--accent); }
  #mcppane button.bad:hover { color:var(--bad); border-color:var(--bad); }
  #mcptable { width:100%; border-collapse:collapse; font-size:13px; }
  #mcptable th { text-align:left; color:var(--dim); font-weight:normal; font-size:11px;
    text-transform:uppercase; letter-spacing:.06em; border-bottom:1px solid var(--rule); padding:4px 8px 4px 0; }
  #mcptable td { border-bottom:1px solid var(--line); padding:6px 8px 6px 0; vertical-align:top; }
  #mcptable td.name { font-family:ui-monospace, monospace; color:var(--accent); overflow-wrap:anywhere; }
  #mcptable td.when { color:var(--dim); white-space:nowrap; }
  #mcptable td.cmd { font-family:ui-monospace, monospace; overflow-wrap:anywhere; color:var(--dim); }
  #mcptable td.acts { text-align:right; white-space:nowrap; }
  #mcptable td.acts button { margin-left:4px; padding:2px 7px; }
  #mcptable tr.off td.name, #mcptable tr.off td.when { color:var(--dim); text-decoration:line-through; }
  #mcptable td.state.ok { color:var(--ok); }
  #mcptable td.state.failed { color:var(--bad); }
  #mcptable td.token { color:var(--dim); font-family:ui-monospace, monospace; }
  #mcptable td.token.unset { color:var(--bad); }
  #mcpform .editing { color:var(--accent); font-size:12px; margin:0 0 8px; }
  #mcpform .editing:empty { display:none; }
  #mcpmsg { font-size:12px; min-height:1.2em; margin:0 0 10px; color:var(--dim); }
  #mcpmsg.bad { color:var(--bad); }
  #mcpform { border:1px solid var(--line); border-radius:8px; padding:12px; margin:14px 0; }
  #mcpform label { display:block; color:var(--dim); font-size:12px; margin-bottom:8px; }
  #mcpform input, #mcpform select { display:block; width:100%; margin-top:3px; background:var(--bg);
    color:var(--fg); border:1px solid var(--line); border-radius:6px; padding:5px 8px;
    font:13px/1.5 ui-monospace, monospace; }
  #mcpform input:focus, #mcpform select:focus { outline:1px solid var(--accent); }
  #mcpform .row { display:flex; gap:8px; margin-top:8px; }
  /* `#505`: the problems pane. One row per complaint, grouped by which loader said it. */
  #problems { display:block; width:100%; margin:0 0 8px; background:transparent; color:var(--dim);
    border:1px solid var(--line); border-radius:8px; padding:5px 0; cursor:pointer; }
  #problems:hover, #problems.on { color:var(--fg); border-color:var(--accent); }
  #problems.has { color:var(--warn); border-color:var(--warn); }
  main.problems #log, main.problems #stats, main.problems #status, main.problems #form,
  main.problems #thinkbar, main.problems #notice, main.problems #open { display:none; }
  #problemspane { display:none; flex:1; overflow-y:auto; padding:16px 20px; }
  main.problems #problemspane { display:block; }
  #problemspane h2 { font-size:15px; margin:0 0 2px; font-weight:600; }
  #problemspane header { display:flex; align-items:baseline; gap:10px; flex-wrap:wrap; margin-bottom:12px; }
  #problemspane header small { color:var(--dim); font:11px ui-monospace, monospace; overflow-wrap:anywhere; }
  #problemspane header .grow { flex:1; }
  #problemspane button { background:transparent; color:var(--dim); border:1px solid var(--line);
    border-radius:6px; padding:3px 9px; cursor:pointer; font:12px/1.4 inherit; }
  #problemspane button:hover { color:var(--fg); border-color:var(--accent); }
  #problemsmsg { font-size:12px; min-height:1.2em; margin:0 0 10px; color:var(--dim); }
  #problemsmsg.bad { color:var(--bad); }
  #problemstable { width:100%; border-collapse:collapse; font-size:13px; }
  #problemstable th { text-align:left; color:var(--dim); font-weight:normal; font-size:11px;
    text-transform:uppercase; letter-spacing:.06em; border-bottom:1px solid var(--rule); padding:4px 8px 4px 0; }
  #problemstable td { border-bottom:1px solid var(--line); padding:6px 8px 6px 0; vertical-align:top; }
  #problemstable td.kind { color:var(--warn); white-space:nowrap; font-family:ui-monospace, monospace; }
  #problemstable td.what { overflow-wrap:anywhere; }
  #problemstable td.path { color:var(--dim); font:11px ui-monospace, monospace; overflow-wrap:anywhere; }
  #problemstable td.none { color:var(--ok); }
  #problemschecked { color:var(--dim); font:11px ui-monospace, monospace; white-space:pre-wrap;
    margin-top:14px; overflow-wrap:anywhere; }
  /* `#509`: the Bots tab. The same pane shape as cron and mcp — a header, one message line, a
     table — because a bot row answers the same three questions a job row does: what is it, where
     does it live, when did it last do something. */
  main.bots #log, main.bots #stats, main.bots #status, main.bots #form,
  main.bots #thinkbar, main.bots #notice, main.bots #open { display:none; }
  #botspane { display:none; flex:1; overflow-y:auto; padding:16px 20px; }
  main.bots #botspane { display:block; }
  #botspane h2 { font-size:15px; margin:0 0 2px; font-weight:600; }
  #botspane header { display:flex; align-items:baseline; gap:10px; flex-wrap:wrap; margin-bottom:12px; }
  #botspane header small { color:var(--dim); font:11px ui-monospace, monospace; overflow-wrap:anywhere; }
  #botspane header .grow { flex:1; }
  #botspane button { background:transparent; color:var(--dim); border:1px solid var(--line);
    border-radius:4px; padding:3px 9px; cursor:pointer; font-size:11px; font-family:inherit; }
  #botspane button:hover:not(:disabled) { color:var(--fg); border-color:var(--accent); }
  #botspane button.go { color:var(--accent); }
  #botspane button.bad:hover { color:var(--bad); border-color:var(--bad); }
  #botstable { width:100%; border-collapse:collapse; font-size:12px; }
  #botstable th { text-align:left; color:var(--dim); font-weight:600; font-size:10px;
    text-transform:uppercase; letter-spacing:.06em; border-bottom:1px solid var(--rule); padding:4px 8px 4px 0; }
  #botstable td { border-bottom:1px solid var(--line); padding:6px 8px 6px 0; vertical-align:top; }
  #botstable td.name { color:var(--fg); font-weight:600; white-space:nowrap; }
  #botstable td.acts { white-space:nowrap; text-align:right; }
  #botstable td.acts button { margin-left:4px; }
  #botsmsg { color:var(--dim); font-size:12px; min-height:16px; margin-bottom:8px; }
  #botsmsg.bad { color:var(--bad); }
  #botsprompt { margin-top:16px; border-top:1px solid var(--rule); padding-top:12px; }
  #botsprompt h3 { font-size:12px; margin:0 0 6px; color:var(--dim); font-weight:600; }
  #botsprompt pre { white-space:pre-wrap; overflow-wrap:anywhere; font:11px/1.5 ui-monospace, monospace;
    color:var(--fg); background:var(--panel); border:1px solid var(--line); border-radius:4px; padding:10px; }
  /* `#171`: the Flares tab. The Bots pane's shape again — a header, one message line, a table —
     because a run row answers the same questions a job row does: what was asked, how far it got,
     what it cost. A run expands *in place*: its children are a row of this same table, so the run
     stays in view while you read them. The pane is spliced into the page only when the ledger
     holds a run, so `main.flares` is never toggled on a page that has no pane. */
  main.flares #log, main.flares #stats, main.flares #status, main.flares #form,
  main.flares #thinkbar, main.flares #notice, main.flares #open { display:none; }
  #flarespane { display:none; flex:1; overflow-y:auto; padding:16px 20px; }
  main.flares #flarespane { display:block; }
  #flarespane h2 { font-size:15px; margin:0 0 2px; font-weight:600; }
  #flarespane header { display:flex; align-items:baseline; gap:10px; flex-wrap:wrap; margin-bottom:12px; }
  #flarespane header small { color:var(--dim); font:11px ui-monospace, monospace; }
  #flarespane header .grow { flex:1; }
  #flarespane button { background:transparent; color:var(--dim); border:1px solid var(--line);
    border-radius:4px; padding:3px 9px; cursor:pointer; font-size:11px; font-family:inherit; }
  #flarespane button:hover:not(:disabled) { color:var(--fg); border-color:var(--accent); }
  #flarespane button:disabled { opacity:.5; cursor:default; }
  #flarespane button.go { color:var(--accent); }
  #flarespane button.bad:hover { color:var(--bad); border-color:var(--bad); }
  #flaresmsg { color:var(--dim); font-size:12px; min-height:16px; margin-bottom:8px; }
  #flaresmsg.bad { color:var(--bad); }
  #flaretable { width:100%; border-collapse:collapse; font-size:12px; }
  #flaretable th { text-align:left; color:var(--dim); font-weight:600; font-size:10px;
    text-transform:uppercase; letter-spacing:.06em; border-bottom:1px solid var(--rule); padding:4px 8px 4px 0; }
  #flaretable td { border-bottom:1px solid var(--line); padding:6px 8px 6px 0; vertical-align:top; }
  #flaretable td.run { color:var(--fg); font-family:ui-monospace, monospace; white-space:nowrap; }
  #flaretable td.run .task { display:block; color:var(--dim); font-family:inherit; font-weight:normal;
    font-size:11px; max-width:46ch; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
  #flaretable td.state { white-space:nowrap; font-family:ui-monospace, monospace; }
  #flaretable td.state.done { color:var(--ok); }
  #flaretable td.state.running { color:var(--accent); }
  #flaretable td.state.failed, #flaretable td.state.cancelled { color:var(--warn); }
  #flaretable td.age, #flaretable td.jobs { white-space:nowrap; color:var(--dim); }
  #flaretable td.routes { color:var(--dim); font-family:ui-monospace, monospace; font-size:11px;
    overflow-wrap:anywhere; }
  #flaretable td.cost { color:var(--dim); font-family:ui-monospace, monospace; font-size:11px;
    white-space:nowrap; }
  #flaretable td.acts { text-align:right; white-space:nowrap; }
  #flaretable td.acts button { margin-left:4px; }
  #flaretable tr.jobs td { background:var(--panel); padding:8px 8px 10px 18px; }
  #flaretable tr.jobs .job { display:flex; align-items:baseline; gap:8px; flex-wrap:wrap; padding:3px 0; }
  #flaretable tr.jobs .job .n { width:2.5ch; color:var(--faint); font-family:ui-monospace, monospace; }
  #flaretable tr.jobs .job .state { font-family:ui-monospace, monospace; }
  #flaretable tr.jobs .job .state.done { color:var(--ok); }
  #flaretable tr.jobs .job .state.running { color:var(--accent); }
  #flaretable tr.jobs .job .state.failed { color:var(--bad); }
  #flaretable tr.jobs .job .state.dropped { color:var(--warn); }
  #flaretable tr.jobs .job .route { color:var(--dim); font-family:ui-monospace, monospace; font-size:11px; }
  #flaretable tr.jobs .job small { color:var(--dim); font:11px ui-monospace, monospace; }
  #flaretable tr.jobs .job small.why { color:var(--warn); overflow-wrap:anywhere; }
  #flaretable tr.jobs .empty { color:var(--dim); font-size:12px; }
</style>
</head>
<body>
<aside>
  <!-- The same three things the terminal's header line carries: the mark, the word, the version.
       `aria-hidden` on the picture, because the accessible name is the word beside it — a screen
       reader should not be read a picture. The model moved out of here into the stats row, where
       the rest of "what is this doing" lives (#238). -->
  <h1><img id="mark" src="/logo.svg" alt="" aria-hidden="true" width="22" height="22">eclipse
    <small class="version">v{{VERSION}}</small></h1>
  <button id="new">+ New session</button>
  <input id="find" type="search" placeholder="find in transcripts…" autocomplete="off"
         aria-label="search the transcripts">
  <div id="findinfo"></div>
  <!-- `#240`: the archive filter. Off is the list a person reads; on is the same list with the
       filed-away rows back in it, under their own heading and marked. The server answers both
       forms from one store call, so this is a filter and not a second ordering rule. -->
  <label id="archtoggle" title="sessions filed away: out of the list, still in the find box">
    <input id="showarchived" type="checkbox"> show archived
  </label>
  <ul id="sessions">{{SESSIONS}}</ul>
  <!-- `#509`: the Bots tab. The server writes this line only when `[bots]` declared something, so
       a config with no bots renders exactly the sidebar it rendered before there were bots. -->
  {{BOTS_BUTTON}}
  <!-- `#171`: the Flares tab, written the same way — the server puts this line in only when the
       run ledger holds a run, so somebody who has never fanned one out sees no button. -->
  {{FLARES_BUTTON}}
  <button id="settings" type="button" aria-expanded="false"
          title="every key this build reads, as the file says it">settings</button>
  <!-- The settings window (#267): a dialog rather than a sidebar box. Every row it draws — the
       type that picks the control, the words beside it, the choices a closed set offers — arrives
       from `GET /api/settings`; this file names no key and no legal value. -->
  <dialog id="settingswindow" aria-label="settings">
    <header>
      <h2>settings</h2>
      <small id="setpath"></small>
      <span class="grow"></span>
      <input id="setfind" type="search" placeholder="filter keys and their descriptions…"
             autocomplete="off" aria-label="filter the settings">
      <button type="button" id="setclose" aria-label="close settings">&times;</button>
    </header>
    <div id="setbody">
      <nav id="setsections" aria-label="sections"></nav>
      <div id="setrows"></div>
    </div>
    <div id="setnote"></div>
  </dialog>
  <button id="cron" type="button" aria-expanded="false"
          title="the jobs the timer runs — the same ones `eclipse cron` shows">scheduled jobs</button>
  <button id="mcp" type="button" aria-expanded="false"
          title="the MCP servers — the same ones `eclipse mcp list` shows">mcp servers</button>
  <button id="problems" type="button" aria-expanded="false"
          title="what the loaders complained about — the same warnings the CLI prints">problems</button>
  <form id="logout"><button type="submit">Sign out</button></form>
</aside>
<main>
  <div id="thinkbar" hidden>
    <button id="thinkall" type="button" title="every reasoning block in this transcript">expand all thinking</button>
  </div>
  <div id="notice" hidden>
    <button id="updatebadge" type="button" aria-expanded="false" aria-controls="updatepop"
            title="this install is behind the newest release — click for the two commands">
      <span id="updatetext"></span>
    </button>
    <div id="updatepop" hidden role="dialog" aria-label="how to update">
      <p><strong>Update available.</strong></p>
      <code>eclipse upgrade</code>
      <code>eclipse gateway restart</code>
      <p class="why">In that order: the upgrade installs the new build, and the restart is what
      makes this dashboard run it. A restart alone upgrades nothing; an upgrade alone leaves the
      process you are reading this in on the old binary.</p>
    </div>
  </div>
  <div id="open" hidden><span id="openname"></span><small id="openid"></small></div>
  {{BOTS_PANE}}
  {{FLARES_PANE}}
  <section id="cronpane" hidden aria-label="scheduled jobs">
    <header>
      <h2>scheduled jobs</h2>
      <small id="cronfile"></small>
      <span class="grow"></span>
      <button id="cronnew" type="button">+ new job</button>
      <button id="cronrefresh" type="button">refresh</button>
    </header>
    <div id="cronmsg"></div>
    <table id="crontable">
      <thead><tr><th>job</th><th>schedule</th><th>next</th><th>last</th><th></th></tr></thead>
      <tbody id="cronrows"></tbody>
    </table>
    <form id="cronform" hidden>
      <label>name
        <input id="cr-name" autocomplete="off" spellcheck="false" placeholder="brief">
      </label>
      <label>schedule
        <input id="cr-schedule" autocomplete="off" spellcheck="false"
               placeholder="every 30m · hourly · daily 07:30 · weekly mon 09:00">
      </label>
      <label>prompt
        <textarea id="cr-prompt" rows="3" placeholder="what to ask when it fires"></textarea>
      </label>
      <label>workdir (optional)
        <input id="cr-workdir" autocomplete="off" spellcheck="false" placeholder="~/notes">
      </label>
      <div class="row">
        <button type="submit" class="go" id="cronsave">save</button>
        <button type="button" id="croncancel">cancel</button>
        <span id="cronediting"></span>
      </div>
    </form>
    <div id="cronlogs" hidden></div>
  </section>
  <section id="problemspane" hidden aria-label="problems">
    <header>
      <h2>problems</h2>
      <small id="problemssummary"></small>
      <span class="grow"></span>
      <button id="problemsrefresh" type="button">refresh</button>
    </header>
    <div id="problemsmsg"></div>
    <table id="problemstable">
      <thead><tr><th>from</th><th>what</th><th>where</th></tr></thead>
      <tbody id="problemsrows"></tbody>
    </table>
    <div id="problemschecked"></div>
  </section>
  <section id="mcppane" hidden aria-label="mcp servers">
    <header>
      <h2>mcp servers</h2>
      <small id="mcpfile"></small>
      <span class="grow"></span>
      <button id="mcpnew" type="button">+ add server</button>
      <button id="mcprefresh" type="button">refresh</button>
    </header>
    <div id="mcpmsg"></div>
    <table id="mcptable">
      <thead><tr><th>name</th><th>source</th><th>tools</th><th>command</th><th>token</th><th>state</th><th></th></tr></thead>
      <tbody id="mcprows"></tbody>
    </table>
    <form id="mcpform" hidden>
      <div class="editing" id="mpediting"></div>
      <label>name
        <input id="mp-name" autocomplete="off" spellcheck="false" placeholder="fs">
      </label>
      <label>transport
        <select id="mp-transport">
          <option value="">auto — a url means http, a command means stdio</option>
          <option value="stdio">stdio — a process this build starts</option>
          <option value="http">http — an endpoint this build posts to</option>
        </select>
      </label>
      <label>url (http)
        <input id="mp-url" autocomplete="off" spellcheck="false"
               placeholder="http://127.0.0.1:18811/api/mcp">
      </label>
      <label>command (stdio)
        <input id="mp-command" autocomplete="off" spellcheck="false" placeholder="npx">
      </label>
      <label>args (stdio, space-separated)
        <input id="mp-args" autocomplete="off" spellcheck="false"
               placeholder="-y @modelcontextprotocol/server-filesystem /srv/data">
      </label>
      <label>token_env (http — the <em>name</em> of a variable holding the token, never the token)
        <input id="mp-token" autocomplete="off" spellcheck="false" placeholder="HA_TOKEN">
      </label>
      <label>prefix (optional)
        <input id="mp-prefix" autocomplete="off" spellcheck="false" placeholder="fs_">
      </label>
      <label>policy
        <select id="mp-policy">
          <option value="">ask — approve every call (the default)</option>
          <option value="allow">allow — run without asking</option>
          <option value="deny">deny — never run</option>
        </select>
      </label>
      <div class="row">
        <button type="submit" class="go" id="mcpsave">save</button>
        <button type="button" id="mcpcancel">cancel</button>
      </div>
    </form>
  </section>
  <div id="log"></div>
  <div id="statsrow">
    <div id="stats" title="the same numbers the CLI prints above its prompt">ctx -- · first -- · wall -- · ↑-- t/s · ⚡--</div>
    <!-- The effort the next turn carries, on the same row for the same reason as the model (#264):
         a session can be running a level nobody chose in the file, and that was invisible here.
         The title carries the sentence `/reasoning` prints — the long form does not fit a row. -->
    <!-- `#285`: approvals off is a mode this dashboard is *in*, so it is a word on the same row as
         the effort, in the alert colour, and it is on screen before the first card it does not
         show. The server owns it: a reload shows what is really in force. -->
    <span id="yolo" {{YOLO_ATTR}} title="{{YOLO_DETAIL}}">yolo</span>
    <!-- `#340`: the aux route decides `ask`-policy calls in `smart` mode, so some run without a
         card. Same row, same rule as `yolo`: a mode that decides without asking says so. -->
    <span id="judge" {{JUDGE_ATTR}} title="`[cli] approval = &quot;smart&quot;`: a cheap model rules allow, deny or escalate on each call that would have been a card, and only escalate asks you">judged</span>
    <!-- `#339`: the pane follows the run only while the reader is following it. This is the way
         back down when they are not, and it says how much is waiting there. It sits in this row
         (already `position:relative`) for the same reason the model menu does. -->
    <button id="jump" type="button" hidden title="the newest line — this pane stops following when you scroll up"></button>
    <span id="effort" class="{{EFFORT_CLASS}}" data-label="{{EFFORT}}" title="{{EFFORT_DETAIL}}">effort {{EFFORT}}</span>
    <!-- The model is the most-changed setting in the app, so it sits in the row that already
         answers "what is this doing", not under the wordmark styled as a footnote (#238). -->
    <button id="model" type="button" aria-expanded="false" aria-haspopup="menu" aria-controls="models"
            title="the model the next turn uses — click to switch">{{MODEL}}</button>
    <div id="models" hidden role="menu" aria-label="model">
      <div id="modellist"></div>
      <div id="modelsub" hidden></div>
      <div id="modelnote"></div>
    </div>
  </div>
  <div id="status">{{STATUS}}</div>
  <form id="form" data-paste-limit="{{PASTE_LIMIT}}">
    <!-- A textarea cannot carry an inline chip, so a big paste stands aside in a row of its own:
         one removable element per paste, saying what it is and how much of it there is (#220). -->
    <div id="pastes" hidden></div>
    <!-- What the `+` menu attached (#239): one removable chip per item, saying what it is and how
         much of it there is. The chips are the request: nothing is read behind the model's back. -->
    <div id="attached" hidden></div>
    <div id="composer">
      <!-- The `/` menu (#282): rows are the server's commands, so nothing here names one. -->
      <div id="cmdmenu" role="listbox" aria-label="Commands" hidden></div>
      <!-- The `+` menu (#239). Three rows do something; `image` and `audio` are disabled and say in
           the row what has to land first, because a picture that arrives as a filename is a lie
           the model then answers around. -->
      <button id="plus" type="button" aria-haspopup="menu" aria-expanded="false"
              aria-label="Attach a file, a path or a link" title="attach: file, path or link">+</button>
      <div id="attachmenu" role="menu" aria-label="Attach" hidden>
        <button type="button" role="menuitem" data-attach="file"><b>file…</b><span>read here, sent with the turn</span></button>
        <button type="button" role="menuitem" data-attach="path"><b>path…</b><span>a file on this machine: the agent reads it</span></button>
        <button type="button" role="menuitem" data-attach="url"><b>link…</b><span>a page: the agent fetches it</span></button>
        <button type="button" role="menuitem" data-attach="image"
                title="a picture, read here and sent with the turn"><b>image…</b><span>a picture: read here, sent with the turn</span></button>
        <button type="button" role="menuitem" data-attach="audio" disabled
                title="there is no transcription endpoint yet"><b>audio</b><span>needs a transcription endpoint</span></button>
      </div>
      <input id="attachfile" type="file" hidden>
      <input id="attachpicture" type="file" accept="image/png,image/jpeg,image/webp,image/gif" hidden>
      <textarea id="input" rows="2" placeholder="Message (Enter to send, Shift+Enter for newline)" autofocus></textarea>
      <button class="go" id="go" type="button" data-state="idle" aria-label="Send">Send</button>
    </div>
  </form>
</main>
<script>
(() => {
  // Anything that changes something carries the session's CSRF token. The guard accepts a browser
  // that will not name its origin — an embedded pane reports `Origin: null` — only when the request
  // proves it read this page, and this token is that proof. It is in the page, not in the cookie,
  // so a page on another site cannot produce it.
  const CSRF = (document.querySelector('meta[name=csrf]') || {}).content || '';
  const post = (url, body) => fetch(url, {
    method: 'POST',
    headers: body === undefined
      ? { 'X-Eclipse-CSRF': CSRF }
      : { 'X-Eclipse-CSRF': CSRF, 'content-type': 'application/json' },
    body: body === undefined ? undefined : JSON.stringify(body),
  });
  const log = document.getElementById('log');
  const input = document.getElementById('input');
  const cmdmenu = document.getElementById('cmdmenu');
  const go = document.getElementById('go');
  const status = document.getElementById('status');
  const list = document.getElementById('sessions');
  const showarchived = document.getElementById('showarchived');
  const openbar = document.getElementById('open');
  const openname = document.getElementById('openname');
  const openid = document.getElementById('openid');

  const stats = document.getElementById('stats');
  // The switch `#285` added. A mode this dashboard is in has to be on screen while it is in
  // force, which is the whole reason the terminal had a word on its bar and the browser did not.
  const yoloChip = document.getElementById('yolo');
  function paintYolo(on) { yoloChip.hidden = !on; }
  // What the process knows before a turn has run (#264). The context text comes from the same
  // `eclipse_core::contextbar` reading the CLI prints — the page does no arithmetic of its own, so
  // a reload shows the window and the tripwire instead of dropping to `ctx --`.
  //
  // `#401`: the level and its sentence are read from the element that already shows them, never
  // interpolated into this script. An HTML-escaped value inside a JS string printed `&#39;` in the
  // fallback tooltip, and one ending in a backslash made the string unterminated — a page that did
  // not run at all.
  const effortEl = document.getElementById('effort');
  const EFFORT0 = effortEl.dataset.label;
  const EFFORT_DETAIL0 = effortEl.title;
  // The level as last reported, so the picker's head row can name it without parsing the row.
  let effortLabel = EFFORT0;
  let sessionId = null;
  let runId = null;   // id of the chat run in flight; the one control cancels it
  // Every session row the page holds, in the store's order — including the ones a closed section
  // has taken out of the DOM (#345). Three readers need a row the list may not be showing
  // (`markActive`, `showOpen`, `costOf`), and a row that is off screen is still a place: finding
  // rows by walking `list.children` would make "where am I" unanswerable the moment its section is
  // collapsed, and would lose the open session's numbers with it.
  let master = [];

  // One control, three states (#236). `starting` is the gap between the press and the run's id
  // arriving with the `session` event: it says what is happening rather than swallowing the press,
  // which is what the old second button did while it was enabled with nothing to cancel.
  function setGo(state) {
    go.dataset.state = state;
    go.classList.toggle('stop', state === 'stop');
    go.textContent = state === 'idle' ? 'Send' : state === 'starting' ? 'Starting…' : 'Stop';
    go.setAttribute('aria-label',
      state === 'idle' ? 'Send'
        : state === 'starting' ? 'Starting — nothing to stop yet'
        : 'Stop the run in flight');
    go.disabled = state === 'starting';
  }
  let busy = false;
  let live = null; // assistant bubble currently being filled by `delta` events
  let deferredLine = null; // a `/` line whose echo waits for the server's answer (#254)
  let thinking = null; // reasoning block currently being filled by `reasoning` events
  let composing = null; // tool block whose arguments are still arriving

  // A streamed block ends when the next kind of block starts: one bubble at a time, and a
  // finished reasoning block never collects the reply that follows it.
  function endBlocks() {
    thinking = null;
    composing = null;
    live = null;
  }

  // Who owns the scroll (#339). The pane followed the run unconditionally — nine call sites each
  // ended with `log.scrollTop = log.scrollHeight` — so reading anything older than the newest token
  // was impossible: every delta snapped the reader back. The intent was right (a page that never
  // scrolls leaves the newest word off-screen); what was missing is the reader's own intent.
  //
  // `pinned` is that intent, and it is only ever written by the pane's scroll event and by us. A
  // scroll the reader makes sets it; the scroll our own `pin()` makes sets it too, which is why the
  // two cannot drift. Nothing else in the page may assign `log.scrollTop` — see
  // `only_the_pane_decides_where_the_pane_is` in `app.rs`, which fails if a tenth call site appears.
  const JUMP_SLACK = 24;   // px from the bottom that still counts as following along
  const jump = document.getElementById('jump');
  // The cards on screen, by id (#339 reads its size to say how many are waiting there).
  const pendingApprovals = new Map();
  const outcomes = { approved: 'Approved', denied: 'Denied', timeout: 'No answer: declined', cancelled: 'Cancelled' };
  let pinned = true;       // the reader is at the bottom, and wants to be carried along
  let unseen = 0;          // events that landed while they were not

  function atBottom() {
    // A pane shorter than its content is at the bottom by definition, or a new session's first line
    // would read as "the reader has scrolled away" and nothing would ever follow.
    return log.scrollHeight - log.scrollTop - log.clientHeight <= JUMP_SLACK;
  }

  function pin() {
    log.scrollTop = log.scrollHeight;
    unseen = 0;
  }

  // What the button says, from state rather than from a counter that could drift: the approval
  // count is the map the page already keeps, so it cannot disagree with the cards on screen.
  function paintJump() {
    const away = !atBottom();
    jump.hidden = !away;
    if (!away) return;
    const cards = pendingApprovals.size;
    jump.classList.toggle('card', cards > 0);
    jump.textContent = cards > 0
      ? '↓ ' + cards + (cards === 1 ? ' approval' : ' approvals')
      : unseen > 0 ? '↓ ' + unseen + ' newer' : '↓ bottom';
  }

  // Called once after anything that made the transcript taller. One rule, one place.
  function follow() {
    if (pinned) pin();
    else unseen += 1;
    paintJump();
  }

  log.addEventListener('scroll', () => {
    pinned = atBottom();
    if (pinned) unseen = 0;
    paintJump();
  }, { passive: true });

  jump.addEventListener('click', () => {
    pinned = true;
    pin();
    paintJump();
    input.focus();
  });

  function add(kind, text) {
    const el = document.createElement('div');
    el.className = 'msg ' + kind;
    el.textContent = text;
    log.appendChild(el);
    follow();
    return el;
  }

  // A pasted wall of text is a wall in the transcript too (#220). The bubble stays a `details` when
  // the message would otherwise take the page — same rule as the composer's chip, same threshold,
  // because "big" must not mean two things on one screen. It is folded, not truncated: the text is
  // there, one click away, and the summary says how much of it.
  const PASTE_FOLD_LINES = 6;

  function userMessage(text) {
    const lines = text.replace(/\n+$/, '').split('\n').length;
    const chars = Array.from(text).length;
    if (lines <= PASTE_FOLD_LINES && chars <= PASTE_LIMIT) return add('user', text);
    const d = document.createElement('details');
    d.className = 'msg user big';
    const sum = document.createElement('summary');
    sum.textContent = lines + ' lines · ' + chars + ' chars — click to read';
    const body = document.createElement('div');
    body.className = 'pasted';
    body.textContent = text;
    d.appendChild(sum);
    d.appendChild(body);
    log.appendChild(d);
    follow();
    return d;
  }

  // Reasoning is folded wherever it arrives — while it streams and again when a stored session is
  // replayed — because a reload that unfolded it would make the fold a thing you lose. The
  // summary carries the count so a collapsed block still says how much is inside it.
  const thinkBar = document.getElementById('thinkbar');
  const thinkAll = document.getElementById('thinkall');

  function thinkingBlocks() {
    return Array.from(log.querySelectorAll('details.reasoning'));
  }

  function noteThinking() {
    thinkBar.hidden = thinkingBlocks().length === 0;
  }

  // Emptying the transcript also hides the control that acts on it.
  function clearLog() {
    log.textContent = '';
    noteThinking();
    // An empty pane is one the reader is at the bottom of, whatever they were reading before.
    pinned = true;
    pin();
    paintJump();
  }

  function thinkingHeader(body) {
    const text = body.textContent;
    const n = text ? text.split('\n').length : 0;
    body.parentElement.querySelector('summary').textContent =
      '💭 Thinking · ' + n + (n === 1 ? ' line' : ' lines');
  }

  function addThinking(text) {
    const el = document.createElement('details');
    el.className = 'msg reasoning';
    const summary = document.createElement('summary');
    const body = document.createElement('div');
    body.className = 'think';
    body.textContent = text || '';
    el.append(summary, body);
    log.appendChild(el);
    thinkingHeader(body);
    noteThinking();
    follow();
    return body;
  }

  // A tool call is one line: what it was, against what. The arguments are the page of JSON the
  // reader did not ask for, so they sit behind the row. The statement is built on the server
  // (`eclipse_web::calls`) where it can be tested; a page that had to guess at `tool_calls`
  // would be the only implementation of that rule.
  // The mark says how the call went, with the same four glyphs the terminal uses: `⏺` while it is
  // running, `✓` when it worked, `⊘` when someone declined it, `✗` when it broke. The state comes
  // from the server (`calls::outcome`), never from the page reading the result text.
  const GLYPH = { running: '⏺', ok: '✓', refused: '⊘', failed: '✗' };

  function addCall(name, args, summary, state, callId) {
    const el = document.createElement('details');
    el.className = 'msg tool call';
    el.dataset.name = name;
    if (callId) el.dataset.call = callId;
    const line = document.createElement('summary');
    const mark = document.createElement('span');
    mark.className = 'mark';
    line.append(mark, document.createTextNode('→ ' + (summary || (name + '(' + args + ')'))));
    const body = document.createElement('pre');
    body.className = 'args';
    body.textContent = args;
    el.append(line, body);
    callState(el, state || 'running');
    log.appendChild(el);
    follow();
    return el;
  }

  function callState(el, state) {
    for (const known of Object.keys(GLYPH)) el.classList.remove(known);
    el.classList.add(GLYPH[state] ? state : 'ok');
    const mark = el.querySelector('summary .mark');
    if (mark) mark.textContent = GLYPH[state] || GLYPH.ok;
  }

  // The output belongs to the call, behind its row — the dashboard's stand-in for the tool log the
  // terminal writes. Never a block of its own in the conversation.
  function attachOutput(el, text) {
    if (!el || text == null) return;
    let out = el.querySelector('.out');
    if (!out) {
      const cap = document.createElement('div');
      cap.className = 'cap';
      cap.textContent = 'output';
      out = document.createElement('pre');
      out.className = 'out';
      el.append(cap, out);
    }
    out.textContent = text;
  }

  // The result names the call it answers, so it goes on *that* row. Two `read_file` calls in one
  // turn used to pair by "the newest row with this name still running", which is the wrong row —
  // and replay pairs by id, so the same transcript changed shape after a reload.
  function callRow(id, name) {
    if (id) {
      const exact = Array.from(log.querySelectorAll('details.tool')).find(el => el.dataset.call === id);
      if (exact) return exact;
    }
    // A result whose call this tab never saw (a resumed run) still lands somewhere sensible: the
    // oldest row with that name that has no output yet.
    const rows = Array.from(log.querySelectorAll('details.tool'));
    return rows.find(el => el.dataset.name === name && !el.querySelector('.out')) || null;
  }

  // One control for the whole transcript: expanding eleven blocks one at a time to read a run is
  // the kind of work a fold should not add. It expands when anything is still closed, and only
  // then does its label say "collapse".
  thinkAll.addEventListener('click', () => {
    const blocks = thinkingBlocks();
    const opening = blocks.some(d => !d.open);
    for (const d of blocks) d.open = opening;
    thinkAll.textContent = opening ? 'collapse all thinking' : 'expand all thinking';
  });

  // The status line above the CLI's prompt, in the browser: the same K/M suffixes, the same
  // second/minute spellings, and `--` for anything the server did not report. A number that
  // never arrived is never drawn as a zero.
  const UNKNOWN = '--';

  function tokens(n) {
    if (typeof n !== 'number' || !isFinite(n) || n < 0) return UNKNOWN;
    if (n < 1e3) return String(Math.round(n));
    if (n < 1e6) { const v = n / 1e3; return (v < 100 ? v.toFixed(1) : v.toFixed(0)) + 'K'; }
    const v = n / 1e6;
    return (v < 100 ? v.toFixed(1) : v.toFixed(0)) + 'M';
  }

  function duration(ms) {
    if (typeof ms !== 'number' || !isFinite(ms) || ms <= 0) return UNKNOWN;
    if (ms < 1e4) return (ms / 1e3).toFixed(1) + 's';
    if (ms < 6e4) return (ms / 1e3).toFixed(0) + 's';
    if (ms < 3.6e6) {
      const s = Math.floor(ms / 1e3);
      return Math.floor(s / 60) + 'm' + String(s % 60).padStart(2, '0') + 's';
    }
    const m = Math.floor(ms / 6e4);
    return Math.floor(m / 60) + 'h' + String(m % 60).padStart(2, '0') + 'm';
  }

  function statsLine(d) {
    // The context field is the server's, character for character: `eclipse_core::contextbar`
    // builds `ctx 12.3K/328K ██░░░░░░│░░ 4%` and the CLI prints the same call's answer, so the two
    // surfaces cannot disagree about a denominator or a percentage (#264).
    //
    // There is no page-load fallback any more (#344). The row used to fall back to a window baked
    // into the HTML when the page was served, which is a fact about a model that may not be the
    // one that ran, printed as though it were the one about to run. Nothing is measured until a
    // turn finishes, so nothing is drawn: `ctx --` is the honest row.
    const ctx = d.ctx || 'ctx --';
    const cache = (typeof d.cached_tokens !== 'number')
      ? '⚡' + UNKNOWN
      : '⚡' + tokens(d.cached_tokens) +
        (d.prompt_tokens > 0
          ? ' (' + Math.round(d.cached_tokens / d.prompt_tokens * 100) + '%)' : '');
    const speed = (typeof d.tokens_per_sec === 'number' && isFinite(d.tokens_per_sec))
      ? d.tokens_per_sec.toFixed(0) : UNKNOWN;
    return [
      ctx,
      'first ' + duration(d.ttft_ms),
      'wall ' + duration(d.latency_ms),
      '↑' + speed + ' t/s',
      cache,
    ].join(' · ');
  }

  function setEffort(label, detail, session) {
    effortLabel = label || EFFORT0;
    effortEl.textContent = 'effort ' + effortLabel;
    effortEl.title = detail || EFFORT_DETAIL0;
    effortEl.classList.toggle('session', !!session);
  }

  // What the row's title says while it is about now, beside the painters that write it. The markup
  // carries the same sentence; a reload shows it until a turn replaces it.
  const LIVE_TITLE = 'the same numbers the CLI prints above its prompt';

  // How long ago, for a row that is showing a turn nobody is watching (#344). Short, because it
  // rides on a line that is already dense, and `now` never prints — a live turn has no suffix.
  function ago(at) {
    if (!at) return '';
    const s = Math.max(0, Math.round((Date.now() - at) / 1000));
    if (s < 45) return 'just now';
    if (s < 5400) return Math.round(s / 60) + 'm ago';
    if (s < 172800) return Math.round(s / 3600) + 'h ago';
    return Math.round(s / 86400) + 'd ago';
  }

  // The row after a turn finished: `last 4m ago` says whose numbers these are. Without it a
  // denominator from a model you stopped using an hour ago reads as the one in force, which is
  // exactly the "wrong context size" the row was reported for.
  function paintCost(cost) {
    stats.classList.toggle('last', !!cost);
    stats.title = cost
      ? 'the last turn in this session, ' + ago(cost.at_ms) + ' — send a message for the current one'
      : LIVE_TITLE;
    stats.textContent = cost
      ? statsLine(cost) + ' · ' + ago(cost.at_ms)
      : statsLine({});
  }

  // The one row that is about now. Separate from `paintCost` because a live turn has no age to
  // name, and `paintCost(null)` would have to mean two things.
  function paintLive(d) {
    stats.classList.remove('last');
    stats.title = LIVE_TITLE;
    stats.textContent = statsLine(d);
  }

  // What the store says this session's last turn cost, read off the row it was opened from. The
  // list carries it, so opening a session costs no request of its own.
  function costOf(id) {
    if (!id) return null;
    for (const li of master) {
      if (li.dataset.id !== id) continue;
      try { return li.dataset.cost ? JSON.parse(li.dataset.cost) : null; }
      catch (e) { return null; }
    }
    return null;
  }

  function clearStats() {
    // Only the turn's numbers are repainted, and they come from the store rather than from nothing:
    // the effort is a fact about the process, not about the last request, so opening another
    // session must not blank it (#264), and the numbers do not vanish because the pane changed
    // (#344).
    paintCost(costOf(sessionId));
  }

  // The row being read can be off screen — its section may be closed (#345) — so the mark has two
  // homes: the row when it is in the DOM, and the heading of the section holding it when it is not.
  // Without the second, closing `Today` while reading today's session leaves the sidebar with no
  // answer to "where am I".
  function markActive() {
    let parked = null;
    for (const li of master) {
      const mine = li.dataset.id === sessionId;
      li.classList.toggle('active', mine);
      if (mine && !li.isConnected) parked = li;
    }
    const here = parked ? sectionOf(parked) : null;
    for (const btn of list.querySelectorAll('.grouptoggle')) {
      btn.classList.toggle('here', here !== null && btn.dataset.section === here);
    }
    showOpen(parked);
  }

  // The name of the session being read, above its transcript: the sidebar scrolls away from the
  // row you clicked, and "which session am I in" is the question the header answers. It is read
  // off the row rather than fetched, so a rename and a name that lands a second after the first
  // turn both show up the next time the list is rebuilt.
  //
  // A pinned row's name carries its `★`, and anything that quotes the name back (this bar, the
  // rename prompt) drops it first: a mark is about the row's place in the list, not part of what a
  // person called the session. Archived rows carry no mark — the `Archived` heading says it, and
  // `⊘` already means "someone declined this tool call" in the transcript (#240).
  const MARKS = /^\u2605 /;
  function showOpen(parked) {
    const row = parked || master.find(li => li.dataset.id === sessionId);
    const name = row && row.querySelector('.name');
    openbar.hidden = !sessionId;
    openname.textContent = name ? name.textContent.replace(MARKS, '') : '';
    openid.textContent = sessionId || '';
  }

  // The session list is server-rendered so the sidebar paints with the page; from then on it is
  // rebuilt from `GET /api/sessions`, because a rename, a pin or a delete has to be visible
  // without reloading. Rows are built with createElement and textContent: a title is text a
  // person typed, and it is never markup.
  function labelOf(s) {
    const child = s.subagent ? '[subagent · ' + s.subagent.route + '] ' : '';
    return child + (s.title || s.preview || s.id);
  }

  function sessionRow(s) {
    const li = document.createElement('li');
    li.className = 'session';
    li.dataset.id = s.id;
    // When it last moved, for the date sections. A session a run just created has not been read
    // back from the API yet, so it is now — which is the truth, and puts it under Today.
    li.dataset.updated = String(s.updated_ms || Date.now());
    li.dataset.pinned = s.pinned ? '1' : '0';
    // Only the `show archived` filter ever returns one of these (#240).
    li.dataset.archived = s.archived ? '1' : '0';
    // The last turn's numbers travel with the row (#344), so opening it paints without a fetch and
    // the sidebar and the stats row cannot describe the same session differently.
    li.dataset.cost = s.cost ? JSON.stringify(s.cost) : '';
    const name = document.createElement('div');
    name.className = 'name';
    name.textContent = (s.pinned ? '★ ' : '') + labelOf(s);

    // One control per row. The menu is in the DOM whether it is open or not, because a control
    // built on hover is a control the keyboard cannot reach; `data-act` is what the click handler
    // dispatches on, so this changes the surface and not the behaviour.
    const dots = document.createElement('button');
    dots.type = 'button';
    dots.className = 'dots';
    dots.textContent = '⋮';
    dots.title = 'pin, archive, rename, copy or delete this session';
    dots.setAttribute('aria-haspopup', 'menu');
    dots.setAttribute('aria-expanded', 'false');
    const menu = document.createElement('div');
    menu.className = 'menu';
    menu.hidden = true;
    menu.setAttribute('role', 'menu');
    const item = (act, text, title, cls) => {
      const b = document.createElement('button');
      b.type = 'button';
      b.dataset.act = act;
      b.setAttribute('role', 'menuitem');
      b.textContent = text;
      b.title = title;
      if (cls) b.className = cls;
      menu.appendChild(b);
    };
    item(s.pinned ? 'unpin' : 'pin', s.pinned ? 'unpin' : 'pin',
      s.pinned ? 'let a prune take this session again'
               : 'keep this session first, and out of reach of every prune');
    // Filed away, not deleted (#240): the menu says so, because the two sit three rows apart and
    // only one of them is irreversible.
    item(s.archived ? 'unarchive' : 'archive', s.archived ? 'unarchive' : 'archive',
      s.archived ? 'put this session back in the list'
                 : 'file this session away — out of the list, still in the find box');
    item('rename', 'rename', 'give this session a title');
    item('copy', 'copy id', 'copy the id to the clipboard');
    item('delete', 'delete', 'delete the transcript, its title and its memory', 'danger');
    li.append(name, dots, menu);
    return li;
  }

  // One open menu at a time, and a way back to the button that opened it: Escape closes and
  // returns focus, so a keyboard user is never left with a popup they cannot leave.
  function closeMenus(except) {
    for (const menu of list.querySelectorAll('.menu')) {
      if (menu === except) continue;
      menu.hidden = true;
      const dots = menu.parentElement.querySelector('.dots');
      if (dots) dots.setAttribute('aria-expanded', 'false');
    }
  }

  function toggleMenu(menu, dots, force) {
    const open = force === undefined ? menu.hidden : force;
    closeMenus(open ? menu : null);
    menu.hidden = !open;
    dots.setAttribute('aria-expanded', String(open));
    if (open) {
      const first = menu.querySelector('button');
      if (first) first.focus();
    } else {
      dots.focus();
    }
  }

  // When a session happened is the reader's midnight, not the gateway's: the browser and the
  // server are the same machine here, but the person reading may not be on it, and "Today" is a
  // fact about their clock. The server says when (`data-updated`), the page says which section.
  const DAY = 86400000;
  const SECTIONS = ['Today', 'Yesterday', 'Last week', 'Last month', 'Older'];

  function section(updated, now) {
    if (!updated) return 'Older';
    const then = new Date(updated); then.setHours(0, 0, 0, 0);
    const today = new Date(now); today.setHours(0, 0, 0, 0);
    const days = Math.round((today - then) / DAY);
    if (days <= 0) return 'Today';
    if (days === 1) return 'Yesterday';
    if (days <= 7) return 'Last week';
    if (days <= 31) return 'Last month';
    return 'Older';
  }

  // Which heading a row belongs under: the same rule `groupList` partitions by, so the mark
  // `markActive` paints and the section its row vanished into cannot disagree.
  function sectionOf(li, now) {
    if (li.dataset.archived === '1') return 'Archived';
    if (li.dataset.pinned === '1') return 'Pinned';
    return section(Number(li.dataset.updated) || 0, now || Date.now());
  }

  // Closed sections (#345). The state lives outside the rebuild because `groupList` re-runs after
  // every refresh: a section that reopens itself on the next list refresh is worse than no toggle
  // at all. One key in `localStorage`, per browser, because a thing a person sets once should stay
  // set — the same reason the stats row remembers its position.
  const COLLAPSED_KEY = 'sessions.collapsed';
  function loadCollapsed() {
    try {
      const saved = JSON.parse(localStorage.getItem(COLLAPSED_KEY) || '[]');
      return new Set(Array.isArray(saved) ? saved.filter(n => typeof n === 'string') : []);
    } catch (e) { return new Set(); }
  }
  const collapsed = loadCollapsed();
  function saveCollapsed() {
    try { localStorage.setItem(COLLAPSED_KEY, JSON.stringify([...collapsed])); } catch (e) {}
  }

  // A heading is a control now, so it is a `button`: Enter and Space work without a keydown
  // handler, it is in the tab order, and `aria-expanded` is what tells a screen reader that the
  // rows under it changed. The count comes from the partition that produces the rows, so it cannot
  // drift from them — and on a closed section it is the only thing saying whether opening is worth
  // a click.
  function header(label, count) {
    const li = document.createElement('li');
    li.className = 'group';
    const btn = document.createElement('button');
    btn.type = 'button';
    btn.className = 'grouptoggle';
    btn.dataset.section = label;
    const shut = collapsed.has(label);
    btn.setAttribute('aria-expanded', String(!shut));
    btn.title = (shut ? 'open ' : 'close ') + label.toLowerCase();
    const chev = document.createElement('span');
    chev.className = 'chev';
    chev.textContent = shut ? '\u25b8' : '\u25be';
    const name = document.createElement('span');
    name.className = 'gname';
    name.textContent = label;
    const num = document.createElement('span');
    num.className = 'gcount';
    num.textContent = '\u00b7 ' + count;
    btn.append(chev, name, num);
    li.append(btn);
    return li;
  }

  // Rows are partitioned, never re-sorted: the ordering rule is the store's, shared with the
  // terminal, and a page that sorted by its own key would be a second rule. Pinned sessions come
  // out of the date buckets and go first — that is what a pin promises. Archived ones come out
  // too, and go last under their own heading: looking at the archive must not move a live row.
  //
  // A closed section's rows are not appended at all, so what the page holds and what it shows are
  // the same thing — and the rows that stay are the same elements, with their menus and their
  // listeners, ready to come back untouched.
  function groupList() {
    if (!master.length) return;
    const now = Date.now();
    const pinned = [];
    const archived = [];
    const buckets = new Map();
    for (const li of master) {
      const name = sectionOf(li, now);
      if (name === 'Archived') { archived.push(li); continue; }
      if (name === 'Pinned') { pinned.push(li); continue; }
      if (!buckets.has(name)) buckets.set(name, []);
      buckets.get(name).push(li);
    }
    const out = [];
    // An empty section is not a heading with nothing under it — but a closed one keeps its heading,
    // because that heading is the only way back to the rows it is holding.
    const add = (label, rows) => {
      if (!rows.length) return;
      out.push(header(label, rows.length));
      if (!collapsed.has(label)) out.push(...rows);
    };
    add('Pinned', pinned);
    for (const name of SECTIONS) add(name, buckets.get(name) || []);
    add('Archived', archived);
    list.replaceChildren(...out);
  }

  // One listener for every heading, present and future: they are rebuilt on every refresh, so a
  // listener per heading would be re-attached forever. `Pinned` and `Archived` close like the rest
  // — an exception is a rule someone has to remember.
  list.addEventListener('click', ev => {
    const btn = ev.target.closest('.grouptoggle');
    if (!btn) return;
    const label = btn.dataset.section;
    if (collapsed.has(label)) collapsed.delete(label); else collapsed.add(label);
    saveCollapsed();
    groupList();
    markActive();
  });

  async function refreshSessions() {
    // One store call on the server either way; `archived=1` is the same list with the filed-away
    // rows back in it (#240). Off is the default, so the request is the same shape it always was.
    const url = '/api/sessions' + (showarchived.checked ? '?archived=1' : '');
    let r;
    try { r = await fetch(url); }
    catch (e) { return; }
    if (r.status === 401) return location.reload();
    if (!r.ok) return;
    master = (await r.json()).map(sessionRow);
    groupList();
    markActive();
  }

  // The archive filter (#240): a checkbox because it filters and does nothing. Turning it on
  // re-asks the server for the same list plus the filed-away rows, so the rows on screen are the
  // store's rows in the store's order — and turning it off takes them away again. A find box with
  // a query up is showing hits, and its saved copy of the list is from before this change: it is
  // emptied first, so the filter cannot be undone by a stale restore.
  showarchived.addEventListener('change', () => { dropFind({ rebuild: false }); refreshSessions(); });

  // One write on one session. The five actions go through four routes on the server, each of
  // which calls the store function the terminal calls — so a rename here is the rename
  // `eclipse sessions rename` performs.
  async function sessionWrite(id, act, body) {
    const url = '/api/sessions/' + encodeURIComponent(id) + '/' + act;
    let r;
    try { r = await post(url, body); }
    catch (e) { status.textContent = String(e); return null; }
    if (r.status === 401) { location.reload(); return null; }
    const data = await r.json().catch(() => ({}));
    if (!r.ok) { status.textContent = data.error || ('HTTP ' + r.status); return null; }
    return data;
  }

  // A write changes what the list says, so the list is rebuilt from the store. The find box
  // holds hits, not sessions, so it is emptied first rather than restored from a stale clone
  // that still shows the old title.
  async function afterWrite() {
    if (find.value) dropFind({ rebuild: false });
    await refreshSessions();
  }

  async function loadSession(id) {
    if (busy) return;
    let r;
    try { r = await fetch('/api/sessions/' + encodeURIComponent(id)); }
    catch (e) { return add('error', String(e)); }
    if (r.status === 401) return location.reload();
    if (!r.ok) return add('error', 'Could not load session');
    // A stored transcript is the session view: the pane must not stay in front of it.
    setView('session');
    sessionId = id;
    clearLog();
    clearStats();
    // Oldest first, in the order a turn produced them: what the model thought, what it asked
    // for, what it said. The reasoning field is `reasoning_content` on the wire, and `calls`
    // carries the server's statement and verdict for each tool call in `tool_calls`, by index.
    //
    // A stored result is a message of its own, but it is not a block of its own: it is the answer
    // to the call above it, so it goes behind that row. A turn with three calls is three lines,
    // which is what the terminal prints and what this page is now matching.
    const byCall = new Map();
    for (const m of await r.json()) {
      if (m.reasoning_content) addThinking(m.reasoning_content);
      const calls = m.calls || [];
      (m.tool_calls || []).forEach((c, i) => {
        const info = calls[i] || {};
        byCall.set(c.id, addCall(c.function.name, c.function.arguments, info.summary, info.state));
      });
      if (m.role === 'tool') {
        attachOutput(byCall.get(m.tool_call_id), m.content);
        continue;
      }
      // `#346`: a picture the turn carried is shown with it, because the session has to be able to
      // explain what was sent — and the model's answer is about something the reader can see.
      const pictures = m.images || [];
      if (pictures.length) {
        const box = m.role === 'user' ? userMessage(m.content || '') : add(m.role, m.content || '');
        for (const picture of pictures) {
          const img = document.createElement('img');
          img.className = 'sent';
          img.src = picture.url;
          img.alt = picture.name || 'attached picture';
          img.title = (picture.name || 'picture') + ' (' + picture.mime + ')' +
            (picture.seen ? ' — described: ' + picture.seen : '');
          box.appendChild(img);
        }
      } else if (m.content) {
        if (m.role === 'user') userMessage(m.content);
        else add(m.role, m.content);
      }
    }
    // A stored session opens at its end. The replay appends through the same `add`/`addCall`, so it
    // followed along by itself while the pane fit; this is the one place that promises it either
    // way, because opening a session and landing halfway up it would look like a lost place.
    pinned = true;
    pin();
    paintJump();
    markActive();
  }

  list.addEventListener('click', async e => {
    const li = e.target.closest('li[data-id]');
    if (!li) return;
    const id = li.dataset.id;
    // The ⋮ opens the row's menu; it is not a request to open the session.
    const dots = e.target.closest('.dots');
    if (dots) {
      const menu = li.querySelector('.menu');
      if (menu) toggleMenu(menu, dots);
      return;
    }
    const btn = e.target.closest('button[data-act]');
    if (!btn) return loadSession(id);
    closeMenus();
    const act = btn.dataset.act;
    // Copy is the only one that changes nothing, so it needs no token and no reload.
    if (act === 'copy') {
      try { await navigator.clipboard.writeText(id); status.textContent = 'copied ' + id; }
      catch (err) { status.textContent = 'could not copy: ' + err; }
      return;
    }
    if (act === 'rename') {
      const shown = (li.querySelector('.name') || {}).textContent || '';
      const title = window.prompt('Title for this session', shown.replace(MARKS, ''));
      if (title === null) return;
      if (await sessionWrite(id, 'rename', { title })) {
        status.textContent = 'renamed ' + id;
        await afterWrite();
      }
      return;
    }
    if (act === 'pin' || act === 'unpin') {
      if (await sessionWrite(id, 'pin', { pinned: act === 'pin' })) {
        status.textContent = (act === 'pin' ? 'pinned ' : 'unpinned ') + id;
        await afterWrite();
      }
      return;
    }
    // Filed away, not deleted (#240): one column, and the row leaves the list unless the filter
    // is on — where it reappears under `Archived`, which is what tells the two apart.
    if (act === 'archive' || act === 'unarchive') {
      if (await sessionWrite(id, 'archive', { archived: act === 'archive' })) {
        status.textContent = (act === 'archive'
          ? 'archived ' + id + ' — still in the find box'
          : 'unarchived ' + id + ' — back in the list');
        await afterWrite();
      }
      return;
    }
    if (act === 'delete') {
      if (!window.confirm('Delete this session? Its transcript, title and memory go with it.')) return;
      if (await sessionWrite(id, 'delete')) {
        if (sessionId === id) { sessionId = null; clearLog(); clearStats(); }
        status.textContent = 'deleted ' + id;
        await afterWrite();
      }
    }
  });
  document.getElementById('new').addEventListener('click', () => {
    if (busy) return;
    setView('session');
    sessionId = null; clearLog(); markActive(); clearStats(); input.focus();
  });

  // The find box: `store.search` over every transcript, one row per matching message. While a
  // query is up the rows replace the session list — a hit is a place in a session, not a session,
  // so the row names the session and shows the line that matched. Clearing the box restores the
  // list exactly as it was, including a session started while the box had text.
  const find = document.getElementById('find');
  const findinfo = document.getElementById('findinfo');
  let findTimer = null;
  let findSeq = 0;

  // Clearing the box rebuilds the list from the store. It used to put back a clone taken before the
  // first query; a clone is copies of rows, so `master` would be pointing at elements the page no
  // longer holds and every closed section would be re-rendered against rows that are not there
  // (#345). One GET is the honest way back to the list a filter covered, and `rebuild: false` lets
  // a caller that is about to refresh anyway avoid asking twice.
  function dropFind(opts) {
    find.value = '';
    clearTimeout(findTimer);
    findinfo.textContent = '';
    if (!opts || opts.rebuild !== false) refreshSessions();
  }

  async function runFind() {
    const q = find.value.trim();
    if (!q) return dropFind();
    const mine = ++findSeq;
    let r;
    try { r = await fetch('/api/search?q=' + encodeURIComponent(q)); }
    catch (e) { findinfo.textContent = String(e); return; }
    if (r.status === 401) return location.reload();
    if (!r.ok) { findinfo.textContent = 'search failed'; return; }
    const hits = await r.json();
    // A later keystroke may have answered first: the newest answer is the one that belongs on
    // screen, so a slow reply to an older query is dropped rather than drawn over its replacement.
    if (mine !== findSeq) return;
    list.textContent = '';
    const sessions = new Set();
    for (const h of hits) {
      sessions.add(h.session_id);
      const li = document.createElement('li');
      li.dataset.id = h.session_id;
      const name = document.createElement('div');
      name.textContent = h.title || h.session_id;
      const snip = document.createElement('div');
      snip.className = 'meta';
      snip.textContent = '#' + h.seq + ' ' + h.role + ' · ' + h.snippet;
      li.append(name, snip);
      list.appendChild(li);
    }
    findinfo.textContent = hits.length === 0
      ? 'no match'
      : hits.length + (hits.length === 1 ? ' hit' : ' hits') + ' in ' +
        sessions.size + (sessions.size === 1 ? ' session' : ' sessions');
    markActive();
  }

  find.addEventListener('input', () => { clearTimeout(findTimer); findTimer = setTimeout(runFind, 180); });
  find.addEventListener('keydown', e => {
    // Esc empties the box and gives the session list back; it never touches the conversation.
    if (e.key === 'Escape') { e.preventDefault(); dropFind(); }
    if (e.key === 'Enter') { e.preventDefault(); clearTimeout(findTimer); runFind(); }
  });

  // The model picker, in the stats row (#238). The button is a choice, not a caption: the model is
  // the most-changed setting in the app. The list is the endpoint's own (`GET <base_url>/models`),
  // plus one row that goes back to the name the config holds. A choice lives in this server process
  // only: it is not written to the file, and a turn already in flight keeps the provider it started
  // with — the rule `/model` follows in the terminal.
  const modelLabel = document.getElementById('model');
  const models = document.getElementById('models');
  const modelList = document.getElementById('modellist');
  const modelSub = document.getElementById('modelsub');
  const modelNote = document.getElementById('modelnote');
  let modelSeq = 0; // a reply to an older open is dropped rather than drawn over a newer one
  let reasoningSeq = 0; // the same, for the submenu's `GET /api/reasoning`

  function closeModels() {
    modelSeq++;
    reasoningSeq++;
    models.hidden = true;
    modelList.hidden = false;
    modelSub.hidden = true;
    modelLabel.setAttribute('aria-expanded', 'false');
    modelList.textContent = '';
    modelSub.textContent = '';
    modelNote.textContent = '';
  }

  // `onClick` absent means a row that is a statement ("listing models…", a section head), not a
  // choice: it is drawn disabled, so the pointer and the keyboard agree it cannot be picked.
  function modelRow(text, cls, onClick, into) {
    const b = document.createElement('button');
    b.type = 'button';
    b.textContent = text;
    b.setAttribute('role', 'menuitem');
    if (cls) b.className = cls;
    if (onClick) b.addEventListener('click', onClick); else b.disabled = true;
    (into || modelList).appendChild(b);
    return b;
  }

  // A row that is a switch (#293). The label never changes its verb — the state is on the control,
  // where `role="switch"` and `aria-checked` make it a state rather than a phrase a reader has to
  // interpret — and it is a `<button>` like every other row, so `modelRows()` walks it with
  // Up/Down and Tab without a second kind of thing in the list.
  function switchRow(label, on, opts, into) {
    const b = document.createElement('button');
    b.type = 'button';
    b.className = 'switchrow' + (opts.dim ? ' dim' : '');
    b.setAttribute('role', 'switch');
    b.setAttribute('aria-checked', on ? 'true' : 'false');
    const name = document.createElement('span');
    name.className = 'switchlabel';
    name.textContent = label;
    const track = document.createElement('span');
    track.className = 'track';
    track.setAttribute('aria-hidden', 'true');
    const knob = document.createElement('span');
    knob.className = 'knob';
    track.appendChild(knob);
    b.append(name, track);
    if (opts.title) b.title = opts.title;
    // No handler means no switch to offer: drawn disabled, so the pointer and the keyboard agree
    // it cannot be flipped, and its title is the policy's own sentence for why.
    if (opts.onClick) b.addEventListener('click', opts.onClick); else b.disabled = true;
    (into || modelList).appendChild(b);
    return b;
  }

  // The rows a person can land on, in the order they are drawn — one list, so Up/Down and Tab
  // cannot disagree about what is reachable.
  function modelRows() {
    return Array.from(models.querySelectorAll('button:not(:disabled)'));
  }

  function focusRow(delta) {
    const rows = modelRows();
    if (!rows.length) return;
    const at = rows.indexOf(document.activeElement);
    rows[(at + delta + rows.length) % rows.length].focus();
  }

  async function pickModel(name) {
    try {
      const r = await post('/api/model', { model: name });
      if (r.status === 401) return location.reload();
      const data = await r.json().catch(() => ({}));
      if (!r.ok) { modelNote.textContent = data.error || ('HTTP ' + r.status); return; }
      modelLabel.textContent = data.model || '(not configured)';
      closeModels();
      modelLabel.focus();
      status.textContent = 'the next turn uses ' + (data.model || 'the configured model');
    } catch (e) { modelNote.textContent = String(e); }
  }

  // ---- the reasoning submenu --------------------------------------------------------------
  //
  // The level the next turn carries (`#275`). Two halves again, and now both of them work:
  // showing or hiding reasoning is this page's own display, and the effort is a live switch on the
  // server's single agent — a pick here changes the next turn without a restart, survives a
  // reload (the server owns it), is gone when eclipse-web stops, and never writes `config.toml`.
  // The durable write is the settings page, which says so.
  //
  // The words on offer come from the route's own policy (`GET /api/reasoning`), not from a union
  // spelled here: a row that is drawn is a row the backend takes, and its title is the policy's
  // own sentence for it. Picking something this route cannot take is refused on the server with
  // that same sentence, so a clamp can never be reported as if it had worked.

  function setThinking(open) {
    for (const d of thinkingBlocks()) d.open = open;
    thinkAll.textContent = open ? 'collapse all thinking' : 'expand all thinking';
  }

  function showModelList() {
    modelSub.hidden = true;
    modelList.hidden = false;
    modelNote.textContent = '';
    const first = modelRows()[0];
    if (first) first.focus();
  }

  // The reply to a pick and the reply to the open are the same shape, so the strip and the menu
  // refresh from one answer instead of one guessing what the other did.
  function applyReasoning(data) {
    setEffort(data.effort, data.effort_detail, data.effort_session);
  }

  // The last graded level a person picked in this page, so turning the switch back on asks for
  // something the route has already offered rather than a level spelled here (#293).
  let lastPicked = null;

  async function pickEffort(level) {
    try {
      const r = await post('/api/reasoning', { level });
      if (r.status === 401) return location.reload();
      const data = await r.json().catch(() => ({}));
      if (!r.ok) { modelNote.textContent = data.error || ('HTTP ' + r.status); return; }
      // Remember the level a person chose, but never the off word: turning the switch back on
      // should restore thinking, not re-ask for the off.
      if (level && level !== (data.off_word || 'none')) lastPicked = level;
      applyReasoning(data);
      renderReasoning(data);
    } catch (e) { modelNote.textContent = String(e); }
  }

  function renderReasoning(data) {
    modelSub.textContent = '';
    // The switch (#293). `Reasoning` in every state, `aria-checked` carrying the state, and the
    // flip asks the route for its own off word — never a guess at `reasoning_effort: "none"` on a
    // wire that would 400 on it. A route with no off draws it disabled with the policy's sentence
    // as its title, because a control that presses and changes nothing is worse than none.
    const offWord = data.off_word || null;
    const isOff = offWord !== null && data.effort === offWord;
    const levels = data.levels || [];
    const said = data.described || {};
    // On means: the level in force before it was switched off, else what the file names, else the
    // first level this route offers. Never a word from outside the menu.
    // A level this route no longer offers is not a restore value: the menu must not ask for
    // something it has stopped drawing.
    const restore = (lastPicked && levels.includes(lastPicked) ? lastPicked : null)
      || (data.configured && levels.includes(data.configured) ? data.configured : null)
      || levels.find(w => w !== offWord) || null;
    switchRow('Reasoning', !isOff, {
      title: offWord
        ? (isOff ? 'thinking is off for this session: press to ask for ' + (restore || 'the default') + ' again'
                 : 'thinking is on for this session: press to turn it off')
        : data.off_why,
      onClick: offWord ? () => pickEffort(isOff ? restore : offWord) : null,
    }, modelSub);
    // The level in force, named. Below it, the words this route takes: the tick is on the one in
    // force, and each row's title is the policy's sentence — `xhigh → sends high` is the backend
    // talking, not the request echoed back. The off word is not one of these rows: it is the
    // switch above, and a level list that also contained it is how one dial came to have two
    // controls that disagreed about what "off" meant.
    modelRow('effort · ' + effortLabel, 'head', null, modelSub);
    for (const word of levels) {
      if (word === offWord) continue;
      const on = !isOff && word === data.effort;
      // While it is off the levels stay visible and dimmed: they name what turning it back on
      // would send, and picking one turns thinking on at that level.
      const row = modelRow(on ? word + ' ✓' : word, on ? 'current' : (isOff ? 'dim' : ''),
        on ? null : () => pickEffort(word), modelSub);
      if (said[word]) row.title = said[word];
    }
    // `default` is the word `/reasoning default` uses, and it means "the file again" — one row,
    // not an empty one. With no override in force there is nothing to go back to, so it is drawn
    // as the statement it is.
    const from = data.configured ? ' (' + data.configured + ')' : '';
    if (data.effort_session) {
      modelRow('default · back to the file' + from, '', () => pickEffort(null), modelSub);
    } else {
      modelRow('default · the file is in charge' + from, 'dim', null, modelSub);
    }
    modelRow('‹ model list', 'dim', showModelList, modelSub);
    if (levels.length === 0) {
      // Nothing to pick, and the reason is the backend's — an off-only model, a model that does
      // not reason, a backend nobody described. Six dead words is what this replaces.
      modelNote.textContent = data.note || 'this route takes no reasoning level';
    } else {
      modelNote.textContent = (isOff
        ? 'off for this session — the next turn carries this route\'s off. ' : '') +
        'this dashboard only: the next turn uses it, a reload keeps it, and it is gone when ' +
        'eclipse-web restarts. config.toml is not touched — the settings page writes the file.';
    }
    const first = modelRows()[0];
    if (first) first.focus();
  }

  async function showReasoning() {
    modelList.hidden = true;
    modelSub.hidden = false;
    modelSub.textContent = '';
    modelNote.textContent = '';
    modelRow('reading the route…', 'dim', null, modelSub);
    const mine = ++reasoningSeq;
    let r;
    try { r = await fetch('/api/reasoning'); }
    catch (e) {
      if (mine === reasoningSeq) { modelSub.textContent = ''; modelNote.textContent = String(e); }
      return;
    }
    if (r.status === 401) return location.reload();
    const data = await r.json().catch(() => ({}));
    if (mine !== reasoningSeq) return;
    modelSub.textContent = '';
    if (!r.ok) { modelNote.textContent = data.error || ('HTTP ' + r.status); return; }
    applyReasoning(data);
    renderReasoning(data);
  }

  async function openModels() {
    const mine = ++modelSeq;
    models.hidden = false;
    modelList.hidden = false;
    modelSub.hidden = true;
    modelLabel.setAttribute('aria-expanded', 'true');
    modelList.textContent = '';
    modelSub.textContent = '';
    modelNote.textContent = '';
    modelRow('listing models…', 'dim');
    let r;
    try { r = await fetch('/api/models'); }
    catch (e) { if (mine === modelSeq) { modelList.textContent = ''; modelNote.textContent = String(e); } return; }
    if (r.status === 401) return location.reload();
    const data = await r.json().catch(() => ({}));
    if (mine !== modelSeq) return;
    modelList.textContent = '';
    if (!r.ok) { modelNote.textContent = data.error || ('HTTP ' + r.status); return; }
    const current = data.model || null;
    const configured = data.configured || null;
    const listed = data.models || [];
    for (const name of listed) {
      modelRow(name === current ? name + ' · current' : name,
        name === current ? 'current' : '', () => pickModel(name));
    }
    // Only when a runtime choice is in force is there anything to go back to.
    if (configured && configured !== current) {
      modelRow('back to ' + configured + ' (what the config names)', 'dim', () => pickModel(null));
    }
    modelRow('Reasoning ›', '', showReasoning);
    if (listed.length === 0) {
      modelNote.textContent = 'the endpoint listed no models';
    } else {
      modelNote.textContent = listed.length + (listed.length === 1 ? ' model' : ' models') +
        ' · the next turn uses the choice; it lasts until eclipse-web stops and the config is not changed';
    }
    const first = modelRows()[0];
    if (first) first.focus();
  }

  modelLabel.addEventListener('click', () => {
    if (!models.hidden) return closeModels();
    openModels();
  });
  modelLabel.addEventListener('keydown', e => {
    // Down and Enter open the menu and land on the first row, the way a menu button should.
    if (e.key === 'ArrowDown' && models.hidden) { e.preventDefault(); openModels(); }
  });

  // The menu owns the keys while it is open: arrows walk the rows the browser would not walk on its
  // own (they are not a native menu), Escape closes one level at a time and hands focus back.
  models.addEventListener('keydown', e => {
    if (e.key === 'ArrowDown') { e.preventDefault(); focusRow(1); }
    else if (e.key === 'ArrowUp') { e.preventDefault(); focusRow(-1); }
    else if (e.key === 'Home') { e.preventDefault(); const r = modelRows()[0]; if (r) r.focus(); }
    else if (e.key === 'End') { e.preventDefault(); const r = modelRows(); const last = r[r.length - 1]; if (last) last.focus(); }
    else if (e.key === 'Escape') {
      e.preventDefault();
      // One level at a time: the submenu goes back to the list, the list closes.
      if (!modelSub.hidden) showModelList();
      else { closeModels(); modelLabel.focus(); }
    } else if (e.key === 'Tab') { closeModels(); }
  });

  document.addEventListener('click', e => {
    // A click anywhere but the panel and its label closes it; a click on a row keeps it open
    // long enough to show why a choice failed.
    if (models.hidden) return;
    if (models.contains(e.target) || modelLabel.contains(e.target)) return;
    closeModels();
  });

  // The settings panel: the same key catalogue `/settings` prints and `eclipse config keys` lists,
  // read from and written to the config file on every opening — the file is what the next run
  // loads, so the file is what this shows.
  const setLabel = document.getElementById('settings');
  // ---- the settings window (#267) --------------------------------------------------------------
  //
  // One dialog over the column, sections down the left, one row per key. Nothing here knows a key
  // or a legal value: the row carries its own `kind`, `about` and `choices`, so a new setting
  // appears with the right control and the right sentence without this file changing.
  const setWin = document.getElementById('settingswindow');
  const setRowsBox = document.getElementById('setrows');
  const setSections = document.getElementById('setsections');
  const setFind = document.getElementById('setfind');
  const setNote = document.getElementById('setnote');
  const setPath = document.getElementById('setpath');
  const setClose = document.getElementById('setclose');
  let setRows = [];        // every row, as the server sent it
  let setSection = '';     // '' = all
  let setSeq = 0;          // a slow answer for a closed window must not paint

  const SET_KIND_LABEL = { bool: 'true or false', integer: 'a whole number', float: 'a number',
    list: 'a list', datetime: 'a date' };
  // One line under each section heading saying what the section is *for* (#297). This is the only
  // prose in the window that does not come from the server, on purpose: it describes how the page
  // is organised rather than what a key means — so a section the catalogue grows later gets none,
  // and the "no key is named here" rule is untouched.
  const SET_SECTION_ABOUT = {
    agent: 'the run itself: how many requests it may make, what it may do without asking, and what it is allowed to be',
    provider: 'the model: where it is reached, which one, and how much reasoning it is asked for',
    context: 'what goes into the prompt before your message does — the files, the budget, compaction',
    sessions: 'the store: retention, pruning, and where the transcripts live',
    tools: 'what the agent may use, and which calls need a person to say yes',
    web: 'the dashboard: where it listens, who may sign in, and what the page can do',
    cli: 'the terminal: the prompt, its colours, and what it remembers between lines',
    user: 'who is running this: the names and files the agent reads about its operator',
    update: 'how this build learns about a newer one, and the daily check it makes',
    plugins: 'what is loaded beyond the build\'s own code',
    gateway: 'the long-lived process the messaging platforms talk to',
    skills: 'where skills are read from',
    hooks: 'shell commands run around a turn'
  };

  function closeSettings() {
    setSeq++;
    if (setWin.open) setWin.close();
    setLabel.setAttribute('aria-expanded', 'false');
  }

  // What the file holds, in the words the row uses.
  function setShown(row) {
    if (row.secret) return row.set ? '(set — the value is not shown)' : '(not set)';
    return row.value === null || row.value === undefined ? '(not set)' : row.value;
  }

  function setErr(row) {
    const box = document.createElement('div');
    box.className = 'err';
    return box;
  }

  // One row: what the key is, what it does, the control its kind asks for, and what a change would
  // do. `reset` sends null, which is "comment the line out" — the same thing `config unset` does.
  function setRow(row) {
    const wrap = document.createElement('div');
    wrap.className = 'srow';
    wrap.id = 'set-' + row.key;

    const what = document.createElement('div');
    what.className = 'what';
    const name = document.createElement('code');
    name.textContent = row.key;
    what.appendChild(name);
    wrap.appendChild(what);

    const about = document.createElement('p');
    about.className = 'about';
    about.textContent = row.about || SET_KIND_LABEL[row.kind] || '';
    wrap.appendChild(about);

    const ctl = document.createElement('div');
    ctl.className = 'ctl';
    const err = setErr(row);

    const send = async value => {
      err.textContent = '';
      try {
        const r = await post('/api/settings', { key: row.key, value });
        if (r.status === 401) return location.reload();
        const data = await r.json().catch(() => ({}));
        if (!r.ok) { err.textContent = data.error || ('HTTP ' + r.status); return; }
        // The answer is the row the file now holds, so the row is redrawn from it rather than from
        // what was typed — a value the parser read differently shows that way.
        const i = setRows.findIndex(x => x.key === data.key);
        if (i >= 0) setRows[i] = data;
        redrawSetting(data.key);
        setNote.textContent = data.key + ' = ' + setShown(data) + ' · written; ' + data.applies;
      } catch (e) { err.textContent = String(e); }
    };

    if (row.kind === 'bool') {
      // A switch, not a text box: `true`/`false` go out as TOML booleans because that is what the
      // file holds — a string here would be refused as the wrong type, and that is the point.
      // `#297`: drawn as a track with a knob, so a boolean is the one row here whose state you can
      // read without reading the key, and it stops looking like the `set` button beside it.
      const on = row.value === 'true';
      const b = document.createElement('button');
      b.type = 'button';
      b.className = 'switch';
      b.setAttribute('role', 'switch');
      b.setAttribute('aria-checked', String(on));
      b.title = on ? 'click to turn off' : 'click to turn on';
      const track = document.createElement('span');
      track.className = 'track';
      const state = document.createElement('span');
      state.className = 'state';
      state.textContent = on ? 'on' : 'off';
      b.appendChild(track);
      b.appendChild(state);
      b.addEventListener('click', () => send(on ? 'false' : 'true'));
      ctl.appendChild(b);
    } else if (row.choices && row.choices.length > 0) {
      // A closed set: the options are the server's words, so this select cannot offer a value the
      // parser would refuse.
      const sel = document.createElement('select');
      const current = (row.value || '').replace(/^"|"$/g, '');
      for (const choice of row.choices) {
        const o = document.createElement('option');
        o.value = choice;
        o.textContent = choice;
        if (choice === current) o.selected = true;
        sel.appendChild(o);
      }
      const b = document.createElement('button');
      b.type = 'button';
      b.textContent = 'set';
      b.addEventListener('click', () => send(sel.value));
      ctl.appendChild(sel);
      ctl.appendChild(b);
    } else if (row.kind === 'list') {
      // One item per line. A JSON array is a TOML array, so the wire value is `JSON.stringify` of
      // the lines — no TOML quoting written by hand here.
      const ta = document.createElement('textarea');
      ta.rows = 2;
      const items = (() => {
        try { const v = JSON.parse(row.value || '[]'); return Array.isArray(v) ? v : []; }
        catch (e) { return []; }
      })();
      ta.value = items.join('\n');
      ta.placeholder = 'one item per line';
      const b = document.createElement('button');
      b.type = 'button';
      b.textContent = 'set';
      b.addEventListener('click', () => {
        const lines = ta.value.split('\n').map(x => x.trim()).filter(x => x.length > 0);
        send(JSON.stringify(lines));
      });
      ctl.appendChild(ta);
      ctl.appendChild(b);
    } else {
      const input = document.createElement('input');
      input.type = row.kind === 'integer' || row.kind === 'float' ? 'number' : 'text';
      if (row.kind === 'float') input.step = 'any';
      if (row.secret) {
        // Write-only: never a filled box, and leaving it alone is the default action.
        input.type = 'password';
        input.placeholder = row.set ? 'leave alone to keep the one set' : 'no value set';
        input.autocomplete = 'new-password';
      } else if (row.value !== null && row.value !== undefined) {
        // The TOML rendering, unquoted for a string: what a person would type back.
        input.value = row.kind === 'str' ? String(row.value).replace(/^"(.*)"$/s, '$1') : row.value;
      }
      const b = document.createElement('button');
      b.type = 'button';
      b.textContent = 'set';
      const commit = () => {
        const typed = input.value;
        // An emptied secret box means "leave it alone", not "set it to nothing".
        if (row.secret && typed.length === 0) { err.textContent = 'type a value to replace it, or use reset'; return; }
        send(typed);
      };
      b.addEventListener('click', commit);
      input.addEventListener('keydown', e => {
        if (e.key === 'Enter') { e.preventDefault(); commit(); }
      });
      ctl.appendChild(input);
      ctl.appendChild(b);
    }

    const reset = document.createElement('button');
    reset.type = 'button';
    reset.textContent = 'reset';
    reset.title = 'comment the line out, so the key falls back to what this build defaults to';
    reset.disabled = row.is_default === true;
    reset.addEventListener('click', () => send(null));
    ctl.appendChild(reset);

    // What it is now, what it would fall back to, and when a change lands.
    const where = document.createElement('div');
    where.className = 'where';
    where.textContent = 'now: ' + setShown(row) +
      (row.default === null || row.default === undefined ? '' : '  ·  default: ' + row.default) +
      (row.is_default ? '  ·  at the default' : '');
    const when = document.createElement('span');
    when.className = row.applies === 'restart the dashboard' ? 'restart' : '';
    when.textContent = '  ·  ' + (row.applies === 'restart the dashboard'
      ? 'needs a dashboard restart, not the next message'
      : 'the next run uses it');
    where.appendChild(when);
    // On the control's line, pushed to its right (#297) — not a fourth line under it, which is
    // what made five rows read as one block.
    ctl.appendChild(where);
    wrap.appendChild(ctl);
    wrap.appendChild(err);
    return wrap;
  }

  function redrawSetting(key) {
    const row = setRows.find(r => r.key === key);
    const old = document.getElementById('set-' + key);
    if (!row || !old || !old.parentNode) return;
    old.parentNode.replaceChild(setRow(row), old);
  }

  // The list: sections down the left, rows on the right, filtered by the section and by a search
  // that matches the key *and* the sentence beside it — the thing you are looking for is usually
  // the words, not the name.
  function paintSettings() {
    if (ctxSel) return paintFile();
    const q = setFind.value.trim().toLowerCase();
    const shown = setRows.filter(r =>
      (setSection === '' || r.section === setSection) &&
      (q === '' || r.key.toLowerCase().includes(q) || String(r.about || '').toLowerCase().includes(q)));

    setRowsBox.textContent = '';
    let lastSection = null;
    for (const row of shown) {
      if (row.section !== lastSection) {
        lastSection = row.section;
        const h = document.createElement('h3');
        h.textContent = row.section;
        setRowsBox.appendChild(h);
        // What the section is for, under its name (#297) — the page's own words about its own
        // organisation, and nothing when the catalogue grows a section this page has not met.
        const what = SET_SECTION_ABOUT[row.section];
        if (what) {
          const p = document.createElement('p');
          p.className = 'sectionabout';
          p.textContent = what;
          setRowsBox.appendChild(p);
        }
      }
      setRowsBox.appendChild(setRow(row));
    }
    if (shown.length === 0) {
      const p = document.createElement('p');
      p.className = 'about';
      p.textContent = setRows.length === 0 ? 'the config could not be read' : 'no key matches that';
      setRowsBox.appendChild(p);
    }
    setNote.textContent = shown.length + ' of ' + setRows.length + ' key(s)' +
      (setSection ? ' in [' + setSection + ']' : '') +
      ' · a write is read back from the file before it answers';
  }

  function paintSections() {
    const counts = new Map();
    for (const r of setRows) counts.set(r.section, (counts.get(r.section) || 0) + 1);
    setSections.textContent = '';
    const group = label => {
      const h = document.createElement('h4');
      h.textContent = label;
      setSections.appendChild(h);
    };
    const add = (label, value, count, isFile) => {
      const b = document.createElement('button');
      b.type = 'button';
      const current = isFile ? ctxSel === value : ctxSel === '' && setSection === value;
      b.setAttribute('aria-current', String(current));
      const name = document.createElement('span');
      name.textContent = label;
      const n = document.createElement('span');
      n.className = 'count';
      n.textContent = String(count);
      b.appendChild(name);
      b.appendChild(n);
      b.addEventListener('click', () => {
        if (isFile) { ctxSel = value; } else { ctxSel = ''; setSection = value; }
        paintSections();
        paintSettings();
      });
      setSections.appendChild(b);
    };

    group('settings');
    add('all', '', setRows.length, false);
    for (const [section, count] of [...counts.entries()].sort()) add(section, section, count, false);

    if (ctxFiles.length > 0) {
      group('context files');
      for (const f of ctxFiles) {
        const id = String(f.chars) + (f.truncated ? ' clipped' : '');
        add(f.file, f.name, id, true);
      }
    }
  }

  // ---- the context files (#268) ---------------------------------------------------------------
  //
  // `AGENT.md`, `USER.md`, `MEMORY.md` — the files that decide how the agent behaves. Not keys:
  // prose, and for `MEMORY.md` a `§`-separated list the `memory` tool owns. The three names come
  // from `GET /api/context`, and a save is a `{"name": <id>, "text": <what you typed>}` — never a
  // path.
  let ctxFiles = [];   // rows from `/api/context`
  let ctxSel = '';     // the file being edited; '' means the keys are showing
  let ctxBaseline = ''; // what the textarea was loaded with, so `save` knows if it is dirty

  async function loadContext() {
    try {
      const r = await fetch('/api/context');
      if (r.status === 401) return location.reload();
      const data = await r.json().catch(() => ({}));
      if (!r.ok) { setNote.textContent = data.error || ('HTTP ' + r.status); return; }
      ctxFiles = data.files || [];
      paintSections();
      if (ctxSel) paintFile();
    } catch (e) { setNote.textContent = String(e); }
  }

  function paintFile() {
    const row = ctxFiles.find(f => f.name === ctxSel);
    setRowsBox.textContent = '';
    if (!row) {
      const p = document.createElement('p');
      p.className = 'about';
      p.textContent = 'that file is not in the list this config resolves';
      setRowsBox.appendChild(p);
      return;
    }
    const head = document.createElement('h3');
    head.textContent = row.file + (row.exists ? '' : ' (does not exist yet — saving creates it)');
    setRowsBox.appendChild(head);

    const where = document.createElement('p');
    where.className = 'about';
    where.textContent = row.path;
    setRowsBox.appendChild(where);

    // The meter. A budget that only appears after a save is a budget nobody respects.
    const budget = row.own_budget === null || row.own_budget === undefined ? row.max_chars : row.own_budget;
    const meter = document.createElement('div');
    meter.className = 'meter';
    const bar = document.createElement('div');
    bar.className = 'bar';
    const fill = document.createElement('i');
    fill.style.width = budget > 0 ? Math.min(100, Math.round(100 * row.chars / budget)) + '%' : '0%';
    bar.appendChild(fill);
    if (row.chars > budget) bar.classList.add('over');
    meter.appendChild(document.createTextNode(row.chars + ' chars of ' + (budget > 0 ? budget : 'no cap')));
    meter.appendChild(bar);
    setRowsBox.appendChild(meter);

    // What the prompt will do with it, in the same words the settings rows use.
    const said = [];
    if (row.truncated) {
      said.push('the prompt is already clipping this file: it keeps ' + row.kept + ' of ' + row.chars + ' chars');
    }
    if (row.others > 0) {
      said.push(row.others + ' more ' + row.file + ' layer(s) are injected above this one — the nearest file wins the last word');
    }
    if (row.kind === 'memory') {
      said.push('entries are separated by a line holding §; the memory tool owns this file, its budget is a refusal rather than a clip, and the same lock and rename apply to a save from here');
    }
    said.push('total across the files: ' + row.total + ' of ' + row.total_budget + ' chars');
    for (const line of said) {
      const p = document.createElement('p');
      p.className = row.truncated && line.startsWith('the prompt is already') ? 'about warn' : 'about';
      p.textContent = line;
      setRowsBox.appendChild(p);
    }

    const area = document.createElement('textarea');
    area.id = 'filetext';
    area.spellcheck = false;
    area.value = row.text;
    area.rows = 18;
    ctxBaseline = row.text;
    setRowsBox.appendChild(area);

    const ctl = document.createElement('div');
    ctl.className = 'ctl filebar';
    const counter = document.createElement('span');
    counter.className = 'where';
    const count = () => {
      const now = [...area.value].length;
      counter.textContent = now + ' chars' + (now === row.chars ? '' : ' (' + (now - row.chars > 0 ? '+' : '') + (now - row.chars) + ')');
    };
    count();
    area.addEventListener('input', () => {
      count();
      save.disabled = area.value === ctxBaseline;
    });

    const save = document.createElement('button');
    save.type = 'button';
    save.textContent = 'save';
    save.className = 'primary';
    save.disabled = true;
    const revert = document.createElement('button');
    revert.type = 'button';
    revert.textContent = 'revert';
    revert.addEventListener('click', () => {
      area.value = ctxBaseline;
      count();
      save.disabled = true;
      err.textContent = '';
    });

    const err = document.createElement('div');
    err.className = 'err';

    save.addEventListener('click', async () => {
      err.textContent = '';
      save.disabled = true;
      try {
        const r = await post('/api/context', { name: row.name, text: area.value });
        if (r.status === 401) return location.reload();
        const data = await r.json().catch(() => ({}));
        if (!r.ok) { err.textContent = data.error || ('HTTP ' + r.status); save.disabled = false; return; }
        const i = ctxFiles.findIndex(f => f.name === row.name);
        if (i >= 0) ctxFiles[i] = data.file;
        paintSections();
        paintFile();
        setNote.textContent = 'saved ' + data.file.file + ' · ' + data.applies +
          (data.file.truncated ? ' · and the prompt will clip it: it keeps ' + data.file.kept + ' of ' + data.file.chars + ' chars' : '');
      } catch (e) { err.textContent = String(e); save.disabled = false; }
    });

    ctl.appendChild(save);
    ctl.appendChild(revert);
    ctl.appendChild(counter);
    setRowsBox.appendChild(ctl);
    setRowsBox.appendChild(err);
    setNote.textContent = 'a save applies to the next run; a turn already in flight keeps the prompt it was built with';
  }

  async function loadSettings() {
    const mine = ++setSeq;
    setRowsBox.textContent = '';
    setSections.textContent = '';
    setNote.textContent = 'reading the config…';
    let r;
    try { r = await fetch('/api/settings'); }
    catch (e) { if (mine === setSeq) setNote.textContent = String(e); return; }
    if (r.status === 401) return location.reload();
    const data = await r.json().catch(() => ({}));
    if (mine !== setSeq) return;
    if (!r.ok) { setNote.textContent = data.error || ('HTTP ' + r.status); return; }
    setRows = data.settings || [];
    setSection = '';
    setPath.textContent = (data.profile || 'default') + (data.path ? ' · ' + data.path : '');
    paintSections();
    paintSettings();
  }

  setLabel.addEventListener('click', () => {
    if (setWin.open) return closeSettings();
    setLabel.setAttribute('aria-expanded', 'true');
    setFind.value = '';
    ctxSel = '';
    if (!setWin.open) setWin.showModal();
    loadSettings();
    loadContext();
  });
  setClose.addEventListener('click', closeSettings);
  // Esc closes the dialog by itself; this keeps the button's state honest when it does.
  setWin.addEventListener('close', () => {
    setSeq++;
    setLabel.setAttribute('aria-expanded', 'false');
  });
  setFind.addEventListener('input', paintSettings);


  function showApproval(d) {
    // Built before it is appended so the card lands in one mutation and counts as one event. A card
    // that stole the scroll would be this same bug with a better excuse: it marks the button
    // instead, and a reader who can see the button is as reachable as one who was dragged.
    const el = document.createElement('div');
    el.className = 'msg approval';
    const text = document.createElement('div');
    text.textContent = 'Allow ' + d.tool + '? ' + d.summary;
    const note = document.createElement('div');
    note.className = 'meta';
    note.textContent = 'Declined automatically after ' + d.timeout_secs + 's without an answer.';
    const actions = document.createElement('div');
    actions.className = 'actions';
    const decide = async approved => {
      for (const b of actions.children) b.disabled = true;
      try {
        const r = await post('/api/approvals/' + encodeURIComponent(d.id), { approved });
        if (r.status === 401) location.reload();
        else if (!r.ok) note.textContent = 'The decision could not be delivered (already answered or expired).';
      } catch (e) { note.textContent = String(e); }
    };
    for (const [label, approved, cls] of [['Approve', true, 'yes'], ['Deny', false, 'no']]) {
      const b = document.createElement('button');
      b.type = 'button'; b.className = cls; b.textContent = label;
      b.addEventListener('click', () => decide(approved));
      actions.appendChild(b);
    }
    el.append(text, note, actions);
    pendingApprovals.set(d.id, { note, actions });
    log.appendChild(el);
    status.textContent = 'waiting for your approval…';
    follow();
  }

  function resolveApproval(d) {
    const p = pendingApprovals.get(d.id);
    if (!p) return;
    pendingApprovals.delete(d.id);
    p.actions.remove();
    p.note.textContent = outcomes[d.outcome] || d.outcome;
    status.textContent = 'thinking…';
  }

  function handle(event, data) {
    switch (event) {
      case 'session':
        // A run that starts a session takes the column, whatever was in it.
        setView('session');
        if (deferredLine) { userMessage(deferredLine); deferredLine = null; }
        sessionId = data.session_id;
        runId = data.run_id || null;
        if (runId && busy) setGo('stop');
        // A session that starts while the find box has text would otherwise be prepended into a
        // list of search hits, which is a different list. The box empties and the list comes back.
        if (find.value) dropFind({ rebuild: false });
        // The `groupList()` below rebuilds the list from `master`, so the hits a filter was showing
        // are replaced by the sessions again — the box is empty by now.
        if (!master.some(li => li.dataset.id === sessionId)) {
          // The row a run just created: same shape as the list's, so the actions are there
          // without waiting for the reply to finish and the list to be read back. It joins
          // `master`, or the rebuild that follows would drop a row the DOM was just given (#345).
          master.unshift(sessionRow({ id: sessionId, preview: input.dataset.last || '' }));
        }
        groupList();
        markActive();
        break;
      case 'reasoning':
        if (thinking) {
          thinking.textContent += data.text;
          thinkingHeader(thinking);
        } else {
          thinking = addThinking(data.text);
        }
        follow();
        break;
      case 'delta':
        thinking = null; composing = null;
        if (!live) live = add('assistant', '');
        live.textContent += data.text;
        follow();
        break;
      case 'tool_call_delta':
        // Arguments arriving for a call that is still being composed. What arrives is JSON for a
        // row that does not exist yet, so the placeholder says that and nothing else: streaming
        // the payload onto the screen was the wall of text this change removes.
        thinking = null; live = null;
        if (!composing) {
          composing = add('tool', '→ working out a tool call…');
          composing.classList.add('composing');
        }
        // Every arriving chunk, `follow()` included, is the difference between "the pane follows the
        // run" and "the pane follows the run until you touch it" (#339).
        follow();
        break;
      case 'tool_call': {
        const row = addCall(data.name, data.arguments, data.summary, 'running', data.call_id);
        if (composing) { composing.replaceWith(row); composing = null; }
        endBlocks();
        break;
      }
      case 'context_trimmed': {
        // What the server actually sends: `memory`, `memory_error` and the judgement pass. A
        // `data.summarized` that nothing ever set used to make this line say "not sent" on every
        // trim, including the ones where a handoff *was* compiled and sent.
        let note = '[context: ' + data.turns + ' older turn(s) not sent to fit the context budget';
        if (data.memory === 'reused') note += '; reused from this session\'s stored memory';
        if (data.memory === 'saved') note += '; saved to this session\'s memory';
        if (data.memory === 'save_failed') note += '; could not save session memory';
        if (data.memory_error) note += '; memory error: ' + data.memory_error;
        // `off` is the config not asking for a judgement pass: saying nothing is the truth there.
        if (data.judgement === 'used') {
          note += '; ' + data.judgement_bullets + ' handoff bullet(s) written by the model';
        } else if (data.judgement === 'rejected') {
          note += '; handoff notes rejected: ' + data.judgement_error;
        } else if (data.judgement === 'failed') {
          note += '; handoff notes failed: ' + data.judgement_error;
        }
        add('tool', note + ']');
        break;
      }
      case 'tool_result': {
        // The row the call already made gains its mark and its output; nothing is printed here.
        // A result with no row (a call from a turn this tab did not see) is shown, because losing
        // it silently would be worse than one line of text.
        const row = callRow(data.call_id, data.name);
        if (!row) { add(data.is_error ? 'error' : 'tool', data.output); break; }
        callState(row, data.state);
        attachOutput(row, data.output);
        follow();
        break;
      }
      case 'message':
        // The final text is authoritative; it replaces whatever was streamed.
        thinking = null; composing = null;
        if (live) { live.textContent = data.text; live = null; } else add('assistant', data.text);
        break;
      case 'notice':
        // A line the server answered instead of the model (`#254`): a command's result, or the
        // reason it was refused. No turn happened, so the line the person typed is drawn here —
        // as a command, not as a question the model was asked.
        endBlocks();
        if (deferredLine) { add('command', deferredLine); deferredLine = null; }
        {
          const row = add('notice', data.text);
          if (data.kind === 'refusal') row.classList.add('refusal');
        }
        // `/new` is a promise, not a switch: the page stops holding a session and the next
        // message opens one.
        if (data.clear_session) { sessionId = null; runId = null; markActive(); }
        // `#285`: approvals off is a mode with a word on the stats row. It is painted from the
        // server's answer, never from the line that was typed — a refusal must leave it alone.
        if (data.yolo !== null && data.yolo !== undefined) paintYolo(data.yolo);
        break;
      case 'approval_request': showApproval(data); break;
      case 'approval_resolved': resolveApproval(data); break;
      case 'stats':
        // A turn in flight is the one row that is current, so it carries no `… ago` (#344).
        paintLive(data);
        if (data.effort) setEffort(data.effort, data.effort_detail, data.effort_session);
        break;
      case 'cancelled': endBlocks(); add('tool', '[cancelled]'); break;
      case 'error': endBlocks(); add('error', data.message); break;
    }
  }

  // A big paste stands aside (#220). The rule is the terminal's — one line and at most
  // PASTE_INLINE_LIMIT characters stays inline — and the number is rendered into the form from the
  // same Rust constant, so the two surfaces cannot disagree about what counts as big. The text is
  // held in memory: parity with the CLI, and nothing to clean up afterwards.
  const PASTE_LIMIT = Number(document.getElementById('form').dataset.pasteLimit || 160);
  const pastes = [];          // [{ chip, text }], numbered from 1 like the CLI's
  const pasteBar = document.getElementById('pastes');

  function pasteLines(text) {
    const trimmed = text.replace(/\n+$/, '');
    return Math.max(1, trimmed.split('\n').length);
  }

  function fitsInline(text) {
    return pasteLines(text) === 1 && Array.from(text).length <= PASTE_LIMIT;
  }

  function chipFor(text) {
    return '[Pasted #' + (pastes.length + 1) + ': ' + pasteLines(text) + ' line(s), ' +
      Array.from(text).length + ' chars]';
  }

  function renderPastes() {
    pasteBar.textContent = '';
    pasteBar.hidden = pastes.length === 0;
    pastes.forEach((paste, i) => {
      const b = document.createElement('button');
      b.type = 'button';
      b.className = 'paste';
      b.title = 'remove this paste — the text is dropped, nothing else changes';
      b.textContent = paste.chip + ' ';
      const x = document.createElement('span');
      x.className = 'x';
      x.textContent = '×';
      b.appendChild(x);
      b.addEventListener('click', () => {
        const at = input.value.indexOf(paste.chip);
        if (at >= 0) input.value = input.value.slice(0, at) + input.value.slice(at + paste.chip.length);
        pastes.splice(i, 1);
        renderPastes();
        input.focus();
      });
      pasteBar.appendChild(b);
    });
  }

  // What the model gets: every chip on the line, replaced by what it stands for. Forgetting this
  // sends a placeholder the user never typed and the answer is about nothing.
  function expandPastes(line) {
    let out = line;
    for (const paste of pastes) out = out.replace(paste.chip, () => paste.text);
    return out;
  }

  input.addEventListener('paste', e => {
    const text = (e.clipboardData || window.clipboardData).getData('text');
    if (!text || fitsInline(text)) return;   // a path or a sentence lands where the caret is
    e.preventDefault();
    const chip = chipFor(text);
    pastes.push({ chip, text });
    const at = input.selectionStart;
    input.value = input.value.slice(0, at) + chip + input.value.slice(input.selectionEnd);
    input.selectionStart = input.selectionEnd = at + chip.length;
    renderPastes();
  });

  // ---- what the `+` menu attaches (#239) ------------------------------------------------------
  //
  // A chip is the request. `text` is a file this page read — a picker hands a page bytes and never a
  // path, which is why "attach by path" is its own row rather than a second mode of the picker —
  // `path` and `url` are references spelled into the turn, because `read_file` and `fetch` are the
  // tools that own those rules. The cap is the server's, restated here so a file over it is refused
  // before it is read rather than after it is sent.
  const ATTACH_MAX_CHARS = 65536;
  // A picture's cap is on the decoded size, matching the server's: bytes are what a request body
  // and every later request's history have to carry.
  const PICTURE_MAX_BYTES = 2 * 1024 * 1024;
  const PICTURE_TYPES = ['image/png', 'image/jpeg', 'image/webp', 'image/gif'];
  const attached = [];
  const attachFile = document.getElementById('attachfile');
  const pictureInput = document.getElementById('attachpicture');
  const attachMenu = document.getElementById('attachmenu');
  const plus = document.getElementById('plus');

  function renderAttached() {
    const box = document.getElementById('attached');
    box.textContent = '';
    box.hidden = attached.length === 0;
    attached.forEach((a, i) => {
      const chip = document.createElement('span');
      chip.className = 'chip';
      const label = document.createElement('span');
      label.textContent = a.kind === 'text'
        ? a.name + ' · ' + a.value.length + ' chars'
        : a.kind === 'image' ? 'picture: ' + a.name
        : a.kind === 'path' ? 'path: ' + a.value : 'link: ' + a.value;
      const x = document.createElement('button');
      x.type = 'button';
      x.className = 'x';
      x.textContent = '×';
      x.title = 'remove this attachment';
      x.addEventListener('click', () => { attached.splice(i, 1); renderAttached(); plus.focus(); });
      chip.append(label, x);
      box.appendChild(chip);
    });
  }

  function closeAttach() {
    attachMenu.hidden = true;
    plus.setAttribute('aria-expanded', 'false');
  }

  /// The rows the menu can offer, and what each one does. A disabled row is in the list on
  /// purpose: `image` and `audio` are things a person will look for, and the row says what has to
  /// land before it works rather than the feature being invisible until it does.
  function attachRow(kind) {
    if (kind === 'file') {
      closeAttach();
      attachFile.click();
      return;
    }
    if (kind === 'path') {
      closeAttach();
      const typed = window.prompt('Path to a file on this machine (the agent reads it with read_file)', '');
      if (typed === null) return;
      const value = typed.trim();
      if (!value) return;
      if (value.length > 512 || /[\u0000-\u001f]/.test(value)) {
        status.textContent = 'a path is one line, at most 512 characters';
        return;
      }
      attached.push({ kind: 'path', name: '', value });
      renderAttached();
      status.textContent = 'attached path: ' + value;
      return;
    }
    // `#346`: a picture is read here, as a data URL, because the page is the only thing that has
    // it — a path would be a reference the model resolves with `read_file`, which is a different
    // act, and a link would be `fetch`.
    if (kind === 'image') {
      closeAttach();
      pictureInput.click();
      return;
    }
    if (kind === 'url') {
      closeAttach();
      const typed = window.prompt('Link (the agent fetches it)', 'https://');
      if (typed === null) return;
      const value = typed.trim();
      if (!value) return;
      if (!/^https?:\/\/\S+$/.test(value) || value.length > 2048) {
        status.textContent = 'a link starts with http:// or https:// and holds no spaces';
        return;
      }
      attached.push({ kind: 'url', name: '', value });
      renderAttached();
      status.textContent = 'attached link: ' + value;
    }
  }

  attachFile.addEventListener('change', async e => {
    const f = e.target.files && e.target.files[0];
    e.target.value = '';
    if (!f) return;
    if (f.size > ATTACH_MAX_CHARS) {
      status.textContent = f.name + ' is ' + f.size + ' bytes and the limit is ' + ATTACH_MAX_CHARS +
        ' — attach it as a path instead and the agent reads the part it needs';
      return;
    }
    let text;
    try { text = await f.text(); } catch (err) {
      status.textContent = f.name + ' could not be read as text: ' + err;
      return;
    }
    if (text.length > ATTACH_MAX_CHARS) {
      status.textContent = f.name + ' is ' + text.length + ' characters and the limit is ' + ATTACH_MAX_CHARS +
        ' — attach it as a path instead';
      return;
    }
    attached.push({ kind: 'text', name: f.name, value: text });
    renderAttached();
    status.textContent = 'attached ' + f.name + ' · ' + text.length + ' chars';
    input.focus();
  });

  // 2 MB decoded is the cap the server enforces; checked here too, so a 40 MB phone photo is a
  // sentence rather than a request that dies halfway.
  pictureInput.addEventListener('change', async e => {
    const f = e.target.files && e.target.files[0];
    e.target.value = '';
    if (!f) return;
    if (f.size > PICTURE_MAX_BYTES) {
      status.textContent = f.name + ' is ' + Math.round(f.size / 1024) + ' KB and a picture may be ' +
        Math.round(PICTURE_MAX_BYTES / 1024) + ' KB';
      return;
    }
    let url;
    try {
      url = await new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => resolve(String(reader.result));
        reader.onerror = () => reject(reader.error || 'could not read it');
        reader.readAsDataURL(f);
      });
    } catch (err) {
      status.textContent = f.name + ' could not be read: ' + err;
      return;
    }
    const mime = (url.match(/^data:([^;,]+)/) || [])[1] || f.type || '';
    if (!PICTURE_TYPES.includes(mime)) {
      status.textContent = f.name + ' is ' + (mime || 'an unknown type') +
        '; this build carries ' + PICTURE_TYPES.join(', ');
      return;
    }
    attached.push({ kind: 'image', name: f.name, value: url });
    renderAttached();
    status.textContent = 'attached picture: ' + f.name + ' · ' + Math.round(f.size / 1024) + ' KB';
    input.focus();
  });

  plus.addEventListener('click', () => {
    if (!attachMenu.hidden) { closeAttach(); return; }
    attachMenu.hidden = false;
    plus.setAttribute('aria-expanded', 'true');
    const first = attachMenu.querySelector('button:not(:disabled)');
    if (first) first.focus();
  });
  attachMenu.addEventListener('click', e => {
    const row = e.target.closest('button[data-attach]');
    if (row && !row.disabled) attachRow(row.dataset.attach);
  });
  // `Escape` closes the menu and hands the keyboard back to the control that opened it — the same
  // contract the `/` menu keeps.
  attachMenu.addEventListener('keydown', e => {
    const rows = [...attachMenu.querySelectorAll('button:not(:disabled)')];
    const at = rows.indexOf(document.activeElement);
    if (e.key === 'Escape') { e.preventDefault(); closeAttach(); plus.focus(); }
    else if (e.key === 'ArrowDown') { e.preventDefault(); (rows[(at + 1) % rows.length] || plus).focus(); }
    else if (e.key === 'ArrowUp') { e.preventDefault(); (rows[(at - 1 + rows.length) % rows.length] || plus).focus(); }
  });
  // A click anywhere else closes it, the way a menu behaves.
  document.addEventListener('mousedown', e => {
    if (!attachMenu.hidden && !attachMenu.contains(e.target) && e.target !== plus) closeAttach();
  });

  async function submit() {
    // The chips become text here, before anything is sent: the transcript and the model both see
    // what was pasted, and nothing else in the app has to know chips exist.
    const text = expandPastes(input.value).trim();
    // A turn may be the attachment alone ("this is the file"), so the words are not required when
    // something is attached (#239).
    if ((!text && attached.length === 0) || busy) return;
    const carrying = attached.map(a => ({ kind: a.kind, name: a.name || '', value: a.value }));
    // `#389`: the composer is cleared optimistically, so a refusal has to put it back — a 413, a
    // refused attachment, a 429 ("too many chats") or a 503 used to cost the words *and* the chips,
    // and the file had to be picked again. Kept rather than re-derived: `text` is the *expanded*
    // form, and re-expanding it would unfold every paste a second time.
    const typed = input.value;
    const pastesBefore = pastes.slice();
    const attachedBefore = attached.slice();
    const restoreComposer = () => {
      input.value = typed;
      pastes.length = 0;
      pastes.push(...pastesBefore);
      renderPastes();
      attached.length = 0;
      attached.push(...attachedBefore);
      renderAttached();
    };
    busy = true;
    endBlocks();
    clearStats();
    // The line is about to go: a menu with no word to complete would stay open over the answer.
    closeCmdMenu();
    input.value = '';
    pastes.length = 0;
    renderPastes();
    attached.length = 0;
    renderAttached();
    input.dataset.last = text.slice(0, 50);
    // A line that starts with `/` is a command the server answers, not a turn (#254), so the echo
    // waits for the answer: a refused command must not look like something the model was asked.
    // A turn carrying only an attachment has no words to echo, and an empty row would read as a
    // message that was lost (#239).
    const said = text || (carrying.length ? '(' + carrying.length + ' attached)' : '');
    let echo = null;
    if (text.startsWith('/')) deferredLine = said; else echo = userMessage(said);
    setGo('starting'); status.textContent = 'thinking…';
    let reader = null;
    try {
      const resp = await post('/api/chat',
        carrying.length ? { message: text, session_id: sessionId, attachments: carrying }
                        : { message: text, session_id: sessionId });
      if (resp.status === 401) { location.reload(); return; }
      if (!resp.ok) {
        const err = await resp.json().catch(() => ({}));
        add('error', err.error || ('HTTP ' + resp.status));
        // Nothing ran, so the press is undone: the bubble was not a message the store has, and the
        // words and chips go back into the composer (#389).
        if (echo) echo.remove();
        restoreComposer();
        return;
      }
      let finished = false;
      reader = resp.body.getReader();
      const dec = new TextDecoder();
      let buf = '';
      for (;;) {
        const { done, value } = await reader.read();
        if (done) break;
        buf += dec.decode(value, { stream: true });
        let idx;
        while ((idx = buf.indexOf('\n\n')) >= 0) {
          const block = buf.slice(0, idx); buf = buf.slice(idx + 2);
          let event = 'message', data = '';
          for (const line of block.split('\n')) {
            if (line.startsWith('event:')) event = line.slice(6).trim();
            else if (line.startsWith('data:')) data += line.slice(5).trim();
          }
          if (event === 'done') finished = true;
          // `#391`: one malformed event must not end the run in the page's head. A throw here used
          // to land in the outer `catch`, which set `busy = false` and cleared `runId` while the
          // server kept running the turn — no output, and no Stop because there was no id left.
          if (data) {
            try { handle(event, JSON.parse(data)); }
            catch (e) { add('error', 'a malformed event: ' + e); }
          }
        }
      }
      if (!finished) add('error', 'Connection closed before the reply finished');
    } catch (e) {
      add('error', String(e));
    } finally {
      // `#391`: a loop that leaves early leaves the connection open otherwise, and the server's
      // disconnect guard is what cancels the turn — closing the reader is how the page stops a run it
      // can no longer show or offer a Stop for.
      if (reader) { try { await reader.cancel(); } catch (e) { /* the stream is already gone */ } }
      // `#390`: a `/command` line whose request never landed left this set, and the next successful
      // turn consumed it — an old command printed above a new answer. Every event that could use it
      // has been handled by now, so it is spent either way.
      deferredLine = null;
      busy = false; setGo('idle'); runId = null;
      status.textContent = ''; input.focus();
      // The store now has the reply, and with it the preview or title the row should show. A
      // session named by a model gets its name from a call that runs beside this turn, so one more
      // read a few seconds later is what makes that name appear without the user doing anything.
      if (!find.value) {
        refreshSessions();
        setTimeout(() => { if (!find.value && !busy) refreshSessions(); }, 5000);
      }
    }
  }

  async function cancelRun() {
    if (!runId) return;
    status.textContent = 'cancelling…';
    try {
      await post('/api/runs/' + encodeURIComponent(runId) + '/cancel');
    } catch (e) {
      add('error', String(e));
    }
  }

  // The one control: idle sends, a run in flight stops, and the gap between them says so. It is a
  // `type="button"` on purpose — a submit button would fire the form's own submit on the same click
  // and race the cancel.
  go.addEventListener('click', () => {
    switch (go.dataset.state) {
      case 'stop': cancelRun(); break;
      case 'starting': status.textContent = 'starting — nothing to cancel yet'; break;
      default: document.getElementById('form').requestSubmit();
    }
  });
  document.getElementById('logout').addEventListener('submit', async e => {
    e.preventDefault();
    try { await post('/logout'); } finally { location.href = '/login'; }
  });
  document.getElementById('form').addEventListener('submit', e => { e.preventDefault(); submit(); });
  // ---- the `/` menu (#282) ------------------------------------------------------------------
  //
  // The rows are the server's command table, fetched once (`GET /api/commands`) and filtered here
  // as the word is typed. This file names no command: if a verb is added to the table it appears
  // in this menu, and if a verb stops being served here it disappears — the menu cannot offer a
  // row that the server's parse would refuse.
  //
  // `commands` is `null` until the fetch settles: a failed fetch leaves it empty and the composer
  // works exactly as before, because the menu is a convenience and the parse is the server's.
  let commands = null;
  let cmdRows = [];    // the rows on screen, in order
  let cmdActive = -1;  // the row the arrows are on, or -1 for none

  const commandWord = () => {
    const line = input.value;
    if (!line.startsWith('/') || /\s/.test(line)) return null;
    return line;
  };

  function closeCmdMenu() {
    cmdmenu.hidden = true;
    cmdmenu.textContent = '';
    input.removeAttribute('aria-activedescendant');
    input.setAttribute('aria-expanded', 'false');
    cmdRows = [];
    cmdActive = -1;
  }

  function markCmdRow() {
    for (let i = 0; i < cmdRows.length; i++) {
      const on = i === cmdActive;
      cmdRows[i].el.setAttribute('aria-selected', String(on));
      if (on) {
        input.setAttribute('aria-activedescendant', cmdRows[i].el.id);
        // Keep the row visible in a list that can scroll.
        const top = cmdRows[i].el.offsetTop, bottom = top + cmdRows[i].el.offsetHeight;
        if (top < cmdmenu.scrollTop) cmdmenu.scrollTop = top;
        else if (bottom > cmdmenu.scrollTop + cmdmenu.clientHeight) {
          cmdmenu.scrollTop = bottom - cmdmenu.clientHeight;
        }
      }
    }
    if (cmdActive < 0) input.removeAttribute('aria-activedescendant');
  }

  function paintCmdMenu(word) {
    cmdmenu.textContent = '';
    cmdRows = [];
    cmdActive = -1;
    if (commands === null) { cmdmenu.hidden = true; return; }
    const shown = commands.filter(c => c.name.startsWith(word) ||
      (c.aliases || []).some(a => a.startsWith(word)));
    if (shown.length === 0) {
      // The word is a `/` line and nothing matches: say so rather than vanish, because the line is
      // still going to be answered by the server (with `unknown command; try /help`).
      const empty = document.createElement('div');
      empty.className = 'empty';
      empty.textContent = 'no command starts with ' + word + ' — Enter sends it as a line';
      cmdmenu.appendChild(empty);
      cmdmenu.hidden = false;
      input.setAttribute('aria-expanded', 'true');
      return;
    }
    for (const c of shown) {
      const el = document.createElement('button');
      el.type = 'button';
      el.id = 'cmd-' + c.name.replace(/^\//, '');
      el.setAttribute('role', 'option');
      el.setAttribute('aria-selected', 'false');
      const label = document.createElement('span');
      label.className = 'label';
      label.textContent = c.label || c.name;
      const why = document.createElement('span');
      why.className = 'why';
      why.textContent = c.help || '';
      el.appendChild(label);
      el.appendChild(why);
      // A click completes the same way Tab does; it never sends.
      el.addEventListener('mousedown', e => { e.preventDefault(); acceptCmd(c); });
      cmdmenu.appendChild(el);
      cmdRows.push({ el, command: c });
    }
    cmdmenu.hidden = false;
    input.setAttribute('aria-expanded', 'true');
    // Land on the only row if there is only one, as the terminal's Tab does.
    if (cmdRows.length === 1) { cmdActive = 0; markCmdRow(); }
  }

  function acceptCmd(c) {
    const word = commandWord();
    if (word === null) return closeCmdMenu();
    // The row shows the table's spelling (`/set <key> <value>`); the line gets the word, and a
    // space when the command takes an argument — the placeholders are help, not syntax to type.
    input.value = c.name + (c.takes_arg ? ' ' : '');
    input.selectionStart = input.selectionEnd = input.value.length;
    closeCmdMenu();
    input.focus();
  }

  async function loadCommands() {
    if (commands !== null) return;
    try {
      const r = await fetch('/api/commands');
      if (r.status === 401) return location.reload();
      const data = await r.json().catch(() => ({}));
      commands = r.ok && Array.isArray(data.commands) ? data.commands : [];
    } catch (e) {
      commands = [];  // a menu that could not be built is not an error in the composer
    }
    // The line may already be a command word: the fetch settles after the first keystroke.
    const word = commandWord();
    if (word !== null) paintCmdMenu(word);
  }
  loadCommands();

  input.addEventListener('input', () => {
    const word = commandWord();
    if (word === null) return closeCmdMenu();
    if (commands === null) { loadCommands(); return; }
    paintCmdMenu(word);
  });

  input.addEventListener('keydown', e => {
    const open = !cmdmenu.hidden;
    if (open) {
      if (e.key === 'ArrowDown') { e.preventDefault(); cmdActive = cmdActive < 0 ? 0 : (cmdActive + 1) % Math.max(cmdRows.length, 1); markCmdRow(); return; }
      if (e.key === 'ArrowUp') { e.preventDefault(); cmdActive = cmdActive < 0 ? cmdRows.length - 1 : (cmdActive - 1 + cmdRows.length) % Math.max(cmdRows.length, 1); markCmdRow(); return; }
      if (e.key === 'Tab' || (e.key === 'Enter' && cmdRows.length > 0 && cmdActive >= 0)) {
        if (cmdActive >= 0) { e.preventDefault(); acceptCmd(cmdRows[cmdActive].command); return; }
      }
      if (e.key === 'Escape') {
        // Closed, and the line untouched: a `/` line is also a legitimate prompt (#282).
        e.preventDefault(); e.stopPropagation(); closeCmdMenu(); return;
      }
    }
    if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); submit(); }
  });
  // A click anywhere else closes it; the row's own mousedown already completed the word.
  document.addEventListener('mousedown', e => {
    if (cmdmenu.hidden) return;
    if (cmdmenu.contains(e.target) || e.target === input) return;
    closeCmdMenu();
  });
  // The update badge: one read of the same cache the CLI reads. The page never asks the
  // repository — the gateway's schedule owns that, and three open tabs must not be three
  // clients. Nothing here installs anything; it names the two commands and stops.
  const notice = document.getElementById('notice');
  const updateBadge = document.getElementById('updatebadge');
  const updateText = document.getElementById('updatetext');
  const updatePop = document.getElementById('updatepop');
  const closeUpdate = () => {
    updatePop.hidden = true;
    updateBadge.setAttribute('aria-expanded', 'false');
  };
  async function refreshUpdate() {
    let r;
    try { r = await fetch('/api/update'); } catch (e) { return; }
    if (r.status === 401) return location.reload();
    const data = await r.json().catch(() => ({}));
    // No answer, no badge: a stale claim is worse than no claim, and the endpoint says so itself.
    if (!r.ok || !data.behind) { notice.hidden = true; closeUpdate(); return; }
    updateText.textContent = '↑ ' + String(data.latest || '').replace(/^v/, '') + ' available';
    notice.hidden = false;
  }
  updateBadge.addEventListener('click', e => {
    e.stopPropagation();
    const opening = updatePop.hidden;
    updatePop.hidden = !opening;
    updateBadge.setAttribute('aria-expanded', String(opening));
  });
  document.addEventListener('click', e => {
    if (updatePop.hidden) return;
    if (updatePop.contains(e.target) || updateBadge.contains(e.target)) return;
    closeUpdate();
  });
  document.addEventListener('keydown', e => {
    if (e.key !== 'Escape') return;
    if (!updatePop.hidden) { e.preventDefault(); closeUpdate(); return; }
    // Escape leaves the menu the way Tab would: closed, with the ⋮ under the keyboard again.
    const open = list.querySelector('.menu:not([hidden])');
    if (open) {
      e.preventDefault();
      toggleMenu(open, open.parentElement.querySelector('.dots'), false);
    }
  });
  document.addEventListener('click', e => {
    if (!e.target.closest('#sessions .dots') && !e.target.closest('#sessions .menu')) closeMenus();
  });
  // Checked again half-hourly, not per repaint: an `eclipse upgrade` in a terminal should clear
  // this without a reload, and a tab left open overnight should not keep yesterday's news.
  refreshUpdate();
  setInterval(refreshUpdate, 30 * 60 * 1000);

  // ---------------------------------------------------------------------------------------
  // Scheduled jobs. The pane is a viewer and an editor of the same file the timer reads: every
  // button here calls a route that calls a `cron::*` function, and nothing schedules anything of
  // its own. `run now` starts a process and answers at once (#112: the tick is a model turn, and a
  // handler that waits for one is a handler that hangs); the pane polls until the tick records
  // that it started.
  // ---------------------------------------------------------------------------------------
  const cronBtn = document.getElementById('cron');
  const cronPane = document.getElementById('cronpane');
  const cronRows = document.getElementById('cronrows');
  const cronMsg = document.getElementById('cronmsg');
  const cronFile = document.getElementById('cronfile');
  const cronForm = document.getElementById('cronform');
  const crName = document.getElementById('cr-name');
  const crSchedule = document.getElementById('cr-schedule');
  const crPrompt = document.getElementById('cr-prompt');
  const crWorkdir = document.getElementById('cr-workdir');
  const crEditing = document.getElementById('cronediting');
  const cronLogsBox = document.getElementById('cronlogs');
  let cronOpen = false;
  let cronJobs = [];
  let cronNow = 0;
  let cronBusy = new Set();   // job names whose run has not started yet
  let cronEditingName = null; // null = the form is creating

  // A write with a verb: the same CSRF header as `post`, and a body only when there is one.
  const write = (method, url, body) => fetch(url, {
    method,
    headers: body === undefined
      ? { 'X-Eclipse-CSRF': CSRF }
      : { 'X-Eclipse-CSRF': CSRF, 'content-type': 'application/json' },
    body: body === undefined ? undefined : JSON.stringify(body),
  });

  function cronSay(text, bad) {
    cronMsg.textContent = text || '';
    cronMsg.className = bad ? 'bad' : '';
  }

  // The server's `now_ms`, not the browser's clock: a laptop whose clock is ten minutes off would
  // otherwise say a job fires in ten minutes when it fires now.
  function inWords(ms) {
    const delta = ms - cronNow;
    if (delta < 0) return 'due';
    const mins = Math.round(delta / 60000);
    if (mins < 60) return 'in ' + mins + 'm';
    const hours = Math.floor(mins / 60);
    if (hours < 24) return 'in ' + hours + 'h ' + (mins % 60) + 'm';
    return 'in ' + Math.floor(hours / 24) + 'd ' + (hours % 24) + 'h';
  }

  function agoWords(ms) {
    const delta = cronNow - ms;
    if (delta < 60000) return 'just now';
    const mins = Math.floor(delta / 60000);
    if (mins < 60) return mins + 'm ago';
    const hours = Math.floor(mins / 60);
    if (hours < 24) return hours + 'h ago';
    return Math.floor(hours / 24) + 'd ago';
  }

  function cronCell(td, text, cls) {
    td.textContent = text;
    if (cls) td.className = cls;
    return td;
  }

  function rowButton(label, title, handler, cls) {
    const b = document.createElement('button');
    b.type = 'button';
    b.textContent = label;
    b.title = title;
    if (cls) b.className = cls;
    b.addEventListener('click', handler);
    return b;
  }

  function renderCron() {
    cronRows.textContent = '';
    if (!cronJobs.length) {
      const tr = document.createElement('tr');
      const td = document.createElement('td');
      td.colSpan = 5;
      td.className = 'when';
      td.textContent = 'no jobs are scheduled — “+ new job” writes the first one';
      tr.appendChild(td);
      cronRows.appendChild(tr);
      return;
    }
    for (const job of cronJobs) {
      const tr = document.createElement('tr');
      if (!job.enabled) tr.className = 'off';
      tr.appendChild(cronCell(document.createElement('td'), job.name, 'name'));
      tr.appendChild(cronCell(document.createElement('td'), job.schedule));
      tr.appendChild(cronCell(document.createElement('td'),
        job.enabled ? (job.next_ms ? inWords(job.next_ms) : '—') : 'off', 'when'));
      const last = job.last_outcome
        ? job.last_outcome + (job.last_started_ms ? ' · ' + agoWords(job.last_started_ms) : '')
        : 'never';
      tr.appendChild(cronCell(document.createElement('td'), last,
        'last ' + (job.last_outcome === 'failed' ? 'failed' : job.last_outcome ? 'ok' : '')));
      const acts = document.createElement('td');
      acts.className = 'acts';
      const running = cronBusy.has(job.name) ||
        (job.last_started_ms && job.last_finished_ms && job.last_started_ms > job.last_finished_ms);
      const run = rowButton(running ? 'running…' : 'run', 'run it now, whether or not it is due',
        () => runNow(job.name), 'go');
      run.disabled = Boolean(running);
      acts.appendChild(run);
      acts.appendChild(rowButton(job.enabled ? 'off' : 'on',
        job.enabled ? 'stop it firing, keeping the job' : 'let it fire again',
        () => toggleJob(job.name, !job.enabled)));
      acts.appendChild(rowButton('logs', 'the last runs and what they answered',
        () => showLogs(job.name)));
      acts.appendChild(rowButton('edit', 'change the schedule or the prompt', () => editJob(job)));
      acts.appendChild(rowButton('remove', 'delete the job; its run logs stay on disk',
        () => removeJob(job.name), 'bad'));
      tr.appendChild(acts);
      cronRows.appendChild(tr);
    }
  }

  async function loadCron(quiet) {
    let r;
    try { r = await fetch('/api/cron'); } catch (e) { cronSay('the dashboard is not answering', true); return; }
    if (r.status === 401) return location.reload();
    const data = await r.json().catch(() => ({}));
    if (!r.ok) { cronSay(data.error || ('could not read the jobs (' + r.status + ')'), true); return; }
    cronJobs = data.jobs || [];
    cronNow = data.now_ms || Date.now();
    cronFile.textContent = data.jobs_file || '';
    // A run that has started is no longer pending: the state moved between two polls.
    if (cronBusy.size) {
      for (const job of cronJobs) {
        if (cronBusy.has(job.name) && job.last_started_ms && job.last_started_ms > job.last_finished_ms) {
          cronBusy.delete(job.name);
        }
      }
    }
    renderCron();
    if (!quiet) cronSay('');
  }

  async function runNow(name) {
    cronBusy.add(name);
    renderCron();
    let r;
    try { r = await write('POST', '/api/cron/' + encodeURIComponent(name) + '/run'); }
    catch (e) { cronBusy.delete(name); renderCron(); return cronSay('the dashboard is not answering', true); }
    const data = await r.json().catch(() => ({}));
    if (!r.ok) { cronBusy.delete(name); renderCron(); return cronSay(data.error || 'could not start it', true); }
    cronSay('started ' + name + ' — the answer lands in its run log');
    // The tick writes `last_started_ms` before it asks the model anything, so a poll every two
    // seconds shows it begin; the pane also has a slow poll of its own.
    setTimeout(() => loadCron(true), 2500);
    setTimeout(() => loadCron(true), 8000);
  }

  async function toggleJob(name, enabled) {
    const r = await write('POST', '/api/cron/' + encodeURIComponent(name) + '/enabled', { enabled });
    const data = await r.json().catch(() => ({}));
    if (!r.ok) return cronSay(data.error || 'could not change it', true);
    cronSay((enabled ? 'enabled ' : 'disabled ') + name);
    loadCron(true);
  }

  async function removeJob(name) {
    if (!confirm('remove the job “' + name + '”? its run logs stay on disk.')) return;
    const r = await write('DELETE', '/api/cron/' + encodeURIComponent(name));
    const data = await r.json().catch(() => ({}));
    if (!r.ok) return cronSay(data.error || 'could not remove it', true);
    if (cronEditingName === name) cancelForm();
    if (!cronLogsBox.hidden && cronLogsBox.dataset.job === name) cronLogsBox.hidden = true;
    cronSay('removed ' + name);
    loadCron(true);
  }

  async function showLogs(name) {
    const r = await fetch('/api/cron/' + encodeURIComponent(name) + '/logs?limit=3');
    const data = await r.json().catch(() => ({}));
    if (!r.ok) return cronSay(data.error || 'could not read its logs', true);
    cronLogsBox.textContent = '';
    cronLogsBox.dataset.job = name;
    const h = document.createElement('h3');
    h.textContent = 'last runs · ' + name;
    cronLogsBox.appendChild(h);
    const runs = data.runs || [];
    if (!runs.length) {
      const p = document.createElement('div');
      p.className = 'when';
      p.textContent = 'no runs yet — “run” starts one now';
      cronLogsBox.appendChild(p);
    }
    for (const run of runs) {
      const art = document.createElement('article');
      // The body after the tick's header; the header repeats the name, the moment and the schedule,
      // all of which the row above already says. The line is the moment only — putting the answer
      // here would print it twice, once as a summary and again as the first line of the text.
      const body = run.text.indexOf('---\n') >= 0 ? run.text.slice(run.text.indexOf('---\n') + 4) : run.text;
      const at = document.createElement('div');
      at.className = 'at';
      at.textContent = run.at;
      art.appendChild(at);
      const pre = document.createElement('pre');
      pre.textContent = body.trim() || run.answer || '(no output)';
      art.appendChild(pre);
      if (run.truncated) {
        const more = document.createElement('div');
        more.className = 'more';
        more.textContent = 'showing the first ' + body.trim().length + ' of ' + run.chars +
          ' characters — the rest is in ' + run.path;
        art.appendChild(more);
      }
      cronLogsBox.appendChild(art);
    }
    const where = document.createElement('div');
    where.className = 'at';
    where.textContent = data.runs_dir;
    cronLogsBox.appendChild(where);
    cronLogsBox.hidden = false;
  }

  function editJob(job) {
    cronEditingName = job.name;
    crName.value = job.name;
    crName.disabled = true;   // the name is the job's identity in the file the timer reads
    crSchedule.value = job.schedule;
    crPrompt.value = job.prompt;
    crWorkdir.value = job.workdir || '';
    crEditing.textContent = 'editing “' + job.name + '”';
    cronForm.hidden = false;
    cronPane.scrollTop = 0;
    crSchedule.focus();
  }

  function cancelForm() {
    cronEditingName = null;
    cronForm.hidden = true;
    crName.disabled = false;
    cronForm.reset();
    crEditing.textContent = '';
  }

  cronForm.addEventListener('submit', async e => {
    e.preventDefault();
    const body = {
      name: crName.value.trim(),
      schedule: crSchedule.value.trim(),
      prompt: crPrompt.value,
      workdir: crWorkdir.value.trim() || null,
    };
    const r = cronEditingName
      ? await write('PUT', '/api/cron/' + encodeURIComponent(cronEditingName), body)
      : await write('POST', '/api/cron', body);
    const data = await r.json().catch(() => ({}));
    if (!r.ok) return cronSay(data.error || 'could not save it', true);
    cronSay((cronEditingName ? 'saved ' : 'added ') + data.name + ' (' + data.schedule + ')');
    cancelForm();
    loadCron(true);
  });

  document.getElementById('croncancel').addEventListener('click', cancelForm);
  document.getElementById('cronrefresh').addEventListener('click', () => loadCron());
  document.getElementById('cronnew').addEventListener('click', () => {
    cancelForm();
    cronForm.hidden = false;
    crEditing.textContent = '';
    crName.focus();
  });

  // One column, one view. Opening the cron pane used to be one-way: a session row still
  // highlighted, its transcript was written into the DOM, and the pane stayed in front of it —
  // because `main.cron` was a class only the cron button ever cleared, and a reload was the only
  // way back. Every path that decides what `main` shows now calls this, so a view added later
  // cannot forget the one it replaces.
  function setView(view) {
    const cron = view === 'cron';
    const mcp = view === 'mcp';
    const problems = view === 'problems';
    // `#509`: the Bots tab exists only when a bot was declared, so its button and pane can be
    // absent — the view is still asked for, and a page with no bots simply has no such view.
    const bots = view === 'bots' && Boolean(botsBtn);
    // `#171`: the same rule for flares, asked of the ledger instead of the config — a page served
    // before the first run has no button and no pane, and asking for the view is a no-op.
    const flares = view === 'flares' && Boolean(flaresBtn);
    cronOpen = cron;
    mcpOpen = mcp;
    problemsOpen = problems;
    botsOpen = bots;
    flaresOpen = flares;
    cronPane.hidden = !cron;
    mcpPane.hidden = !mcp;
    problemsPane.hidden = !problems;
    if (botsPane) botsPane.hidden = !bots;
    if (flaresPane) flaresPane.hidden = !flares;
    document.querySelector('main').classList.toggle('cron', cron);
    document.querySelector('main').classList.toggle('mcp', mcp);
    document.querySelector('main').classList.toggle('problems', problems);
    document.querySelector('main').classList.toggle('bots', bots);
    document.querySelector('main').classList.toggle('flares', flares);
    cronBtn.classList.toggle('on', cron);
    mcpBtn.classList.toggle('on', mcp);
    problemsBtn.classList.toggle('on', problems);
    if (botsBtn) botsBtn.classList.toggle('on', bots);
    if (flaresBtn) flaresBtn.classList.toggle('on', flares);
    cronBtn.setAttribute('aria-expanded', String(cron));
    mcpBtn.setAttribute('aria-expanded', String(mcp));
    problemsBtn.setAttribute('aria-expanded', String(problems));
    if (botsBtn) botsBtn.setAttribute('aria-expanded', String(bots));
    if (flaresBtn) flaresBtn.setAttribute('aria-expanded', String(flares));
    if (cron) loadCron(); else cancelForm();
    if (mcp) loadMcp(); else cancelMcpForm();
    if (problems) loadProblems();
    if (bots) loadBots();
    if (flares) loadFlares();
  }

  // ---------------------------------------------------------------------------------------
  // `#505`: the problems pane. Every manifest, skill and context warning the loaders produce —
  // the ones this build used to print to stderr and nowhere else. Read-only, re-read on opening
  // and on the refresh button; the badge beside the sidebar button tells you there is something
  // to read without opening anything.
  // ---------------------------------------------------------------------------------------
  const problemsBtn = document.getElementById('problems');
  const problemsPane = document.getElementById('problemspane');
  const problemsRows = document.getElementById('problemsrows');
  const problemsMsg = document.getElementById('problemsmsg');
  const problemsSummary = document.getElementById('problemssummary');
  const problemsChecked = document.getElementById('problemschecked');
  let problemsOpen = false;
  let problemsCount = 0;

  function problemsSay(text, bad) {
    problemsMsg.textContent = text || '';
    problemsMsg.className = bad ? 'bad' : '';
  }

  /// The button carries the count, so a broken skill is visible from any view. `has` colours it
  /// while there is something to fix, and it goes quiet again when the list is empty.
  function problemsBadge(count) {
    problemsCount = count;
    problemsBtn.textContent = count ? 'problems (' + count + ')' : 'problems';
    problemsBtn.classList.toggle('has', count > 0);
  }

  function renderProblems(data) {
    problemsRows.textContent = '';
    const problems = data.problems || [];
    const configError = data.config_error;
    problemsSummary.textContent = data.summary || '';
    problemsBadge(problems.length + (configError ? 1 : 0));
    if (configError) {
      // The loudest row: the config did not load, so the loaders below it did not really run.
      const tr = document.createElement('tr');
      const kind = document.createElement('td');
      kind.className = 'kind';
      kind.textContent = 'config';
      const what = document.createElement('td');
      what.className = 'what';
      what.textContent = configError;
      const where = document.createElement('td');
      where.className = 'path';
      tr.appendChild(kind); tr.appendChild(what); tr.appendChild(where);
      problemsRows.appendChild(tr);
    }
    if (!problems.length && !configError) {
      const tr = document.createElement('tr');
      const td = document.createElement('td');
      td.colSpan = 3;
      td.className = 'none';
      td.textContent = data.summary || 'nothing to fix';
      tr.appendChild(td);
      problemsRows.appendChild(tr);
    }
    for (const p of problems) {
      const tr = document.createElement('tr');
      const kind = document.createElement('td');
      kind.className = 'kind';
      kind.textContent = p.kind || '';
      const what = document.createElement('td');
      what.className = 'what';
      what.textContent = p.text || '';
      const where = document.createElement('td');
      where.className = 'path';
      where.textContent = p.path || '';
      tr.appendChild(kind); tr.appendChild(what); tr.appendChild(where);
      problemsRows.appendChild(tr);
    }
    // What was looked at and found nothing wrong with: without it, an empty pane is
    // indistinguishable from a search that never happened.
    const checked = data.checked || [];
    problemsChecked.textContent = checked.length
      ? 'checked:\n  ' + checked.join('\n  ')
      : 'nothing to check — no plugin directory and no skills root was found';
  }

  async function loadProblems(quiet) {
    let r;
    try { r = await fetch('/api/problems'); } catch (e) {
      if (!quiet) problemsSay('the dashboard is not answering', true);
      return;
    }
    if (r.status === 401) return location.reload();
    const data = await r.json().catch(() => ({}));
    if (!r.ok) {
      problemsSay(data.error || ('could not read the loaders\' report (' + r.status + ')'), true);
      return;
    }
    if (!quiet) problemsSay('');
    renderProblems(data);
  }

  function showProblems(open) { setView(open ? 'problems' : 'session'); }

  problemsBtn.addEventListener('click', () => showProblems(!problemsOpen));
  document.getElementById('problemsrefresh').addEventListener('click', () => loadProblems());

  // ---------------------------------------------------------------------------------------
  // `#509`: the Bots tab. A bot is a declaration in `[bots]` plus one long-lived conversation,
  // and this pane lists the *identities*, not the sessions: name, the lane it answers on, when it
  // last spoke, and how much it has said. Opening one loads its conversation into the ordinary
  // transcript view; the send path needs no second field, because the session row's own `origin`
  // is what makes that turn run on the bot's agent (its instructions, its memory, its skills).
  //
  // Every button calls a route that calls the store method the CLI calls, so a rename here is the
  // rename `eclipse sessions rename` performs. The declaration itself is not editable from this
  // pane: a bot's name is its key in `[bots]`, and a page that could invent one would be a second
  // config file.
  //
  // `var`, not `let`: `setView` above mentions these, and a page with no bots has no buttons to
  // find. A hoisted undefined is "there are no bots here", which is the truth; a TDZ throw on a
  // dashboard with no bots would be the one thing this tab must never do.
  // ---------------------------------------------------------------------------------------
  var botsBtn = document.getElementById('bots');
  var botsPane = document.getElementById('botspane');
  var botsRows = document.getElementById('botsrows');
  var botsMsg = document.getElementById('botsmsg');
  var botsFile = document.getElementById('botsfile');
  var botsPrompt = document.getElementById('botsprompt');
  var botsOpen = false;

  function botsSay(text, bad) {
    if (!botsMsg) return;
    botsMsg.textContent = text || '';
    botsMsg.className = bad ? 'bad' : '';
  }

  async function botWrite(name, act, body) {
    const url = '/api/bots/' + encodeURIComponent(name) + '/' + act;
    let r;
    try { r = await post(url, body); }
    catch (e) { botsSay(String(e), true); return null; }
    if (r.status === 401) { location.reload(); return null; }
    const data = await r.json().catch(() => ({}));
    if (!r.ok) { botsSay(data.error || ('HTTP ' + r.status), true); return null; }
    return data;
  }

  function renderBots(bots) {
    if (!botsRows) return;
    botsRows.textContent = '';
    if (botsPrompt) { botsPrompt.hidden = true; botsPrompt.textContent = ''; }
    if (!bots.length) {
      const tr = document.createElement('tr');
      const td = document.createElement('td');
      td.colSpan = 5;
      td.className = 'when';
      td.textContent = 'no bots are declared — add a [bots.<name>] section to the config file';
      tr.appendChild(td);
      botsRows.appendChild(tr);
      return;
    }
    if (botsFile) botsFile.textContent = bots.length + ' declared';
    for (const bot of bots) {
      const tr = document.createElement('tr');
      tr.dataset.name = bot.name;
      const name = document.createElement('td');
      name.className = 'name';
      name.textContent = bot.name;
      const lane = document.createElement('td');
      lane.textContent = bot.lane;
      const last = document.createElement('td');
      last.textContent = bot.last_activity_ms ? agoWords(bot.last_activity_ms) : 'never';
      const said = document.createElement('td');
      if (bot.problem) {
        // A declaration that cannot run says why, in the row, instead of offering a button that
        // would answer 503.
        said.textContent = bot.problem;
        said.className = 'bad';
      } else {
        said.textContent = bot.messages + ' msg' + (bot.messages === 1 ? '' : 's') +
          (bot.sessions > 1 ? ' · ' + bot.sessions + ' conversations' : '') +
          (bot.archived ? ' · cleared' : '');
      }
      const acts = document.createElement('td');
      acts.className = 'acts';
      if (!bot.problem) {
        acts.appendChild(rowButton('open', 'open this bot\'s conversation',
          () => openBot(bot.name), 'go'));
        acts.appendChild(rowButton('rename', 'name this bot\'s conversation',
          () => renameBot(bot.name)));
        acts.appendChild(rowButton('clear', 'file this conversation away and start a fresh one',
          () => clearBot(bot.name), 'bad'));
      }
      acts.appendChild(rowButton('prompt', 'the instructions this bot runs with',
        () => showBotPrompt(bot.name)));
      tr.appendChild(name); tr.appendChild(lane); tr.appendChild(last);
      tr.appendChild(said); tr.appendChild(acts);
      botsRows.appendChild(tr);
    }
  }

  async function loadBots(quiet) {
    if (!botsRows) return;
    let r;
    try { r = await fetch('/api/bots'); } catch (e) {
      if (!quiet) botsSay('the dashboard is not answering', true);
      return;
    }
    if (r.status === 401) return location.reload();
    const data = await r.json().catch(() => ([]));
    if (!r.ok) {
      botsSay(data.error || ('could not read the bots (' + r.status + ')'), true);
      return;
    }
    if (!quiet) botsSay('');
    renderBots(data);
  }

  async function openBot(name) {
    botsSay('opening ' + name + '…');
    const data = await botWrite(name, 'open');
    if (!data) return;
    botsSay('');
    await loadSession(data.session_id);
    await refreshSessions();
  }

  async function renameBot(name) {
    const typed = window.prompt('Title for this bot\'s conversation', name);
    if (typed === null) return;
    const title = typed.trim();
    if (!title) return;
    const data = await botWrite(name, 'rename', { title });
    if (!data) return;
    botsSay('renamed the ' + name + ' conversation to “' + title + '”');
    await loadBots(true);
    await refreshSessions();
  }

  async function clearBot(name) {
    if (!window.confirm('File the ' + name + ' conversation away and start a fresh one? The ' +
      'transcript stays in the archive; the bot keeps its identity.')) return;
    const data = await botWrite(name, 'clear');
    if (!data) return;
    botsSay('cleared ' + name + ' · ' + data.archived + ' conversation(s) archived');
    await loadBots(true);
    await refreshSessions();
  }

  async function showBotPrompt(name) {
    let r;
    try { r = await fetch('/api/bots/' + encodeURIComponent(name) + '/prompt'); }
    catch (e) { return botsSay(String(e), true); }
    if (r.status === 401) return location.reload();
    const data = await r.json().catch(() => ({}));
    if (!r.ok) return botsSay(data.error || ('could not read the prompt (' + r.status + ')'), true);
    if (!botsPrompt) return;
    botsPrompt.textContent = '';
    const h = document.createElement('h3');
    h.textContent = 'prompt · ' + data.name +
      (data.instructions && data.instructions.path ? ' · ' + data.instructions.path : '');
    botsPrompt.appendChild(h);
    const pre = document.createElement('pre');
    if (data.instructions && data.instructions.body) {
      pre.textContent = data.instructions.body;
    } else if (data.why) {
      pre.textContent = data.why;
    } else {
      pre.textContent = 'this bot declares no instructions — it runs on the agent\'s own prompt, ' +
        'with its own memory and the skills it named';
    }
    botsPrompt.appendChild(pre);
    const facts = document.createElement('h3');
    facts.textContent = 'declaration';
    botsPrompt.appendChild(facts);
    const decl = document.createElement('pre');
    const skills = data.skills ? (data.skills.join(', ') || '(none)') : '(every root)';
    decl.textContent = 'lane: ' + (data.adapter || 'web') +
      '\nmemory: ' + (data.memory || '(none)') +
      '\nskills: ' + skills +
      (data.problem ? '\nproblem: ' + data.problem : '');
    botsPrompt.appendChild(decl);
    botsPrompt.hidden = false;
  }

  if (botsBtn) {
    botsBtn.addEventListener('click', () => setView(botsOpen ? 'session' : 'bots'));
    const botsRefresh = document.getElementById('botsrefresh');
    if (botsRefresh) botsRefresh.addEventListener('click', () => loadBots());
  }

  // ---------------------------------------------------------------------------------------
  // `#171`: the Flares tab. A run is one task split across N read-only agents, and this pane is
  // the ledger `eclipse flares list` prints: newest first, state, age, routes, job count, cost.
  // Expanding a run lists its children; a child that has a session opens in the ordinary
  // transcript view, because a flare's session is a session — `loadSession` is the one renderer,
  // and a second one would be a second way for a transcript to be wrong.
  //
  // There is no poll here, unlike the cron pane above: a re-render rebuilds the rows and would
  // close the children a person just opened. The ledger only moves while a run is in flight, and
  // the refresh button is one click that does not claim to have read more recently than it did.
  //
  // `var` again, for the reason the Bots block gives: `setView` mentions these, and a page served
  // before the first run has none of the elements. A hoisted undefined is "there is no tab here".
  // ---------------------------------------------------------------------------------------
  var flaresBtn = document.getElementById('flares');
  var flaresPane = document.getElementById('flarespane');
  var flaresRows = document.getElementById('flarerows');
  var flaresMsg = document.getElementById('flaresmsg');
  var flaresFile = document.getElementById('flaresfile');
  var flaresOpen = false;

  function flaresSay(text, bad) {
    if (!flaresMsg) return;
    flaresMsg.textContent = text || '';
    flaresMsg.className = bad ? 'bad' : '';
  }

  // `?`, never `0`: a count that never arrived is not a free run. `count_tokens` on the command
  // line makes the same call, and the two surfaces read the same ledger row.
  function flareTokens(n) {
    return (typeof n === 'number' && isFinite(n) && n >= 0) ? tokens(n) : '?';
  }

  function flareCost(iters, prompt, completion) {
    return iters + (iters === 1 ? ' iteration' : ' iterations') +
      ' · ' + flareTokens(prompt) + ' prompt / ' + flareTokens(completion) + ' completion';
  }

  function flareSpan(text, cls) {
    const s = document.createElement('span');
    s.className = cls;
    s.textContent = text;
    return s;
  }

  function renderFlares(runs) {
    if (!flaresRows) return;
    flaresRows.textContent = '';
    if (flaresFile) {
      // The listing asks for the newest 50. Saying so when exactly 50 came back is true whether
      // or not there are older ones, which is the only honest way to write it without a count.
      flaresFile.textContent = runs.length + (runs.length === 1 ? ' run' : ' runs') +
        (runs.length === 50 ? ' · the newest 50' : '');
    }
    if (!runs.length) {
      const tr = document.createElement('tr');
      const td = cronCell(document.createElement('td'),
        'no flare runs on the ledger — `eclipse flares run "…"` starts one', 'when');
      td.colSpan = 7;
      tr.appendChild(td);
      flaresRows.appendChild(tr);
      return;
    }
    for (const run of runs) {
      const tr = document.createElement('tr');
      tr.dataset.run = run.id;
      // The id is the handle a person types into `eclipse flares show`, so it names the row and
      // the task sits under it: a run is recognised by what it was asked to do.
      const id = flareCell(run.id, 'run');
      if (run.task) {
        const task = flareSpan(run.task, 'task');
        task.title = run.task;
        id.appendChild(task);
      }
      const age = flareCell(ago(run.started_ms), 'age');
      age.title = run.finished_ms
        ? 'started ' + ago(run.started_ms) + ', finished ' + ago(run.finished_ms)
        : 'started ' + ago(run.started_ms) + ', still going';
      const routes = flareCell(run.routes.join(', ') || '?', 'routes');
      if (run.parent) routes.title = 'led from session ' + run.parent;
      const cost = flareCell(
        flareCost(run.iterations, run.prompt_tokens, run.completion_tokens), 'cost');
      if (run.running) {
        cost.title = 'a run still going has counted only the children that finished';
      }
      const acts = document.createElement('td');
      acts.className = 'acts';
      const children = rowButton('children',
        'the flares this run started — each one opens its own transcript',
        () => toggleFlare(run, tr, children), 'go');
      children.setAttribute('aria-expanded', 'false');
      acts.appendChild(children);
      if (run.running) {
        acts.appendChild(rowButton('cancel',
          'drop the queued flares and stop the running ones at their next boundary',
          () => cancelFlare(run), 'bad'));
      }
      tr.appendChild(id);
      tr.appendChild(flareCell(run.state, 'state ' + run.state));
      tr.appendChild(age);
      tr.appendChild(routes);
      tr.appendChild(flareCell(String(run.jobs), 'jobs'));
      tr.appendChild(cost);
      tr.appendChild(acts);
      flaresRows.appendChild(tr);
    }
  }

  function flareCell(text, cls) {
    return cronCell(document.createElement('td'), text, cls);
  }

  // The expansion is a row of this table, placed under the run it belongs to, so the run stays in
  // view while its children are read. It is built once and then shown and hidden: re-fetching on
  // every toggle would be a request per click to answer the same question.
  async function toggleFlare(run, tr, btn) {
    const shown = tr.nextElementSibling;
    if (shown && shown.classList.contains('jobs')) {
      shown.hidden = !shown.hidden;
      btn.textContent = shown.hidden ? 'children' : 'hide';
      btn.setAttribute('aria-expanded', String(!shown.hidden));
      return;
    }
    btn.disabled = true;
    let r;
    try { r = await fetch('/api/flares/' + encodeURIComponent(run.id)); }
    catch (e) { btn.disabled = false; return flaresSay(String(e), true); }
    btn.disabled = false;
    if (r.status === 401) return location.reload();
    const data = await r.json().catch(() => ({}));
    if (!r.ok) {
      flaresSay(data.error || ('could not read the run (' + r.status + ')'), true);
      return;
    }
    const row = document.createElement('tr');
    row.className = 'jobs';
    const cell = document.createElement('td');
    cell.colSpan = 7;
    cell.appendChild(flareJobsList(data.jobs || []));
    row.appendChild(cell);
    tr.insertAdjacentElement('afterend', row);
    btn.textContent = 'hide';
    btn.setAttribute('aria-expanded', 'true');
  }

  function flareJobsList(jobs) {
    const box = document.createElement('div');
    if (!jobs.length) {
      const empty = flareSpan('this run has no children on the ledger yet — a cancelled run ' +
        'stops before its queue empties', 'empty');
      box.appendChild(empty);
      return box;
    }
    for (const job of jobs) {
      const line = document.createElement('div');
      line.className = 'job';
      line.appendChild(flareSpan(job.n + '.', 'n'));
      line.appendChild(flareSpan(job.state, 'state ' + job.state));
      line.appendChild(flareSpan(job.route, 'route'));
      if (job.session_id) {
        line.appendChild(rowButton('open session',
          'open this flare\'s transcript — the same view every session opens in',
          () => loadSession(job.session_id), 'go'));
        const cost = document.createElement('small');
        cost.textContent = flareCost(job.iterations, job.prompt_tokens, job.completion_tokens);
        line.appendChild(cost);
      } else {
        // A dropped child never started: no session to open and no cost to show, so the row *is*
        // its reason. `why` is the line it ended with, and a blank would say nothing at all.
        const why = document.createElement('small');
        why.className = 'why';
        why.textContent = job.why || 'never ran — no session, no cost';
        line.appendChild(why);
      }
      // A failed child has both: a transcript that says what it managed, and the line it died on.
      if (job.session_id && job.why) {
        const why = document.createElement('small');
        why.className = 'why';
        why.textContent = job.why;
        line.appendChild(why);
      }
      box.appendChild(line);
    }
    return box;
  }

  async function loadFlares(quiet) {
    if (!flaresRows) return;
    let r;
    try { r = await fetch('/api/flares'); } catch (e) {
      if (!quiet) flaresSay('the dashboard is not answering', true);
      return;
    }
    if (r.status === 401) return location.reload();
    const data = await r.json().catch(() => ([]));
    if (!r.ok) {
      flaresSay(data.error || ('could not read the flare runs (' + r.status + ')'), true);
      return;
    }
    if (!quiet) flaresSay('');
    renderFlares(data);
  }

  async function cancelFlare(run) {
    if (!window.confirm('Ask run ' + run.id + ' to stop? Queued flares are dropped before they ' +
      'start; a running one ends at its next boundary.')) return;
    flaresSay('asking ' + run.id + ' to stop…');
    let r;
    try { r = await post('/api/flares/' + encodeURIComponent(run.id) + '/cancel'); }
    catch (e) { return flaresSay(String(e), true); }
    if (r.status === 401) return location.reload();
    const data = await r.json().catch(() => ({}));
    if (!r.ok) return flaresSay(data.error || ('HTTP ' + r.status), true);
    flaresSay(data.note || 'cancel requested');
    await loadFlares(true);
  }

  if (flaresBtn) {
    flaresBtn.addEventListener('click', () => setView(flaresOpen ? 'session' : 'flares'));
    const flaresRefresh = document.getElementById('flaresrefresh');
    if (flaresRefresh) flaresRefresh.addEventListener('click', () => loadFlares());
  }

  function showCron(open) { setView(open ? 'cron' : 'session'); }

  cronBtn.addEventListener('click', () => showCron(!cronOpen));
  // While the pane is open: the same two files re-read every ten seconds, so a job that fired on
  // its schedule while you watched shows up without a reload.
  setInterval(() => { if (cronOpen) loadCron(true); }, 10000);

  // ---------------------------------------------------------------------------------------
  // MCP servers. The pane is a viewer and an editor of the same `[[mcp]]` entries the CLI
  // lists: every button here calls a route that calls a `config::mcp_*` writer, and the page
  // paraphrases nothing — a refusal shown here is the writer's own sentence, naming the line
  // or the field. There is no ten-second poll on purpose: listing *starts* every server it
  // shows (a row that says "12 tools" only ever comes from asking), so the rows refresh on a
  // click and after a write, not behind the clock.
  // ---------------------------------------------------------------------------------------
  const mcpBtn = document.getElementById('mcp');
  const mcpPane = document.getElementById('mcppane');
  const mcpRows = document.getElementById('mcprows');
  const mcpMsg = document.getElementById('mcpmsg');
  const mcpFile = document.getElementById('mcpfile');
  const mcpForm = document.getElementById('mcpform');
  const mpName = document.getElementById('mp-name');
  const mpTransport = document.getElementById('mp-transport');
  const mpUrl = document.getElementById('mp-url');
  const mpCommand = document.getElementById('mp-command');
  const mpArgs = document.getElementById('mp-args');
  const mpPrefix = document.getElementById('mp-prefix');
  const mpPolicy = document.getElementById('mp-policy');
  const mpToken = document.getElementById('mp-token');
  const mpEditing = document.getElementById('mpediting');
  const mcpSave = document.getElementById('mcpsave');
  let mcpOpen = false;
  let mcpServers = [];
  let mcpBusy = new Set();   // server names whose test has not come back yet
  let mcpEditingName = null; // null = the form is creating, a name = it is editing that entry

  function mcpSay(text, bad) {
    mcpMsg.textContent = text || '';
    mcpMsg.className = bad ? 'bad' : '';
  }

  function mcpCell(td, text, cls) {
    td.textContent = text;
    if (cls) td.className = cls;
    return td;
  }

  // A fresh row from any route replaces the one it describes: the row is what the file and
  // the server now say, so the page adopts it rather than keeping its own copy.
  function replaceServer(row) {
    const i = mcpServers.findIndex(s => s.name === row.name);
    if (i >= 0) mcpServers[i] = row;
    else mcpServers.push(row);
    renderMcp();
  }

  function renderMcp() {
    mcpRows.textContent = '';
    if (!mcpServers.length) {
      const tr = document.createElement('tr');
      const td = document.createElement('td');
      td.colSpan = 6;
      td.className = 'when';
      td.textContent = 'no MCP server is configured — “+ add server” writes the first entry';
      tr.appendChild(td);
      mcpRows.appendChild(tr);
      return;
    }
    for (const s of mcpServers) {
      const tr = document.createElement('tr');
      if (s.disabled) tr.className = 'off';
      tr.appendChild(mcpCell(document.createElement('td'), s.name, 'name'));
      tr.appendChild(mcpCell(document.createElement('td'), s.source, 'when'));
      tr.appendChild(mcpCell(document.createElement('td'),
        s.disabled ? 'off' : (s.error ? 'failed' : String(s.tools)), 'when'));
      tr.appendChild(mcpCell(document.createElement('td'), s.command, 'cmd'));
      // `#517`: whether the token variable resolves is a fact about this machine, so it is in the
      // row — not only in what `test` answers. A word, never the value.
      const tokenTd = document.createElement('td');
      tokenTd.className = 'token' + (s.token === 'unset' ? ' unset' : '');
      if (s.token_env) {
        tokenTd.textContent = s.token_env + ': ' + s.token;
        tokenTd.title = s.token === 'unset'
          ? s.token_env + ' is set neither in the environment nor in .env, so this server cannot authenticate'
          : 'the token is read from ' + (s.token === '.env' ? 'the .env file' : 'the environment');
      } else {
        tokenTd.textContent = '—';
        tokenTd.title = 'the entry asks for no token';
      }
      tr.appendChild(tokenTd);
      // The state cell answers "does it work": off, failed (with the reason as the title),
      // ok — or, once `test` has run, what the server actually reported.
      let state = s.disabled ? 'off' : (s.error ? 'failed' : 'ok');
      if (s.tested && !s.disabled && !s.error) {
        state = 'protocol ' + (s.protocol || '(not reported)') + ' · ' + s.tools + ' tool(s)';
      }
      const stateTd = mcpCell(document.createElement('td'), state,
        'state ' + (s.error ? 'failed' : s.disabled ? '' : 'ok'));
      if (s.error) stateTd.title = s.error;
      tr.appendChild(stateTd);
      const acts = document.createElement('td');
      acts.className = 'acts';
      const testing = mcpBusy.has(s.name);
      const test = rowButton(testing ? 'testing…' : 'test',
        'start it and report what it answers: the protocol, the tool count, or the reason it failed',
        () => testServer(s.name), 'go');
      test.disabled = testing || Boolean(s.disabled);
      acts.appendChild(test);
      acts.appendChild(rowButton('edit',
        'change this entry — the form opens with what the file says',
        () => editServer(s)));
      acts.appendChild(rowButton(s.disabled ? 'on' : 'off',
        s.disabled ? 'clear disabled, so the next run starts it' : 'write disabled = true; the entry stays',
        () => toggleServer(s.name, s.disabled)));
      acts.appendChild(rowButton('remove', 'delete the entry from config.toml',
        () => removeServer(s.name), 'bad'));
      tr.appendChild(acts);
      mcpRows.appendChild(tr);
    }
  }

  async function loadMcp(quiet) {
    let r;
    try { r = await fetch('/api/mcp'); } catch (e) { mcpSay('the dashboard is not answering', true); return; }
    if (r.status === 401) return location.reload();
    const data = await r.json().catch(() => ({}));
    if (!r.ok) { mcpSay(data.error || ('could not read the entries (' + r.status + ')'), true); return; }
    mcpServers = data.servers || [];
    mcpFile.textContent = data.config_path || '';
    renderMcp();
    // A shadowed manifest entry is not a server's row, so it rides here — the same warnings
    // `eclipse mcp list` prints above the table.
    const problems = data.problems || [];
    if (problems.length) mcpSay(problems.join(' · '));
    else if (!quiet) mcpSay('');
  }

  async function toggleServer(name, wasDisabled) {
    const r = await write('POST', '/api/mcp/' + encodeURIComponent(name) + '/enabled',
      { enabled: wasDisabled });
    const data = await r.json().catch(() => ({}));
    if (!r.ok) return mcpSay(data.error || 'could not change it', true);
    replaceServer(data);
    mcpSay((wasDisabled ? 'enabled ' : 'disabled ') + name);
  }

  async function testServer(name) {
    mcpBusy.add(name);
    renderMcp();
    let r;
    try { r = await write('POST', '/api/mcp/' + encodeURIComponent(name) + '/test'); }
    catch (e) { mcpBusy.delete(name); renderMcp(); return mcpSay('the dashboard is not answering', true); }
    const data = await r.json().catch(() => ({}));
    mcpBusy.delete(name);
    if (!r.ok) { renderMcp(); return mcpSay(data.error || 'could not run the test', true); }
    data.tested = true;
    replaceServer(data);
    mcpSay(data.error ? name + ': ' + data.error :
      name + ' speaks protocol ' + (data.protocol || '(not reported)') +
      ' and lists ' + data.tools + ' tool(s)');
  }

  async function removeServer(name) {
    if (!confirm('remove the entry “' + name + '”? the other entries and their comments stay.')) return;
    const r = await write('DELETE', '/api/mcp/' + encodeURIComponent(name));
    const data = await r.json().catch(() => ({}));
    if (!r.ok) return mcpSay(data.error || 'could not remove it', true);
    mcpServers = mcpServers.filter(s => s.name !== name);
    if (mpName.value.trim() === name) cancelMcpForm();
    mcpSay('removed ' + name);
    renderMcp();
  }

  // The form opens with what the file says (`#517`). The name is the entry's identity, so it is
  // read-only while editing: an edit does not rename — the route refuses one, and the page does not
  // offer it.
  function editServer(s) {
    mcpEditingName = s.name;
    mpName.value = s.name;
    mpName.readOnly = true;
    mpTransport.value = s.transport || '';
    mpUrl.value = s.url || '';
    mpCommand.value = s.program || '';
    mpArgs.value = (s.args || []).join(' ');
    mpPrefix.value = s.prefix || '';
    mpPolicy.value = s.policy || '';
    mpToken.value = s.token_env || '';
    mpEditing.textContent = 'editing “' + s.name + '”';
    mcpSave.textContent = 'save';
    mcpForm.hidden = false;
    mcpPane.scrollTop = 0;
    mpUrl.focus();
  }

  function cancelMcpForm() {
    mcpEditingName = null;
    mcpForm.hidden = true;
    mcpForm.reset();
    mpName.readOnly = false;
    mpEditing.textContent = '';
    mcpSave.textContent = 'save';
  }

  mcpForm.addEventListener('submit', async e => {
    e.preventDefault();
    const args = mpArgs.value.trim();
    const body = {
      name: mpName.value.trim(),
      transport: mpTransport.value || null,
      url: mpUrl.value.trim() || null,
      command: mpCommand.value.trim() || null,
      args: args ? args.split(/\s+/) : null,
      prefix: mpPrefix.value.trim() || null,
      policy: mpPolicy.value || null,
      token_env: mpToken.value.trim() || null,
    };
    const editing = mcpEditingName;
    const r = await write(editing ? 'PUT' : 'POST',
      editing ? '/api/mcp/' + encodeURIComponent(editing) : '/api/mcp', body);
    const data = await r.json().catch(() => ({}));
    if (!r.ok) return mcpSay(data.error || 'could not save it', true);
    cancelMcpForm();
    replaceServer(data);
    mcpSay((editing ? 'updated ' : 'added ') + data.name + ' (' + data.source + ')');
  });

  document.getElementById('mcpcancel').addEventListener('click', cancelMcpForm);
  document.getElementById('mcprefresh').addEventListener('click', () => loadMcp());
  document.getElementById('mcpnew').addEventListener('click', () => {
    cancelMcpForm();
    mcpForm.hidden = false;
    mpName.focus();
  });

  function showMcp(open) { setView(open ? 'mcp' : 'session'); }

  mcpBtn.addEventListener('click', () => showMcp(!mcpOpen));

  // The server-rendered rows carry no actions (no JavaScript ran to build them), so the list is
  // read back once on load and from then on it is the API's.
  refreshSessions();
  // `#505`: the count on the sidebar button, so a broken skill is visible without opening the
  // pane. Quiet: it must not put an error line on a dashboard that opened fine.
  loadProblems(true);
})();
</script>
</body>
</html>