cctop 0.16.3

An htop-like terminal monitor for AI coding agent sessions on Linux (Claude Code, Codex, Cursor, Devin, Gemini CLI, OpenCode, Pi, Windsurf)
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
<title>cctop — session report</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark">
<link rel="icon" href="/favicon.svg" type="image/svg+xml">
<!-- The dark --bg: a page watched in a dark terminal's browser should not
     flash a light chrome around it. -->
<meta name="theme-color" content="#16151a">
<style>__CCTOP_CSS__
  .back { font-size: 13px; color: var(--dim); text-decoration: none; }
  .back:hover { color: var(--accent); }

  .subject { margin-bottom: 18px; }
  .subject h2 { font-size: 20px; margin-bottom: 4px; }
  .subject .where { color: var(--dim); font-size: 13px; display: flex; gap: 10px; flex-wrap: wrap; align-items: center; }

  /* The green end of the pill range. common.css carries warn and bad because
     the dashboard's live state is a dot and only the problems are pills; here
     the state itself is a pill, so "working" needs a colour too. */
  .pill.ok { color: var(--green); border-color: var(--green); }

  .tiles { display: grid; gap: 10px; grid-template-columns: repeat(auto-fit, minmax(132px, 1fr)); margin-bottom: 22px; }
  .tile { padding: 12px 14px; }
  .tile .k { font-size: 11px; text-transform: uppercase; letter-spacing: .06em; color: var(--faint); }
  .tile .v { font-family: var(--mono); font-size: 21px; font-weight: 600; margin-top: 3px; font-variant-numeric: tabular-nums; }
  .tile .n { font-size: 11px; color: var(--faint); margin-top: 2px; }
  .tile.bad .v { color: var(--red); }
  .tile.warn .v { color: var(--amber); }

  section.block { margin-bottom: 26px; }
  section.block > h3 { font-size: 13px; text-transform: uppercase; letter-spacing: .06em;
                       color: var(--faint); margin-bottom: 9px; }
  section.block > .note { font-size: 12px; color: var(--faint); margin: -4px 0 9px; max-width: 62ch; }
  .pad { padding: 12px 14px; }

  /* The one finding worth leading with, so it is styled like one. */
  .failure { border-top: 1px solid var(--line); padding: 11px 14px; }
  .failure:first-child { border-top: 0; }
  .failure .head { display: flex; gap: 9px; align-items: baseline; flex-wrap: wrap; }
  .failure .count { font-family: var(--mono); font-weight: 600; color: var(--red); }
  .failure .tool { font-family: var(--mono); font-size: 12px; color: var(--dim); }
  .failure pre { margin: 6px 0 0; font-family: var(--mono); font-size: 12px; color: var(--ink);
                 background: var(--bg); border: 1px solid var(--line); border-radius: 6px;
                 padding: 8px 10px; overflow-x: auto; white-space: pre-wrap; word-break: break-word; }

  /* Stacked proportion bar for the context breakdown. */
  .stack { display: flex; height: 22px; border-radius: 6px; overflow: hidden; background: var(--line); }
  .stack span { display: block; height: 100%; min-width: 0; }
  .legend { display: flex; flex-wrap: wrap; gap: 10px 18px; margin-top: 11px; font-size: 12px; }
  .legend .item { display: flex; align-items: center; gap: 6px; }
  .legend .swatch { width: 9px; height: 9px; border-radius: 2px; flex: 0 0 9px; }
  .legend .amt { color: var(--faint); font-family: var(--mono); }

  svg { display: block; max-width: 100%; }
  .axis { fill: var(--faint); font-size: 10px; font-family: var(--mono); }
  .gridline { stroke: var(--line); stroke-width: 1; }

  .files { columns: 2 260px; column-gap: 22px; font-family: var(--mono); font-size: 12px; }
  .files div { break-inside: avoid; color: var(--dim); padding: 1px 0; overflow-wrap: anywhere; }
  .files .plus { color: var(--green); }
  .files .minus { color: var(--red); }

  /* One file's edits. <details> rather than scripted toggling: it opens with
     no JavaScript, it is keyboard-reachable, and the browser already knows
     how to do it. */
  .diff { border-top: 1px solid var(--line); }
  .diff:first-child { border-top: 0; }
  .diff > summary {
    padding: 9px 14px; cursor: pointer; display: flex; gap: 10px;
    align-items: baseline; flex-wrap: wrap; list-style: none;
  }
  .diff > summary::-webkit-details-marker { display: none; }
  .diff > summary::before { content: ""; color: var(--faint); flex: 0 0 auto; }
  .diff[open] > summary::before { content: ""; }
  .diff > summary:hover { background: color-mix(in srgb, var(--accent) 7%, transparent); }
  .diff .path { font-family: var(--mono); font-size: 12.5px; overflow-wrap: anywhere; }
  .diff .plus { color: var(--green); font-family: var(--mono); font-size: 12px; }
  .diff .minus { color: var(--red); font-family: var(--mono); font-size: 12px; }
  .diff pre {
    margin: 0; padding: 8px 0 12px; font-family: var(--mono); font-size: 12px;
    line-height: 1.45; overflow-x: auto;
  }
  .diff pre span { display: block; padding: 0 14px; white-space: pre; }
  .diff pre .add { background: color-mix(in srgb, var(--green) 14%, transparent); }
  .diff pre .del { background: color-mix(in srgb, var(--red) 14%, transparent); }
  .diff pre .meta { color: var(--faint); }

  /* The full call log. Capped in height so it is a panel rather than the rest
     of the page, and scrolled inside itself. */
  .log { max-height: 60vh; overflow-y: auto; }
  .log table { font-size: 12px; }
  .log thead th { position: sticky; top: 0; background: var(--panel); z-index: 1; padding-top: 10px; }
  .log td { padding: 4px 10px; }
  .log tr.bad td { background: color-mix(in srgb, var(--red) 9%, transparent); }
  .log .when { color: var(--faint); white-space: nowrap; font-family: var(--mono); }

  /* --- the views -------------------------------------------------------- */

  /* One page, four things to read. Buttons rather than links: switching view
     should not be a navigation, because the report behind it was expensive to
     build and going back would build it again. */
  nav.views { display: flex; gap: 6px; flex-wrap: wrap; margin: 0 0 18px; }
  nav.views button {
    font: inherit; font-size: 13px; padding: 5px 12px; border-radius: 99px;
    border: 1px solid var(--line); background: var(--panel); color: var(--dim);
    cursor: pointer;
  }
  nav.views button:hover { color: var(--ink); }
  nav.views button[aria-selected="true"] { color: var(--panel); background: var(--accent); border-color: var(--accent); }
  nav.views button .n { font-family: var(--mono); font-size: 11px; opacity: .75; margin-left: 5px; }
  /* Copy reads what is already on the page rather than switching it, so it is
     not a view — pushed to the far end to keep the four views at the left. */
  nav.views button.copymd { margin-left: auto; }

  /* --- the conversation, and the terminal beside it ---------------------- */

  /* One column until the terminal is asked for, two after. The conversation
     keeps the left because that is what the page is for; the terminal sticks
     to the viewport, so scrolling a long transcript does not scroll the thing
     you opened it to watch. */
  .split { display: grid; gap: 16px; grid-template-columns: minmax(0, 1fr); align-items: start; }
  .split.with-term { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); }
  .termside { display: flex; flex-direction: column; min-width: 0;
              position: sticky; top: 12px; }
  /* `display` beats the `hidden` attribute, so closed has to be said in CSS —
     without this the closed column keeps a screen's worth of height. */
  .termside[hidden] { display: none; }
  .termside .head { display: flex; align-items: center; gap: 10px; margin-bottom: 7px;
                    font-size: 12px; color: var(--faint); }
  .termside .head button {
    font: inherit; font-size: 12px; margin-left: auto; padding: 3px 10px; border-radius: 99px;
    border: 1px solid var(--line); background: var(--panel); color: var(--dim); cursor: pointer;
  }
  .termside .head button:hover { color: var(--accent); border-color: var(--accent); }
  .termcard { display: flex; flex-direction: column; gap: 8px; align-items: flex-start; }
  .termcard .open {
    font-size: 13px; padding: 6px 14px; border-radius: 7px; text-decoration: none;
    border: 1px solid var(--accent); background: var(--accent); color: var(--panel);
  }
  .termcard .why { font-size: 12px; color: var(--faint); }
  .termcard .why.bad { color: var(--amber); }
  .termside .note { font-size: 12px; color: var(--amber); margin-top: 7px; }
  nav.views button.toggle[aria-pressed="true"] { color: var(--accent); border-color: var(--accent); }
  nav.views button:disabled { color: var(--faint); cursor: default; }

  /* Two columns need a screen. On a phone the terminal goes under the
     conversation at a readable height rather than into a 40-column strip. */
  @media (max-width: 900px) {
    .split.with-term { grid-template-columns: minmax(0, 1fr); }
    .termside { position: static; }
  }

  /* --- acting on the session -------------------------------------------- */

  .acts { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; margin-top: 12px; }
  .acts button, .acts select {
    font: inherit; font-size: 13px; padding: 5px 11px; border-radius: 7px;
    border: 1px solid var(--line); background: var(--panel); color: var(--ink); cursor: pointer;
  }
  .acts button:hover:enabled { border-color: var(--accent); color: var(--accent); }
  .acts button:disabled { color: var(--faint); cursor: default; }
  .said { font-size: 13px; margin-top: 10px; }
  .said.bad { color: var(--red); }
  .said.ok { color: var(--green); }

  /* The prompt box. Sticky at the bottom of the conversation, which is where
     the thing being replied to is. */
  form.say { display: flex; gap: 8px; padding: 10px; position: sticky; bottom: 10px;
             background: var(--panel); border: 1px solid var(--line); border-radius: 10px;
             box-shadow: var(--shadow); margin-top: 14px; }
  form.say input {
    flex: 1 1 auto; font: inherit; font-size: 14px; padding: 8px 10px; min-width: 0;
    border-radius: 7px; border: 1px solid var(--line); background: var(--bg); color: var(--ink);
  }
  form.say input:focus { outline: 2px solid var(--accent); outline-offset: -1px; }
  form.say button {
    font: inherit; font-size: 13px; padding: 0 16px; border-radius: 7px; cursor: pointer;
    border: 1px solid var(--accent); background: var(--accent); color: var(--panel);
  }
  form.say button:disabled { opacity: .5; cursor: default; }

  /* "New activity" floats rather than sitting in the flow: it is about the
     scroll position, not the transcript. Fixed above the composer — bottom
     78px clears its ~60px of height and 10px of offset — and centred so it
     reads as the page's pill, not a turn's. */
  .more {
    position: fixed; left: 50%; bottom: 78px; transform: translateX(-50%); z-index: 5;
    font: inherit; font-size: 12px; padding: 5px 14px; border-radius: 99px;
    border: 1px solid var(--line); background: var(--panel); color: var(--dim);
    box-shadow: var(--shadow); cursor: pointer;
  }
  .more:hover { color: var(--accent); border-color: var(--accent); }
  .earlier { display: block; width: 100%; padding: 10px 14px; border: 0;
             border-bottom: 1px solid var(--line); border-radius: 0;
             color: var(--faint); font-size: 12px; text-align: left; }
  .earlier:hover { color: var(--accent); }
  /* The "N new" jump rides on the earlier button's shape but speaks in the
     accent: it points at what arrived since the last visit, which is a
     finding rather than a chore. */
  .earlier.jumpnew { color: var(--accent); }

  /* The chat pane's own controls. They sit above #split rather than inside
     #talk because the poll rebuilds #talk every five seconds — a control in
     there would be thrown away under a typing reader. */
  .chattools { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; margin-bottom: 10px; }
  .chattools input {
    flex: 1 1 180px; min-width: 0; font: inherit; font-size: 13px; padding: 6px 10px;
    border-radius: 7px; border: 1px solid var(--line); background: var(--panel); color: var(--ink);
  }
  .chattools input:focus { outline: 2px solid var(--accent); outline-offset: -1px; }
  .chattools .n { font-size: 12px; color: var(--faint); white-space: nowrap; }
  .chattools button {
    font: inherit; font-size: 12px; padding: 5px 11px; border-radius: 99px;
    border: 1px solid var(--line); background: var(--panel); color: var(--dim); cursor: pointer;
  }
  .chattools button:hover:enabled { color: var(--accent); border-color: var(--accent); }
  .chattools button:disabled { color: var(--faint); cursor: default; }

  /* --- the conversation -------------------------------------------------- */

  .turn { border-top: 1px solid var(--line); padding: 12px 14px;
          /* Offscreen turns skip layout and paint — the browser's own lazy
             pass, so a long conversation is cheap even before the chunking
             below keeps its DOM small. */
          content-visibility: auto; contain-intrinsic-size: auto 140px; }
  .turn:first-child { border-top: 0; }
  .turn > .who {
    display: flex; gap: 8px; align-items: baseline; font-size: 11px;
    text-transform: uppercase; letter-spacing: .06em; color: var(--faint); margin-bottom: 5px;
  }
  .turn > .said-text { white-space: pre-wrap; overflow-wrap: anywhere; font-size: 14px; }
  .turn.user { background: color-mix(in srgb, var(--accent) 6%, transparent); }
  .turn.user > .who { color: var(--accent); }
  .turn.system > .said-text, .turn.reasoning > .said-text,
  .turn.system > .md, .turn.reasoning > .md { color: var(--dim); font-size: 13px; }

  /* What an agent writes is markdown, so it is shown as markdown. Paragraphs
     keep their own line breaks — a reply is written with them and reflowing it
     changes what it says. */
  .md { font-size: 14px; overflow-wrap: anywhere; }
  .md > * { margin: 0 0 9px; }
  .md > *:last-child { margin-bottom: 0; }
  .md p { white-space: pre-wrap; }
  .md h1, .md h2, .md h3, .md h4, .md h5, .md h6 {
    font-size: 1em; font-weight: 600; margin-top: 14px; line-height: 1.35;
  }
  .md h1 { font-size: 1.15em; }
  .md h2 { font-size: 1.07em; }
  .md ul, .md ol { padding-left: 21px; }
  .md li { margin: 2px 0; }
  .md li > .md { margin: 2px 0; }
  .md code {
    font-family: var(--mono); font-size: .87em; padding: 0 4px; border-radius: 4px;
    background: var(--bg); border: 1px solid var(--line);
  }
  .md pre {
    background: var(--bg); border: 1px solid var(--line); border-radius: 7px;
    padding: 8px 10px; overflow-x: auto;
  }
  .md pre code { border: 0; background: none; padding: 0; white-space: pre; font-size: 12px; }
  /* The page's own tables are data grids, with faint uppercase headers and a
     column set the report chose. A table an agent wrote is neither, so it
     keeps the words it was given and scrolls rather than crushing a column. */
  .md .scroll { overflow-x: auto; }
  /* Sized to its contents, not to the pane: a two-column table stretched to
     full width reads as a layout rather than a table. */
  .md table { font-size: 13px; width: auto; max-width: 100%; }
  .md th {
    text-transform: none; letter-spacing: 0; font-size: 13px; font-weight: 600;
    color: var(--ink); padding: 0 10px 7px; white-space: normal;
  }
  .md td { white-space: normal; }
  .md blockquote { border-left: 2px solid var(--line); padding-left: 11px; color: var(--dim); }
  .md hr { border: 0; border-top: 1px solid var(--line); }
  .md a { color: var(--accent); }
  .turn.compaction { text-align: center; color: var(--faint); font-size: 12px; }
  .turn .clip { font-size: 11px; color: var(--faint); margin-top: 4px; }

  /* The deep-link button at the .who line's far end — kept faint because it
     is a way to point at a turn, not part of what was said. */
  .turn > .who .anchor {
    margin-left: auto; font: inherit; font-size: 12px; line-height: inherit;
    text-transform: none; letter-spacing: 0; padding: 0 3px;
    border: 0; background: none; color: var(--faint); cursor: pointer; opacity: .6;
  }
  .turn > .who .anchor:hover { color: var(--accent); opacity: 1; }

  /* A turn the find box names, and the one it is sitting on — which is also
     the mark a deep link leaves. An inset shadow rather than a border, so
     marking a turn moves nothing. */
  .turn.hit { box-shadow: inset 3px 0 0 var(--accent); }
  .turn.current { background: color-mix(in srgb, var(--accent) 10%, transparent); }

  /* The keyboard selection — j/k marks a turn the way the dashboard's j/k
     marks a row. A thin frame rather than the find marks' edge or current's
     wash, so the three can be told apart on one turn. */
  .turn.sel { box-shadow: inset 0 0 0 1px var(--accent); }

  /* Newer than the stored "seen" seq: a small accent dot on the header line.
     A compaction has no header, so it takes a quiet edge instead. */
  .turn.new > .who::after {
    content: ""; align-self: center; flex: 0 0 auto;
    width: 6px; height: 6px; margin-left: 2px;
    border-radius: 50%; background: var(--accent);
  }
  .turn.new.compaction { box-shadow: inset 2px 0 0 var(--accent); }

  /* A tool call inside a turn: collapsed to one line, opened for the result. */
  details.tool { margin-top: 7px; border: 1px solid var(--line); border-radius: 7px; background: var(--bg); }
  details.tool > summary {
    padding: 6px 10px; cursor: pointer; display: flex; gap: 8px; align-items: baseline;
    flex-wrap: wrap; list-style: none; font-size: 12.5px;
  }
  details.tool > summary::-webkit-details-marker { display: none; }
  details.tool > summary .name { font-family: var(--mono); font-weight: 600; }
  details.tool > summary .arg { font-family: var(--mono); color: var(--dim); overflow-wrap: anywhere; }
  details.tool.failed { border-color: var(--red); }
  details.tool.failed > summary .name { color: var(--red); }
  details.tool.running > summary .name { color: var(--amber); }
  details.tool pre {
    margin: 0; padding: 8px 10px; border-top: 1px solid var(--line); font-family: var(--mono);
    font-size: 12px; white-space: pre-wrap; overflow-wrap: anywhere; color: var(--dim);
  }
  details.tool pre.patch { white-space: pre; overflow-x: auto; padding: 8px 0; color: var(--ink); }
  details.tool pre.patch span { display: block; padding: 0 10px; }
  details.tool pre.patch .add { background: color-mix(in srgb, var(--green) 14%, transparent); }
  details.tool pre.patch .del { background: color-mix(in srgb, var(--red) 14%, transparent); }
  details.tool pre.patch .meta { color: var(--faint); }

  /* --- what it can reach ------------------------------------------------- */

  .kv { display: grid; grid-template-columns: max-content 1fr; gap: 5px 14px; font-size: 13px; }
  .kv dt { color: var(--faint); }
  .kv dd { margin: 0; overflow-wrap: anywhere; }
  .rule { border-top: 1px solid var(--line); }
  .rule:first-child { border-top: 0; }
  .rule > summary {
    padding: 9px 14px; cursor: pointer; display: flex; gap: 10px; align-items: baseline;
    flex-wrap: wrap; list-style: none; font-size: 13px;
  }
  .rule > summary::-webkit-details-marker { display: none; }
  .rule > summary .path { font-family: var(--mono); font-size: 12.5px; overflow-wrap: anywhere; }
  .rule[data-present="false"] > summary { color: var(--faint); cursor: default; }
  .rule pre {
    margin: 0; padding: 10px 14px; border-top: 1px solid var(--line); font-family: var(--mono);
    font-size: 12px; white-space: pre-wrap; overflow-wrap: anywhere; max-height: 50vh; overflow-y: auto;
  }
  .chips { display: flex; flex-wrap: wrap; gap: 6px; }
  .chip { font-size: 12px; padding: 2px 9px; border-radius: 99px; border: 1px solid var(--line); }
  .chip .n { font-family: var(--mono); color: var(--faint); margin-left: 5px; }

  /* Compact is a choice about the conversation's rhythm — tighter turns,
     smaller markdown, tools that tuck in. It hangs off #talk so the choice
     survives the poll's rebuild, which only replaces what is inside it. */
  .talk[data-density="compact"] .turn { padding: 7px 14px; }
  .talk[data-density="compact"] .turn > .who { margin-bottom: 3px; }
  .talk[data-density="compact"] .turn > .said-text,
  .talk[data-density="compact"] .md { font-size: 13px; }
  .talk[data-density="compact"] .md > * { margin-bottom: 5px; }
  .talk[data-density="compact"] details.tool { margin-top: 4px; }

  /* --- a phone -------------------------------------------------------------
     The view pills get a scroll lane instead of wrapping into a stack of
     rows; the conversation keeps the full width; the find box and the
     composer stay usable — 16px inputs because a phone zooms the page on
     anything smaller. */
  @media (max-width: 700px) {
    .wrap { padding: 14px 10px 56px; }
    nav.views { flex-wrap: nowrap; overflow-x: auto; padding-bottom: 4px; }
    nav.views button { white-space: nowrap; }
    .subject h2 { font-size: 18px; }
    .tiles { grid-template-columns: repeat(2, minmax(0, 1fr)); }
    .files { columns: 1; }
    .turn { padding: 10px 10px; }
    .chattools input, form.say input { font-size: 16px; }
    form.say { bottom: 6px; }
  }
</style>
<!-- The stored light/dark choice has to land on <html> before the first
     paint, so it runs here rather than down with the page's own script. -->
<script>__CCTOP_THEME__</script>

<div class="wrap">
  <header class="top">
    <a class="back" href="/__CCTOP_BACK__">← all sessions</a>
    <div class="spacer"></div>
    <span class="faint mono" style="font-size:12px">cctop __CCTOP_VERSION__</span>
  </header>
  <main id="main"><div class="empty">Reading the transcript…</div></main>
</div>

<script>
"use strict";
const TOKEN = "__CCTOP_TOKEN__";
const QUERY = TOKEN ? "?t=" + encodeURIComponent(TOKEN) : "";
const ID = decodeURIComponent(location.pathname.replace(/^\/session\//, ""));
// Whether this cctop serves the routes that act on a session. Substituted by
// the server rather than discovered, so the controls are never drawn for a run
// that would refuse them.
const CAN_ACT = "__CCTOP_ACTIONS__";

// A "?find=" on the opening URL seeds the conversation's find box — the
// dashboard's global search links here with one. Read now: the token scrub
// in load() rewrites the address bar before the chat view exists to use it.
let findSeed = new URLSearchParams(location.search).get("find") || "";

// The light/dark/system switch, at the header's right end. The inlined
// theme.js defines window.themeToggle when the page is served; a copy opened
// as a bare file has none, so this is guarded rather than assumed.
const topBar = document.querySelector("header.top");
const themeButton = window.themeToggle && window.themeToggle();
if (topBar && themeButton) topBar.appendChild(themeButton);

const el = (tag, cls, text) => {
  const node = document.createElement(tag);
  if (cls) node.className = cls;
  if (text !== undefined && text !== null) node.textContent = String(text);
  return node;
};
const svg = (tag, attrs) => {
  const node = document.createElementNS("http://www.w3.org/2000/svg", tag);
  for (const [k, v] of Object.entries(attrs || {})) node.setAttribute(k, String(v));
  return node;
};

const money = (v) => {
  const n = Number(v) || 0;
  if (n === 0) return "$0";
  if (n < 0.01) return "<$0.01";
  return "$" + (n < 100 ? n.toFixed(2) : Math.round(n).toLocaleString());
};
const tokens = (v) => {
  const n = Number(v) || 0;
  if (n >= 1e9) return (n / 1e9).toFixed(2) + "G";
  if (n >= 1e6) return (n / 1e6).toFixed(1) + "M";
  if (n >= 1e3) return (n / 1e3).toFixed(1) + "k";
  return String(n);
};
// How long ago, for a session that has stopped. The clock time says when; this
// says how long ago, which is the part a reader actually holds in their head.
const ago = (iso) => {
  const then = Date.parse(iso);
  if (!isFinite(then)) return "";
  const s = Math.max(0, (Date.now() - then) / 1000);
  if (s < 60) return Math.floor(s) + "s ago";
  if (s < 3600) return Math.floor(s / 60) + "m ago";
  if (s < 86400) return Math.floor(s / 3600) + "h ago";
  return Math.floor(s / 86400) + "d ago";
};

const secs = (ms) => {
  const n = Number(ms) || 0;
  if (n >= 60000) return Math.round(n / 60000) + "m";
  if (n >= 1000) return (n / 1000).toFixed(1) + "s";
  return n + "ms";
};

const block = (heading, note) => {
  const s = el("section", "block");
  s.appendChild(el("h3", null, heading));
  if (note) s.appendChild(el("p", "note", note));
  return s;
};

// --- the pieces ------------------------------------------------------------

// The session's span, in words: when it started, how long it ran, and — for one
// that has stopped — how long ago it stopped. `duration` arrives already
// rendered because the server owns this codebase's rounding rules.
const when = (r) => {
  const spansDays =
    new Date(r.started_at).toDateString() !== new Date(r.last_active).toDateString();
  const start = clock(r.started_at, spansDays);
  if (!start) return r.duration;
  // A running session's end is "now", and printing it as a clock time invites
  // the reader to believe the page updates. It does not.
  const tail = r.running ? "still going" : ago(r.last_active);
  return start + " · " + r.duration + " · " + tail;
};

function subject(r) {
  const box = el("div", "subject");
  box.appendChild(el("h2", null, r.title || r.project || r.session_id));
  const where = el("div", "where");
  // The dot and the live pill are rewritten from the event stream after this,
  // so they carry ids rather than being composed here and forgotten.
  const dot = el("span", "dot " + (r.running ? r.state : "idle"));
  dot.id = "live-dot";
  where.appendChild(dot);
  const pill = el("span");
  pill.id = "live-pill";
  where.appendChild(pill);
  const tag = (t) => { if (t) where.appendChild(el("span", null, t)); };
  tag(r.project);
  tag(r.branch);
  if (r.profile && r.profile !== "default") tag("profile: " + r.profile);
  // Harness and model are separate facts — the dashboard's rows tag both, so
  // the header does too.
  tag(r.provider);
  if (r.model) tag(r.model);
  // When, not just how long. A duration on its own answers "was this a long
  // session" and nothing else — the reader who opened this because something
  // happened this morning needs to know whether they are looking at it.
  tag(when(r));
  if (r.plan !== "retail") tag("plan: " + r.plan);
  where.appendChild(el("span", "faint mono", r.session_id));
  box.appendChild(where);
  return box;
}

function tiles(r) {
  const grid = el("div", "tiles");
  const add = (k, v, note, cls) => {
    const t = el("div", "card tile" + (cls ? " " + cls : ""));
    t.appendChild(el("div", "k", k));
    t.appendChild(el("div", "v", v));
    if (note) t.appendChild(el("div", "n", note));
    grid.appendChild(t);
  };

  // "incl" and "—" are different claims: one says the plan bundles this, the
  // other says the transcript records no billable usage at all.
  const cost = r.cost.included ? "incl" : (r.cost.available ? money(r.cost.total) : "");
  add("Cost", cost, r.cost.included ? "bundled by this plan" : null);
  add("Tokens", tokens(r.tokens.total || (r.tokens.input + r.tokens.output)),
      tokens(r.tokens.input) + " in · " + tokens(r.tokens.output) + " out");
  add("Tool calls", (r.activity.tool_count || 0).toLocaleString());

  if (r.activity.error_rate !== null && r.activity.error_rate !== undefined) {
    const pct = Math.round(r.activity.error_rate * 100);
    add("Tool errors", pct + "%", (r.activity.tool_errors || 0) + " failed",
        pct >= 25 ? "bad" : (pct >= 10 ? "warn" : null));
  }
  if (r.context) {
    const pct = Math.round(r.context.percent_to_compact);
    add("Context", pct + "%", tokens(r.context.used) + " of " + tokens(r.context.max),
        pct >= 90 ? "bad" : (pct >= 70 ? "warn" : null));
    if (r.context.compactions > 0) {
      // A session that compacts repeatedly is rebuilding a window it keeps
      // refilling, and paying to read it back each time.
      add("Compactions", r.context.compactions, null, r.context.compactions >= 3 ? "warn" : null);
    }
  }
  if (r.activity.lines_added || r.activity.lines_removed) {
    add("Lines", "+" + r.activity.lines_added, "" + r.activity.lines_removed);
  }
  return grid;
}

function failures(r) {
  const found = r.activity.failures || [];
  if (!found.length) return null;
  const repeated = found.filter((f) => f.count > 1).length;
  // The heading follows the content. Calling a list of one-offs "Repeated
  // failures" promises a loop and then shows ×1 down the whole section, which
  // teaches the reader to stop believing the headings.
  const s = block(
    repeated ? "Repeated failures" : "Failed tool calls",
    repeated
      ? "Grouped by tool and by argument. A count above one is the same call retried — the agent paid for every attempt."
      : "Grouped by tool and by argument. Nothing repeated, so these are one-offs rather than a loop."
  );
  const card = el("div", "card");
  for (const f of found) {
    const item = el("div", "failure");
    const head = el("div", "head");
    // ×1 is not a count, it is the absence of one. Shown only where it says
    // something.
    if (f.count > 1) head.appendChild(el("span", "count", "×" + f.count));
    head.appendChild(el("span", "tool", f.tool));
    const when = f.samples && f.samples.length ? f.samples[0].ts : null;
    if (when) head.appendChild(el("span", "faint", "first at " + when.replace("T", " ").replace(/\..*$/, "")));
    item.appendChild(head);
    item.appendChild(el("pre", null, f.detail));
    card.appendChild(item);
  }
  s.appendChild(card);
  return s;
}

const CONTEXT_PARTS = [
  ["startup", "Startup", "var(--dim)"],
  ["tool_output", "Tool output", "var(--accent)"],
  ["tool_input", "Tool input", "var(--amber)"],
  ["attachments", "Attachments", "var(--green)"],
  ["user_text", "You", "var(--red)"],
  ["assistant_text", "Assistant", "var(--faint)"],
];

function breakdown(r) {
  const b = r.context && r.context.breakdown;
  if (!b || !b.total) return null;

  const s = block(
    "What is in the context window",
    "Startup and the window total are exact; the rest is estimated from transcript characters, so read them as proportions. " +
    (b.unaccounted >= 0
      ? "Unaccounted is thinking — stored stripped — plus the harness's per-turn reminders and estimation error."
      : "The estimate overshoots the measured window, which happens when the harness has dropped old tool results the transcript still holds.") +
    (b.superseded ? " A compaction has since replaced this segment, so these describe the window before it." : "")
  );

  const card = el("div", "card pad");
  const bar = el("div", "stack");
  const legend = el("div", "legend");
  const parts = CONTEXT_PARTS.map(([key, label, color]) => [label, b[key] || 0, color]);
  if (b.unaccounted > 0) parts.push(["Unaccounted", b.unaccounted, "var(--line)"]);

  const shown = parts.reduce((sum, [, v]) => sum + v, 0) || 1;
  for (const [label, value, color] of parts) {
    if (value <= 0) continue;
    const seg = el("span");
    seg.style.width = (value / shown * 100).toFixed(2) + "%";
    seg.style.background = color;
    seg.title = label + ": " + tokens(value);
    bar.appendChild(seg);

    const item = el("div", "item");
    const swatch = el("span", "swatch");
    swatch.style.background = color;
    item.appendChild(swatch);
    item.appendChild(el("span", null, label));
    item.appendChild(el("span", "amt", tokens(value)));
    legend.appendChild(item);
  }
  card.appendChild(bar);
  card.appendChild(legend);
  s.appendChild(card);
  return s;
}

// A clock time from an ISO timestamp, with the date when the session spans
// more than one.
const clock = (iso, withDate) => {
  const at = new Date(iso);
  if (isNaN(at)) return "";
  const hm = String(at.getHours()).padStart(2, "0") + ":" +
             String(at.getMinutes()).padStart(2, "0");
  if (!withDate) return hm;
  return at.toLocaleDateString(undefined, { month: "short", day: "numeric" }) + " " + hm;
};

// The window measured at every request, oldest first. A steady climb is a
// conversation growing; a step is one tool result that will do it again.
function windowChart(r) {
  const series = (r.context && r.context.series) || [];
  if (series.length < 3) return null;

  const first = series[0].ts, last = series[series.length - 1].ts;
  // Requests are not evenly spaced in time, so the axis is labelled with the
  // clock but the spacing is per request. Saying so is the whole point of the
  // note: a reader who assumes a time axis reads every flat stretch as a pause
  // and every steep one as a burst, and neither is what the chart shows.
  const spansDays = new Date(first).toDateString() !== new Date(last).toDateString();
  const s = block(
    "How the window filled",
    "Left to right, one point per request in the order they were made — evenly spaced, " +
    "so this is not a time axis: a wide flat stretch is many requests, not a long pause. " +
    "The labels underneath say when each end happened. Up is tokens in the window; " +
    "dashed vertical marks are compactions, where the harness reclaimed it."
  );
  const W = 900, H = 205, PAD_L = 46, PAD_B = 32, PAD_T = 8;
  const max = Math.max(...series.map((p) => p.window), 1);
  const x = (i) => PAD_L + (i / (series.length - 1)) * (W - PAD_L - 8);
  const y = (v) => PAD_T + (1 - v / max) * (H - PAD_T - PAD_B);

  const chart = svg("svg", { viewBox: `0 0 ${W} ${H}`, width: "100%", height: H,
                             role: "img",
                             "aria-label": "Context window size across " + series.length +
                                           " requests, from " + clock(first, true) +
                                           " to " + clock(last, true) });
  for (const frac of [0, 0.5, 1]) {
    const yy = y(max * frac);
    chart.appendChild(svg("line", { x1: PAD_L, y1: yy, x2: W - 8, y2: yy, class: "gridline" }));
    const label = svg("text", { x: PAD_L - 6, y: yy + 3, "text-anchor": "end", class: "axis" });
    label.textContent = tokens(Math.round(max * frac));
    chart.appendChild(label);
  }

  // The x axis: what the ends are, and what the distance between them counts.
  const foot = (xPos, anchor, text) => {
    const t = svg("text", { x: xPos, y: H - 14, "text-anchor": anchor, class: "axis" });
    t.textContent = text;
    chart.appendChild(t);
  };
  foot(PAD_L, "start", clock(first, spansDays));
  foot((PAD_L + W - 8) / 2, "middle", series.length + " requests →");
  foot(W - 8, "end", clock(last, spansDays));

  const line = series.map((p, i) => `${i ? "L" : "M"}${x(i).toFixed(1)},${y(p.window).toFixed(1)}`).join("");
  chart.appendChild(svg("path", {
    d: `${line}L${x(series.length - 1).toFixed(1)},${y(0)}L${x(0).toFixed(1)},${y(0)}Z`,
    fill: "var(--accent)", "fill-opacity": ".13",
  }));
  chart.appendChild(svg("path", { d: line, fill: "none", stroke: "var(--accent)", "stroke-width": "1.5" }));

  series.forEach((p, i) => {
    if (!p.after_compaction) return;
    chart.appendChild(svg("line", {
      x1: x(i), y1: PAD_T, x2: x(i), y2: y(0),
      stroke: "var(--amber)", "stroke-width": "1", "stroke-dasharray": "3 3",
    }));
  });

  const holder = el("div", "card pad scroll-x");
  holder.appendChild(chart);
  s.appendChild(holder);
  return s;
}

function spend(r) {
  const byModel = r.cost.by_model || [];
  const byHour = r.cost.by_hour || [];
  if (!byModel.length && !byHour.length) return null;
  const s = block("What it cost");
  const card = el("div", "card");

  if (byHour.length > 1) {
    const W = 900, H = 110, PAD_L = 46, PAD_B = 16;
    const max = Math.max(...byHour.map(([, v]) => v), 0.0001);
    const chart = svg("svg", { viewBox: `0 0 ${W} ${H}`, width: "100%", height: H,
                               role: "img", "aria-label": "Spend per hour" });
    const gap = 1;
    const bw = Math.max(1, (W - PAD_L - 8) / byHour.length - gap);
    byHour.forEach(([key, value], i) => {
      const h = Math.max(1, (value / max) * (H - PAD_B - 4));
      const bar = svg("rect", {
        x: PAD_L + i * (bw + gap), y: H - PAD_B - h, width: bw, height: h,
        fill: "var(--accent)", rx: 1,
      });
      const tip = svg("title");
      tip.textContent = key.replace("T", " ") + ":00 — " + money(value);
      bar.appendChild(tip);
      chart.appendChild(bar);
    });
    const top = svg("text", { x: PAD_L - 6, y: 12, "text-anchor": "end", class: "axis" });
    top.textContent = money(max);
    chart.appendChild(top);
    const holder = el("div", "pad scroll-x");
    holder.appendChild(chart);
    holder.appendChild(el("div", "faint", "Per hour, most recent at the right."));
    card.appendChild(holder);
  }

  if (byModel.length) {
    const holder = el("div", "pad scroll-x");
    const table = el("table");
    const head = el("tr");
    for (const [label, cls] of [["Model", ""], ["Input", "num"], ["Output", "num"], ["Cost", "num"]]) {
      head.appendChild(el("th", cls, label));
    }
    table.appendChild(head);
    for (const m of byModel) {
      const tr = el("tr");
      tr.appendChild(el("td", null, m.model));
      tr.appendChild(el("td", "num", tokens(m.tokens.input)));
      tr.appendChild(el("td", "num", tokens(m.tokens.output)));
      tr.appendChild(el("td", "num", r.cost.included ? "incl" : money(m.total)));
      table.appendChild(tr);
    }
    holder.appendChild(table);
    card.appendChild(holder);
  }
  s.appendChild(card);
  return s;
}

function slowest(r) {
  const calls = r.activity.slowest || [];
  if (!calls.length) return null;
  const s = block("Slowest calls", "Wall time from the call being issued to its result arriving.");
  const card = el("div", "card pad scroll-x");
  const table = el("table");
  const head = el("tr");
  head.appendChild(el("th", null, "Tool"));
  head.appendChild(el("th", null, "Call"));
  head.appendChild(el("th", "num", "Took"));
  table.appendChild(head);
  for (const c of calls) {
    const tr = el("tr");
    tr.appendChild(el("td", "mono", c.tool));
    const what = el("td");
    what.appendChild(el("span", "mono", c.detail));
    if (c.failed) what.appendChild(el("span", "pill bad", "failed"));
    if (c.origin) what.appendChild(el("span", "pill", c.origin));
    tr.appendChild(what);
    tr.appendChild(el("td", "num", secs(c.duration_ms)));
    table.appendChild(tr);
  }
  card.appendChild(table);
  s.appendChild(card);
  return s;
}

function toolTable(r) {
  const tools = r.activity.tools || [];
  if (!tools.length) return null;
  const s = block("Tools");
  const card = el("div", "card pad scroll-x");
  const table = el("table");
  const head = el("tr");
  head.appendChild(el("th", null, "Tool"));
  head.appendChild(el("th", "num", "Calls"));
  head.appendChild(el("th", "num", "Failed"));
  table.appendChild(head);
  for (const t of tools) {
    const tr = el("tr");
    tr.appendChild(el("td", "mono", t.name));
    tr.appendChild(el("td", "num", t.calls.toLocaleString()));
    tr.appendChild(el("td", "num", t.failed ? String(t.failed) : ""));
    table.appendChild(tr);
  }
  card.appendChild(table);
  s.appendChild(card);
  return s;
}

function files(r) {
  if (!r.files || !r.files.length) return null;
  const s = block("Files it wrote", "Most recent first. Line counts where the transcript kept the edits.");
  const card = el("div", "card pad");
  const list = el("div", "files");
  const stats = new Map(diffFiles(r).map((d) => [d.file, d]));
  for (const f of r.files) {
    const row = el("div");
    row.appendChild(document.createTextNode(f));
    const d = stats.get(f);
    if (d && (d.added || d.removed)) {
      row.appendChild(el("span", "plus", " +" + (d.added || 0)));
      row.appendChild(el("span", "minus", "" + (d.removed || 0)));
    }
    list.appendChild(row);
  }
  card.appendChild(list);
  s.appendChild(card);
  return s;
}

// Which results filled the window. The breakdown says tool output is most of
// it; this says which calls put it there.
//
// The figure is the window's growth after the call, which the transcript can
// give and a result size it cannot: nothing records how big a tool result was,
// but every request records the prompt it was billed for, and that prompt is the
// conversation so far. The difference is the result.
function heaviest(r) {
  const calls = r.activity.heaviest || [];
  if (!calls.length) return null;
  const shared = calls.some((c) => c.shared > 1);
  const s = block(
    "What filled the window",
    "How much the context window grew after each call — which is what its result " +
    "added. Largest first. Measured from the prompt each request was billed for, " +
    "not from the result itself, which no transcript records" +
    (shared
      ? ": a turn that issued several calls grew it by all of their results together, " +
        "and those are marked."
      : ". Anything else that arrived in the same gap — a message you typed while it " +
        "worked — is counted here too.")
  );
  const card = el("div", "card pad scroll-x");
  const table = el("table");
  const head = el("tr");
  head.appendChild(el("th", null, "Tool"));
  head.appendChild(el("th", null, "Call"));
  head.appendChild(el("th", "num", "Grew by"));
  table.appendChild(head);
  for (const c of calls) {
    const tr = el("tr");
    tr.appendChild(el("td", "mono", c.tool));
    const what = el("td");
    what.appendChild(el("span", "mono", c.detail));
    // The one honest caveat per row: this figure covers every result that
    // turn's calls returned, and the page must not imply otherwise.
    if (c.shared > 1) what.appendChild(el("span", "pill", "with " + (c.shared - 1) + " more"));
    if (c.origin) what.appendChild(el("span", "pill", c.origin));
    tr.appendChild(what);
    tr.appendChild(el("td", "num", tokens(c.window_growth)));
    table.appendChild(tr);
  }
  card.appendChild(table);
  s.appendChild(card);
  return s;
}

// r.diffs as one entry per file. That is what the server sends; the merge is
// repeated here so neither changes-view part depends on how the data arrived.
// The line counts come from the transcript's own tally — where an entry
// carries none they are counted back out of the hunk lines, which is the sum
// they were taken from.
function diffFiles(r) {
  const byFile = new Map();
  for (const f of r.diffs || []) {
    let got = byFile.get(f.file);
    if (!got) {
      got = { file: f.file, added: 0, removed: 0, edits: 0, hunks: [], truncated: false };
      byFile.set(f.file, got);
    }
    got.added += f.added || 0;
    got.removed += f.removed || 0;
    got.edits += f.edits || 1;
    got.hunks.push(...(f.hunks || []));
    got.truncated = got.truncated || !!f.truncated;
  }
  const files = [...byFile.values()];
  for (const f of files) {
    if (f.added || f.removed || !f.hunks.length) continue;
    for (const line of f.hunks) {
      if (line.startsWith("+") && !line.startsWith("+++")) f.added++;
      else if (line.startsWith("-") && !line.startsWith("---")) f.removed++;
    }
  }
  return files;
}

// What the session actually changed. A list of file names says it touched
// something; this says what it did to it.
function diffs(r) {
  const files = diffFiles(r);
  if (!files.length) return null;
  const total = files.reduce((a, f) => a + f.added + f.removed, 0);
  const s = block(
    "What it changed",
    files.length + (files.length === 1 ? " file, " : " files, ") + total +
      " changed lines. Most-changed first; click a file for its diff. Reconstructed from the patches the transcript recorded, so it is what the agent applied rather than what the file holds now."
  );
  const card = el("div", "card");
  for (const f of files) {
    const box = el("details", "diff");
    const head = el("summary");
    head.appendChild(el("span", "path", f.file));
    if (f.added) head.appendChild(el("span", "plus", "+" + f.added));
    if (f.removed) head.appendChild(el("span", "minus", "" + f.removed));
    if (f.edits > 1) head.appendChild(el("span", "faint", f.edits + " edits"));
    box.appendChild(head);

    const pre = el("pre");
    for (const line of f.hunks) {
      // Classed by the diff marker, never by parsing the content: a line of
      // code beginning with a minus is not a deletion.
      const cls = line.startsWith("+") ? "add"
        : line.startsWith("-") ? "del"
        : line.startsWith("@@") || line.startsWith("diff ") ? "meta"
        : "";
      pre.appendChild(el("span", cls, line));
    }
    if (f.truncated) {
      pre.appendChild(el("span", "meta", "… the rest of this file's edits are not kept"));
    }
    box.appendChild(pre);
    card.appendChild(box);
  }
  s.appendChild(card);
  return s;
}

// Every call the extraction still holds. The slowest ten answer one question;
// this answers "what did it actually do, in order".
function callLog(r) {
  const calls = r.activity.calls || [];
  if (!calls.length) return null;
  const made = r.activity.tool_count || 0;
  // Never presented as the whole record when it is not. A log that silently
  // stopped short reads as a session that stopped doing things.
  const note = calls.length < made
    ? "Newest first. The transcript keeps only its most recent " + calls.length +
      " calls, of " + made + " the session made."
    : "Newest first. All " + calls.length + " calls.";
  const note2 = calls.some((c) => c.origin)
    ? " A call a subagent made carries its name; the rest are the session's own."
    : "";
  const s = block("Every tool call", note + note2);

  const card = el("div", "card log");
  const table = el("table");
  const head = el("thead");
  const hrow = el("tr");
  hrow.appendChild(el("th", null, "Tool"));
  hrow.appendChild(el("th", null, "Call"));
  hrow.appendChild(el("th", "num", "Took"));
  hrow.appendChild(el("th", "num", "Grew"));
  hrow.appendChild(el("th", null, "When"));
  head.appendChild(hrow);
  table.appendChild(head);

  const body = el("tbody");
  for (const c of calls) {
    const tr = el("tr", c.failed ? "bad" : null);
    tr.appendChild(el("td", "mono", c.tool));
    const what = el("td");
    what.appendChild(el("span", "mono", c.detail));
    if (c.failed) what.appendChild(el("span", "pill bad", "failed"));
    // Whose call it was. Absent for the session's own, so the pill appears
    // exactly where it distinguishes something.
    if (c.origin) what.appendChild(el("span", "pill", c.origin));
    tr.appendChild(what);
    tr.appendChild(el("td", "num", c.duration_ms == null ? "" : secs(c.duration_ms)));
    // How much this call's result added to the window. A dash where it could not
    // be measured — the last call of the session, or a window that shrank around
    // a compaction — because a zero would read as a result that was empty.
    const grew = el("td", "num", c.window_growth == null ? "" : "+" + tokens(c.window_growth));
    if (c.shared > 1) grew.title = "shared with " + (c.shared - 1) + " more calls in the same turn";
    tr.appendChild(grew);
    tr.appendChild(el("td", "when", (c.ts || "").replace("T", " ").replace(/\..*$/, "")));
    body.appendChild(tr);
  }
  table.appendChild(body);
  card.appendChild(table);
  s.appendChild(card);
  return s;
}

function subagents(r) {
  if (!r.subagents || !r.subagents.length) return null;
  const s = block("Subagents");
  const card = el("div", "card pad scroll-x");
  const table = el("table");
  const head = el("tr");
  for (const [label, cls] of [["Type", ""], ["Description", ""], ["Tools", "num"], ["Cost", "num"]]) {
    head.appendChild(el("th", cls, label));
  }
  table.appendChild(head);
  for (const a of r.subagents) {
    const tr = el("tr");
    tr.appendChild(el("td", "mono", a.type));
    tr.appendChild(el("td", null, a.description));
    tr.appendChild(el("td", "num", a.tool_count));
    tr.appendChild(el("td", "num", r.cost.included ? "incl" : money(a.cost)));
    table.appendChild(tr);
  }
  card.appendChild(table);
  s.appendChild(card);
  return s;
}

// --- the conversation ------------------------------------------------------

// One diff, coloured by line. Shared by the conversation's tool calls and the
// Changes view, because a patch reads the same way in both.
function patchLines(hunks) {
  const pre = el("pre", "patch");
  for (const line of hunks) {
    const cls = line.startsWith("+") ? "add" : line.startsWith("-") ? "del"
      : line.startsWith("@@") ? "meta" : "";
    pre.appendChild(el("span", cls, line));
  }
  return pre;
}

// A tool call: one line saying what it did, opening onto what came back.
function toolNode(tool) {
  const failed = !!tool.failed;
  const running = tool.result === undefined || tool.result === null;
  const node = el("details", "tool" + (failed ? " failed" : running ? " running" : ""));
  const sum = el("summary");
  sum.appendChild(el("span", "name", tool.name));
  if (tool.detail) sum.appendChild(el("span", "arg", tool.detail));
  if (tool.added || tool.removed) {
    sum.appendChild(el("span", "plus", "+" + (tool.added || 0)));
    sum.appendChild(el("span", "minus", "" + (tool.removed || 0)));
  }
  if (failed) sum.appendChild(el("span", "pill bad", "failed"));
  else if (running) sum.appendChild(el("span", "pill warn", "running"));
  node.appendChild(sum);

  if (tool.full && tool.full !== tool.detail) node.appendChild(el("pre", null, tool.full));
  if (tool.diff && tool.diff.length) node.appendChild(patchLines(tool.diff));
  if (!running && tool.result !== "") node.appendChild(el("pre", null, tool.result));
  return node;
}

const WHO = { user: "you", assistant: "agent", system: "harness" };

// --- markdown --------------------------------------------------------------

// Enough markdown to read a reply by: headings, lists, quotes, rules, fenced
// code, and the inline run of code, emphasis and links. It is built as nodes
// rather than a string of HTML, because nothing in this page sets innerHTML
// and a transcript — somebody else's text, including whatever a tool printed
// into it — is the last place to start.

const BLOCK = /^\s*(```|~~~|#{1,6}\s|>|[-*+]\s|\d+[.)]\s)/;
// The second row of a table, which is the only thing that makes the first one
// a table: dashes and optional colons, one run per column.
const RULE_ROW = /^\s*\|?(\s*:?-+:?\s*\|)+(\s*:?-+:?\s*)?\|?\s*$/;
const BULLET = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/;
const FENCE = /^\s*(```|~~~)/;

// A link is only followed if it goes somewhere a browser should go. Anything
// else — a `javascript:` href above all — comes back as the text it was
// written as, which is both safe and honest about what was there.
function linkNode(label, href, raw) {
  if (!/^(https?:|mailto:)/i.test(href)) return document.createTextNode(raw || label);
  const a = el("a", null, label);
  a.href = href;
  a.target = "_blank";
  a.rel = "noopener noreferrer";
  return a;
}

const INLINE = /`([^`]+)`|\*\*([\s\S]+?)\*\*|(?<![\w*])\*([^*\n]+)\*(?![\w*])|\[([^\]]*)\]\(([^)\s]+)\)|(https?:\/\/[^\s<>()\[\]]+)/g;

function inlineInto(node, text) {
  let at = 0;
  let m;
  INLINE.lastIndex = 0;
  while ((m = INLINE.exec(text))) {
    if (m.index > at) node.appendChild(document.createTextNode(text.slice(at, m.index)));
    if (m[1] !== undefined) node.appendChild(el("code", null, m[1]));
    else if (m[2] !== undefined) node.appendChild(el("strong", null, m[2]));
    else if (m[3] !== undefined) node.appendChild(el("em", null, m[3]));
    else if (m[4] !== undefined) node.appendChild(linkNode(m[4] || m[5], m[5], m[0]));
    else node.appendChild(linkNode(m[6], m[6]));
    at = INLINE.lastIndex;
  }
  if (at < text.length) node.appendChild(document.createTextNode(text.slice(at)));
  return node;
}

// A table is recognised by its second line, so it is asked about by position
// rather than by line — including from inside the paragraph loop, which would
// otherwise swallow a header row as prose.
function tableAt(lines, i) {
  return i + 1 < lines.length && lines[i].includes("|") && RULE_ROW.test(lines[i + 1]);
}

// `| a | b |` → ["a", "b"]. The outer pipes are optional and an escaped one is
// a pipe, not a cell wall.
function cells(line) {
  return line
    .trim()
    .replace(/^\|/, "")
    .replace(/\|$/, "")
    .split(/(?<!\\)\|/)
    .map((cell) => cell.replace(/\\\|/g, "|").trim());
}

function markdown(text) {
  const root = el("div", "md");
  const lines = String(text).split("\n");
  let i = 0;
  while (i < lines.length) {
    const line = lines[i];
    if (FENCE.test(line)) {
      i++;
      const body = [];
      while (i < lines.length && !FENCE.test(lines[i])) body.push(lines[i++]);
      i++;  // the closing fence, or the end of the text if it was never closed
      const pre = el("pre");
      pre.appendChild(el("code", null, body.join("\n")));
      root.appendChild(pre);
      continue;
    }
    if (!line.trim()) {
      i++;
      continue;
    }
    const heading = line.match(/^\s{0,3}(#{1,6})\s+(.*)$/);
    if (heading) {
      root.appendChild(inlineInto(el("h" + heading[1].length), heading[2].trim()));
      i++;
      continue;
    }
    if (/^\s*([-*_])\s*(\1\s*){2,}$/.test(line)) {
      root.appendChild(el("hr"));
      i++;
      continue;
    }
    if (/^\s*>/.test(line)) {
      const body = [];
      while (i < lines.length && /^\s*>/.test(lines[i])) body.push(lines[i++].replace(/^\s*>\s?/, ""));
      const quote = el("blockquote");
      quote.appendChild(markdown(body.join("\n")));
      root.appendChild(quote);
      continue;
    }
    if (tableAt(lines, i)) {
      const head = cells(line);
      // `:---:` and `---:` are the alignments a writer can ask for, and the
      // only part of the rule row worth keeping.
      const align = cells(lines[i + 1]).map((rule) => {
        if (/^:-+:$/.test(rule)) return "center";
        if (/-+:$/.test(rule)) return "right";
        return "";
      });
      i += 2;
      const table = el("table");
      const header = el("tr");
      head.forEach((cell, n) => {
        const th = inlineInto(el("th"), cell);
        if (align[n]) th.style.textAlign = align[n];
        header.appendChild(th);
      });
      table.appendChild(el("thead")).appendChild(header);
      const body = el("tbody");
      while (i < lines.length && lines[i].includes("|") && lines[i].trim()) {
        const row = el("tr");
        cells(lines[i++]).forEach((cell, n) => {
          const td = inlineInto(el("td"), cell);
          if (align[n]) td.style.textAlign = align[n];
          row.appendChild(td);
        });
        body.appendChild(row);
      }
      table.appendChild(body);
      const scroll = el("div", "scroll");
      scroll.appendChild(table);
      root.appendChild(scroll);
      continue;
    }
    if (BULLET.test(line)) {
      // ponytail: a nested list renders flat. Depth is indentation, and
      // guessing at it wrongly reads worse than one honest level.
      const list = el(/^\s*\d/.test(line) ? "ol" : "ul");
      while (i < lines.length && BULLET.test(lines[i])) {
        const m = lines[i++].match(BULLET);
        // A line under a bullet that is neither blank nor a bullet of its own
        // belongs to the item above it — that is how a wrapped list item is
        // written, and splitting it into a paragraph would break the list.
        const said = [m[3]];
        while (i < lines.length && lines[i].trim() && !BULLET.test(lines[i]) && !FENCE.test(lines[i])) {
          said.push(lines[i++].trim());
        }
        list.appendChild(inlineInto(el("li"), said.join(" ")));
      }
      root.appendChild(list);
      continue;
    }
    // The first line is taken whatever it looks like. Everything above has
    // declined it, and a loop that can decline every branch and still not
    // advance is a hung page.
    const para = [lines[i++]];
    while (i < lines.length && lines[i].trim() && !BLOCK.test(lines[i]) && !tableAt(lines, i)) {
      para.push(lines[i++]);
    }
    root.appendChild(inlineInto(el("p"), para.join("\n")));
  }
  return root;
}

function turnNode(turn, seq) {
  const kind = turn.kind === "message" ? "" : " " + turn.kind;
  const node = el("div", "turn " + turn.role + kind);
  // The id is the turn's transcript-wide seq — what a "#chat/turn-N" link and
  // the find box's marks name. Set before the compaction early return because
  // a link can name a compaction turn too.
  node.id = "turn-" + seq;
  if (turn.kind === "compaction") {
    node.appendChild(el("div", "said-text", "— context compacted here —"));
    return node;
  }
  const who = el("div", "who");
  who.appendChild(el("span", null, turn.kind === "reasoning" ? "thinking" : (WHO[turn.role] || turn.role)));
  if (turn.ts) who.appendChild(el("span", "faint", clock(turn.ts, true) || ""));
  // "#" copies a link that opens this page on this turn.
  const anchor = el("button", "anchor", "#");
  anchor.type = "button";
  anchor.title = "Copy a link to this turn";
  anchor.addEventListener("click", () => linkTurn(seq));
  who.appendChild(anchor);
  node.appendChild(who);
  if (turn.text) node.appendChild(markdown(turn.text));
  if (turn.clipped) node.appendChild(el("div", "clip", "… cut for length; the whole of it is in the transcript"));
  for (const tool of turn.tools || []) node.appendChild(toolNode(tool));
  return node;
}

function conversation(chat) {
  const s = block("Conversation");
  if (!chat.supported) {
    s.appendChild(el("div", "card pad faint", chat.note || "no reader for this harness"));
    return s;
  }
  const card = el("div", "card");
  const turns = TURNS;
  // Drawing every turn at once is what makes a big session stall — each is a
  // markdown pass plus its tool rows. The tail is what is live, so it is
  // drawn and the rest is a click per chunk away — fetched turns first, and
  // once those are all showing the same button pages the transcript itself.
  const hidden = Math.max(0, turns.length - chatShown);
  const earlier = earlierCount() + hidden;
  if (earlier) {
    const more = el("button", "earlier",
      "show " + Math.min(CHAT_CHUNK, earlier) + " earlier turns — " + earlier + " in all not drawn");
    more.type = "button";
    more.addEventListener("click", () => showEarlier(more));
    card.appendChild(more);
  }
  // The seen line as this visit found it. null is a first visit — nothing is
  // marked "new" against a baseline that did not exist.
  const base = seenSeq();
  if (base !== null && turns.length && turns[turns.length - 1].seq > base) {
    const fresh = turns.filter((t) => t.seq > base).length;
    // Unfetched earlier turns may hold unread ones too; the count owns up to
    // only covering what has been fetched.
    const jump = el("button", "earlier jumpnew",
      fresh + (earlierCount() > base ? "+" : "") + " new — jump to the first");
    jump.type = "button";
    jump.title = "Scroll to the first turn since this page last recorded a visit";
    jump.addEventListener("click", () => gotoTurn(base + 1));
    card.appendChild(jump);
  }
  if (!turns.length) {
    card.appendChild(el("div", "empty", "Nothing has been said in this session yet."));
  }
  // The id a turn is drawn with is its transcript seq — `hidden` is also the
  // first drawn position — so a "#chat/turn-N" link names the same turn
  // however the fetched window slides.
  turns.forEach((turn, i) => {
    if (i >= hidden) {
      const node = turnNode(turn, turn.seq);
      if (base !== null && turn.seq > base) node.classList.add("new");
      card.appendChild(node);
    }
  });
  s.appendChild(card);
  return s;
}

// One click on "show earlier": a chunk more of what is already held, or —
// when everything held is drawn — a fetch for the turns before it. The
// redraw lands above the fold either way, so the scroll is held on the same
// turn rather than jumping to wherever the new top put it.
async function showEarlier(button) {
  if (TURNS.length - chatShown > 0) {
    chatShown += CHAT_CHUNK;
  } else {
    const first = earlierCount();
    if (!first) return;
    button.disabled = true;
    button.textContent = "Reading earlier turns…";
    try {
      const chat = await ask(
        "/api/chat/" + encodeURIComponent(ID) +
          (QUERY ? QUERY + "&" : "?") + "before=" + first,
      ).then(asJson);
      mergeChat(chat);
      chatShown += Math.min(CHAT_CHUNK, (chat.turns || []).length);
    } catch (e) {
      // The button this came from is spent; the redraw remakes it.
      drawChat();
      saidFlash(String(e.message || e), false);
      return;
    }
  }
  const before = document.documentElement.scrollHeight;
  drawChat();
  window.scrollTo(0, window.scrollY + document.documentElement.scrollHeight - before);
}

// --- talking to the server -------------------------------------------------

// What went wrong, in words worth showing. A cctop error is short and arrives
// as text/plain; anything else in the body was written by something between
// this page and the server — a tunnel whose far end has gone answers with a
// whole HTML error page, and that page used to land in the pane verbatim.
async function problem(response) {
  const kind = (response.headers.get("content-type") || "").split(";")[0].trim();
  const said = kind === "text/plain" ? (await response.text()).trim() : "";
  if (said) return said.length > 400 ? said.slice(0, 400) + "" : said;
  if (response.status >= 502 && response.status <= 504) return "cctop is not answering. The link is up but nothing is behind it — the terminal it runs in may have stopped.";
  if (response.status === 401 || response.status === 403) return "This link is no longer authorised. Open a fresh one from the terminal.";
  return "The server answered " + response.status + (response.statusText ? " " + response.statusText : "") + ".";
}

// The body as JSON, or a sentence saying why it is not.
//
// A 200 is not a promise of JSON. A captive portal, a proxy, or a tunnel that
// has been repointed all answer with an HTML page and a perfectly good status,
// and `response.json()` then throws a parser's complaint — `Unexpected token
// '<', "<html><bod"... is not valid JSON` — which is machinery, shown to
// somebody who wanted to read a conversation. The status is not enough on its
// own; what came back has to be looked at.
async function asJson(response) {
  const text = await response.text();
  try {
    return JSON.parse(text);
  } catch (e) {
    throw new Error(
      "cctop answered with something that is not its own: whatever replied to " +
        "this page, it was not the session it was asked about."
    );
  }
}

// Every request the page makes. A dropped connection rejects the fetch itself
// with nothing in it worth reading, so it is named here instead.
async function ask(url, init) {
  let response;
  try {
    response = await fetch(url, init);
  } catch (e) {
    throw new Error("cctop is unreachable — the connection dropped.");
  }
  if (!response.ok) throw new Error(await problem(response));
  return response;
}

// A page whose server has gone says so once, at the top, and keeps everything
// it had already read. The alternative — replacing a conversation with the
// reason it could not be refreshed — throws away the part that was still true.
function offline(why) {
  const main = document.getElementById("main");
  let banner = document.getElementById("offline");
  if (!why) {
    if (banner) banner.remove();
    return;
  }
  if (!banner) {
    banner = el("div", "banner");
    banner.id = "offline";
    main.prepend(banner);
  }
  banner.textContent = why + " Still trying.";
}

// --- acting ----------------------------------------------------------------

// Every action is a POST with a JSON body. The token authorises it; the content
// type is what stops a page on another origin from sending one — see the `http`
// module for why that pairing carries the weight.
async function act(verb, body) {
  const response = await ask("/api/act/" + verb + "/" + encodeURIComponent(ID) + QUERY, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(body || {}),
  });
  const text = (await response.text()).trim();
  try { return JSON.parse(text); } catch (e) { return { message: text }; }
}

// What an action said, in the one place the page says such things. Kept on
// screen rather than flashed: the message that matters most — a tmux session to
// attach to — is one somebody has to copy.
//
// The generation counts every write, so a flash's timeout can tell whether the
// message still on screen is the one it wrote — clearing unconditionally would
// erase an action's answer that landed in between.
let saidGen = 0;
function report_said(text, ok) {
  saidGen++;
  const node = document.getElementById("said");
  if (!node) return;
  node.className = "said " + (ok ? "ok" : "bad");
  node.textContent = text;
}

// The transient kind, for "copied" and its failures: a note that stayed would
// read as a state rather than a reply.
function saidFlash(text, ok) {
  report_said(text, ok);
  const gen = saidGen;
  setTimeout(() => { if (gen === saidGen) report_said("", true); }, 2600);
}

// The report as something to paste, not to look at: the figures a person
// summarising the session would type, in the order the page leads with them.
function reportMarkdown(r) {
  const out = [];
  out.push("# " + (r.title || r.project || r.session_id));
  const meta = [r.project, r.branch, r.model || r.provider].filter(Boolean).join(" · ");
  if (meta) out.push(meta);
  out.push("");
  // "incl" and "—" are different claims, as on the tiles: one says the plan
  // bundles this, the other that nothing billable was recorded.
  const cost = r.cost.included ? "included in the plan"
    : (r.cost.available ? money(r.cost.total) : "not recorded");
  out.push("- Cost: " + cost);
  out.push("- Tokens: " + tokens(r.tokens.total || (r.tokens.input + r.tokens.output)) +
           " (" + tokens(r.tokens.input) + " in · " + tokens(r.tokens.output) + " out)");
  if (r.context && r.context.max) {
    out.push("- Context: " + Math.round(r.context.percent_to_compact) + "% of the window" +
             " (" + tokens(r.context.used) + " of " + tokens(r.context.max) + ")" +
             (r.context.compactions ? ", " + r.context.compactions + " compactions" : ""));
  }
  if (r.duration) out.push("- Duration: " + r.duration + (r.running ? ", still running" : ""));
  if (r.activity && r.activity.error_rate !== null && r.activity.error_rate !== undefined) {
    out.push("- Tool errors: " + Math.round(r.activity.error_rate * 100) + "%" +
             " (" + (r.activity.tool_errors || 0) + " of " + (r.activity.tool_count || 0) + ")");
  }
  // ×1 is the absence of a loop, not a finding — the repeated ones are the
  // part worth pasting.
  const loops = (r.activity.failures || []).filter((f) => f.count > 1);
  if (loops.length) {
    out.push("", "## Repeated failures");
    for (const f of loops.slice(0, 6)) {
      // One line, capped: a detail can be a whole command's worth of output.
      let detail = String(f.detail || "").split("\n")[0];
      if (detail.length > 120) detail = detail.slice(0, 117) + "";
      out.push("- ×" + f.count + " `" + f.tool + "`" + (detail ? " — `" + detail + "`" : ""));
    }
  }
  if (r.files && r.files.length) {
    out.push("", "## Files it wrote");
    for (const f of r.files) out.push("- " + f);
  }
  return out.join("\n");
}

// navigator.clipboard only answers in a secure context; the textarea detour is
// what a plain http page falls back to. Off-screen rather than hidden, because
// a display:none textarea does not select.
async function copyText(text) {
  if (navigator.clipboard && navigator.clipboard.writeText) {
    try {
      await navigator.clipboard.writeText(text);
      return;
    } catch (e) { /* refused — try the detour */ }
  }
  const ta = el("textarea");
  ta.value = text;
  ta.style.cssText = "position:fixed;top:0;left:0;opacity:0";
  document.body.appendChild(ta);
  ta.select();
  try {
    if (!document.execCommand("copy")) throw new Error("the browser refused");
  } finally {
    ta.remove();
  }
}

function copyButton() {
  const button = el("button", "copymd", "Copy markdown");
  button.type = "button";
  button.title = "Copy this report as a markdown summary";
  button.addEventListener("click", () => {
    if (!REPORT) return;
    copyText(reportMarkdown(REPORT))
      .then(() => saidFlash("Copied — this report as markdown", true))
      .catch((e) => saidFlash("Copy failed: " + String((e && e.message) || e), false));
  });
  return button;
}

async function run(button, verb, body, verb_label) {
  const was = button.textContent;
  button.disabled = true;
  button.textContent = "";
  report_said("", true);
  try {
    const done = await act(verb, body);
    report_said(done.message || (verb_label + " done"), true);
  } catch (e) {
    report_said(String(e.message || e), false);
  } finally {
    button.disabled = false;
    button.textContent = was;
  }
}

// The buttons that are not a prompt: put this session back, or give its work to
// somebody else. Absent entirely when this run serves no actions, rather than
// present and refusing.
function actionBar(r, agents) {
  if (!CAN_ACT) return null;
  const bar = el("div", "acts");

  const resume = el("button", null, r.running ? "Reattach" : "Resume");
  resume.title = "Start this session's own harness back up on this transcript, in tmux";
  resume.addEventListener("click", () => run(resume, "resume", {}, "Resume"));
  bar.appendChild(resume);

  if (agents.length) {
    const pick = el("select");
    pick.title = "Which agent takes this session's work";
    for (const agent of agents) {
      const option = el("option", null, agent);
      option.value = agent;
      pick.appendChild(option);
    }
    const hand = el("button", null, "Hand off →");
    hand.title = "Write a brief of this session and start the chosen agent on it, here";
    hand.addEventListener("click", () => run(hand, "handoff", { agent: pick.value }, "Handoff"));
    bar.appendChild(pick);
    bar.appendChild(hand);
  }
  return bar;
}

// The prompt box. One line, because that is what a pty submit is: the server
// refuses a newline rather than sending half a paragraph, so the box will not
// pretend to take one.
//
// While the session is stopped the box doubles as the resume button — "resume
// it first" asked of a dead input is a chore, a button that does it is not.
function composer(r) {
  if (!CAN_ACT) return null;
  const form = el("form", "say");
  form.id = "say";
  const input = el("input");
  input.type = "text";
  input.maxLength = 4000;
  input.autocomplete = "off";
  const send = el("button");
  send.type = "submit";
  composerMode(input, send, !!r.running);
  form.appendChild(input);
  form.appendChild(send);
  form.addEventListener("submit", async (event) => {
    event.preventDefault();
    send.disabled = true;
    try {
      if (send.dataset.mode === "resume") {
        const done = await act("resume", {});
        report_said(done.message || "Resumed", true);
      } else {
        const text = input.value.trim();
        if (!text) return;
        const done = await act("send", { text });
        report_said(done.message || "Sent", true);
        input.value = "";
        // The turn takes a moment to reach the transcript, so the refresh is
        // deliberately late rather than immediate-and-empty.
        setTimeout(refreshChat, 1200);
      }
    } catch (e) {
      report_said(String(e.message || e), false);
    } finally {
      send.disabled = false;
      input.focus();
    }
  });
  return form;
}

// Which of the two jobs the composer's button is doing right now — answering a
// live agent, or putting a stopped one back. Shared by the load-time draw and
// the stream, so a session that starts under you becomes answerable without a
// reload.
function composerMode(input, send, running) {
  input.disabled = !running;
  input.placeholder = running
    ? "Answer this session…"
    : "Nothing is running this session";
  send.dataset.mode = running ? "send" : "resume";
  send.textContent = running ? "Send" : "Resume";
  send.disabled = false;
  send.title = running ? "" : "Start this session's harness back up on this transcript";
}

// --- what it can reach -----------------------------------------------------

function fileRules(heading, files) {
  if (!files || !files.length) return null;
  const s = block(heading);
  const card = el("div", "card");
  for (const file of files) {
    const node = el("details", "rule");
    node.dataset.present = String(!!file.present);
    const sum = el("summary");
    sum.appendChild(el("span", "path", file.path));
    sum.appendChild(el("span", "pill", file.scope));
    sum.appendChild(el("span", "faint", file.present ? bytes(file.bytes) : "not there"));
    node.appendChild(sum);
    if (file.present) {
      node.appendChild(el("pre", null, (file.head || "") + (file.clipped ? "\n\n… cut for length" : "")));
    }
    card.appendChild(node);
  }
  s.appendChild(card);
  return s;
}

const bytes = (n) => {
  const v = Number(n) || 0;
  if (v >= 1048576) return (v / 1048576).toFixed(1) + " MB";
  if (v >= 1024) return Math.round(v / 1024) + " KB";
  return v + " B";
};

function accessView(a) {
  const parts = [];

  const s = block("In scope", "The files and servers that apply to a session in this directory — which is checkable. What the harness actually loaded is its own business, and this does not claim to know it.");
  const card = el("div", "card pad");
  const dl = el("dl", "kv");
  const row = (k, v) => { if (v) { dl.appendChild(el("dt", null, k)); dl.appendChild(el("dd", null, v)); } };
  row("Directory", a.cwd + (a.cwd_exists ? "" : " (gone)"));
  row("Branch", a.branch);
  row("Harness", a.harness);
  row("Model", a.model);
  if (a.permission) row("Permission", a.permission + "" + (a.permission_detail || ""));
  if (a.pid) row("Process", "pid " + a.pid);
  card.appendChild(dl);
  if (a.note) card.appendChild(el("p", "note", a.note));
  s.appendChild(card);
  parts.push(s);

  parts.push(fileRules("Instructions", a.instructions));
  parts.push(fileRules("Settings", a.configs));

  if (a.mcp && a.mcp.length) {
    const m = block("MCP servers", "Tools reaching outside this machine's filesystem come from here.");
    const card = el("div", "card pad scroll-x");
    const table = el("table");
    const head = el("tr");
    for (const label of ["Server", "Scope", "Command"]) head.appendChild(el("th", null, label));
    table.appendChild(head);
    for (const server of a.mcp) {
      const tr = el("tr");
      tr.appendChild(el("td", "mono", server.name));
      tr.appendChild(el("td", null, server.scope));
      tr.appendChild(el("td", "mono dim", server.command || ""));
      table.appendChild(tr);
    }
    card.appendChild(table);
    m.appendChild(card);
    parts.push(m);
  }

  if (a.skills && a.skills.length) {
    const k = block("Skills", a.skills_dir || "");
    const card = el("div", "card");
    for (const skill of a.skills) {
      const node = el("div", "rule");
      const line = el("div", null, null);
      line.style.padding = "9px 14px";
      line.appendChild(el("span", "mono", skill.name));
      if (skill.description) {
        line.appendChild(el("span", "faint", " " + skill.description));
      }
      node.appendChild(line);
      card.appendChild(node);
    }
    k.appendChild(card);
    parts.push(k);
  }

  if (a.tools && a.tools.length) {
    const t = block("Tools it has used", "What it reached for, not what it was offered.");
    const card = el("div", "card pad");
    const chips = el("div", "chips");
    for (const tool of a.tools) {
      const chip = el("span", "chip", tool.name);
      chip.appendChild(el("span", "n", tool.count));
      chips.appendChild(chip);
    }
    card.appendChild(chips);
    t.appendChild(card);
    parts.push(t);
  }

  if (a.hooks && a.hooks.length) {
    const h = block("cctop's own hooks", "Whether this harness reports its state to cctop as it happens, rather than being read off disk after the fact.");
    const card = el("div", "card pad scroll-x");
    const table = el("table");
    const head = el("tr");
    for (const label of ["Harness", "Scope", "State", "File"]) head.appendChild(el("th", null, label));
    table.appendChild(head);
    for (const hook of a.hooks) {
      const tr = el("tr");
      tr.appendChild(el("td", null, hook.harness));
      tr.appendChild(el("td", null, hook.scope));
      const state = el("td");
      const cls = hook.state === "installed" ? "" : hook.state === "absent" ? "" : hook.state === "broken" ? "bad" : "warn";
      state.appendChild(el("span", "pill " + cls, hook.state));
      if (hook.detail) state.appendChild(el("span", "faint", " " + hook.detail));
      tr.appendChild(state);
      tr.appendChild(el("td", "mono dim", hook.path));
      table.appendChild(tr);
    }
    card.appendChild(table);
    h.appendChild(card);
    parts.push(h);
  }

  if (a.writes && a.writes.length) {
    const w = block("Written lately");
    const card = el("div", "card pad");
    const files = el("div", "files");
    for (const path of a.writes) files.appendChild(el("div", null, path));
    card.appendChild(files);
    w.appendChild(card);
    parts.push(w);
  }

  return parts.filter(Boolean);
}

// --- load ------------------------------------------------------------------

// One pane per view, built on first sight and kept. The report cost a full
// transcript parse to build; switching away from it and back must not repeat
// that, which is why these are panes rather than pages.
const PANES = {};
let CHAT_TIMER = null;
// What the events stream last said about this session, or null until the
// first event or the report itself answers — whichever lands first.
let LIVE = null;
// The session's real id once the report has answered. The URL carries any
// unambiguous prefix, so until then matching has to accept one.
let SESSION = ID;
// The loaded report, kept for the markdown copy.
let REPORT = null;
// What the conversation looked like at the last build — see chatSig.
let CHAT_SIG = null;
// The newest window the server sent, kept for `supported`/`note` and the
// change signature — the turns drawn come from TURNS, not straight from it.
let LAST_CHAT = null;
// Every turn fetched so far, oldest first, each carrying the transcript-wide
// `seq` the server numbers it with. A poll merges over the tail; a paged-back
// fetch (`?before=`) prepends older turns — so a turn's `seq` is the only name
// that stays true across both, and it is what the DOM ids, deep links and the
// find box all use.
let TURNS = [];
// How many of a long conversation's turns are drawn: the newest CHAT_CHUNK,
// one chunk more per click. The tail is the part that is live; drawing all of
// a 200-turn session is the stall, not the poll.
const CHAT_CHUNK = 120;
let chatShown = CHAT_CHUNK;
// Turns the transcript holds before everything fetched — the seq of the
// oldest held turn, which is exactly the count of what came before it.
const earlierCount = () =>
  TURNS.length ? TURNS[0].seq : (LAST_CHAT ? LAST_CHAT.earlier || 0 : 0);

// Fold a response into TURNS: a shared seq is the same turn re-read, and the
// fresh copy wins — for the tail that is a turn still being written.
function mergeChat(chat) {
  const fresh = new Map((chat.turns || []).map((t) => [t.seq, t]));
  TURNS = TURNS.filter((t) => !fresh.has(t.seq))
    .concat(chat.turns || [])
    .sort((a, b) => a.seq - b.seq);
}
// The "new activity" pill, built on first use.
let MORE = null;
// The turn half of a "#chat/turn-N" link, kept until the conversation is
// drawn — it cannot be scrolled to before it exists.
let wantTurn = null;
// The find box's parts and what it currently matches, plus the all-tools
// fold. All of it lives outside the turns because drawChat replaces the
// turns on every poll.
let SEEK = null;
let seekHits = [];
let seekAt = -1;
let toolsOpen = false;

// Compact or comfortable, kept across visits under its own key. The choice
// rides on #talk as data-density so it survives the poll's rebuild of what
// is inside it.
let density = "comfortable";
try {
  if (localStorage.getItem("cctop-density") === "compact") density = "compact";
} catch (e) { /* no store, no memory — comfortable it is */ }

function applyDensity() {
  const talk = document.getElementById("talk");
  if (talk) talk.dataset.density = density;
}

// localStorage["cctop-seen"] is the visit ledger shared with the dashboard:
// {<session id>: {"seq": N, "at": ms}} — the newest turn seq the session was
// last seen at, and when. The seq is what this page marks against; `at` is
// written too because the dashboard reads it for its own badge. Every access
// is try/catch'd — private windows throw on localStorage, and a page about a
// conversation must not die on bookkeeping.
let seenDone = false;
let SEEN_BASE = null;
// The stored seq as this visit found it: the line between "already read" and
// "new". Captured once — re-reading after seenRecord would move the line and
// the marks would vanish under the reader on the next poll.
function seenSeq() {
  if (!seenDone) {
    seenDone = true;
    try {
      const all = JSON.parse(localStorage.getItem("cctop-seen")) || {};
      const entry = all[SESSION];
      const seq = entry && Number(entry.seq);
      SEEN_BASE = isFinite(seq) ? seq : null;
    } catch (e) {
      SEEN_BASE = null;
    }
  }
  return SEEN_BASE;
}
// Written after the marks, which compare against the value from before this
// visit — mark first, then record. The newest fetched seq is what "seen"
// means: everything up to it was on offer this visit.
function seenRecord() {
  if (!TURNS.length) return;
  const max = TURNS[TURNS.length - 1].seq;
  try {
    const all = JSON.parse(localStorage.getItem("cctop-seen")) || {};
    const prev = all[SESSION] && Number(all[SESSION].seq);
    all[SESSION] = { seq: Math.max(max, isFinite(prev) ? prev : 0), at: Date.now() };
    localStorage.setItem("cctop-seen", JSON.stringify(all));
  } catch (e) { /* bookkeeping only — the marks stay best-effort */ }
}

function show(name) {
  for (const [key, pane] of Object.entries(PANES)) pane.hidden = key !== name;
  for (const button of document.querySelectorAll("nav.views button")) {
    button.setAttribute("aria-selected", String(button.dataset.view === name));
  }
  // A deep link already names this view — "#chat/turn-3" is the chat, plus
  // where in it. Rewriting it to the bare name would strip the turn.
  if (!location.hash.startsWith("#" + name + "/")) location.hash = name;
}

function startChatPoll() {
  if (!CHAT_TIMER) CHAT_TIMER = setInterval(refreshChat, 5000);
}
function stopChatPoll() {
  if (CHAT_TIMER) { clearInterval(CHAT_TIMER); CHAT_TIMER = null; }
}

// Whether a poll brought anything worth redrawing, without stringifying a
// conversation that can run to thousands of turns. What changes while a
// session is live is the count, and the tail: the last turn grows and its
// last tool resolves, everything before them is already written.
function chatSig(chat) {
  const turns = chat.turns || [];
  const last = turns[turns.length - 1] || {};
  const tools = last.tools || [];
  const lastTool = tools[tools.length - 1] || {};
  const result = lastTool.result;
  return [turns.length, chat.earlier || 0, last.kind || "", last.ts || "",
          (last.text || "").length, tools.length,
          result === undefined || result === null ? -1 : String(result).length]
    .join(":");
}

// "Following" means within a short scroll of the end: close enough that the
// reader is clearly watching the tail rather than reading something above it.
const nearBottom = () =>
  window.innerHeight + window.scrollY >= document.documentElement.scrollHeight - 80;

// The floating "new activity" pill. Kept inside the chat pane rather than on
// the page so it hides with the view — a note about the conversation has no
// business floating over the report.
function moreActivity(on) {
  if (!MORE) {
    MORE = el("button", "more", "new activity ↓");
    MORE.type = "button";
    MORE.addEventListener("click", () => {
      window.scrollTo(0, document.documentElement.scrollHeight);
      moreActivity(false);
    });
    PANES.chat.appendChild(MORE);
  }
  MORE.hidden = !on;
}

// Reaching the bottom is the reader saying they are caught up — the pill's
// own dismissal, and it has to work for a scroll wheel as much as the click.
window.addEventListener("scroll", () => {
  if (MORE && !MORE.hidden && nearBottom()) moreActivity(false);
}, { passive: true });

// --- finding a turn ---------------------------------------------------------

// The chat pane's own controls: a find box over the drawn turns and the
// all-tools fold. Built once and kept — they sit above #split rather than
// inside #talk, which drawChat empties on every poll.
function chatTools() {
  const bar = el("div", "chattools");
  const input = el("input");
  input.type = "search";
  input.autocomplete = "off";
  input.placeholder = "Find in the conversation…";
  input.setAttribute("aria-label", "Find in the conversation");
  const count = el("span", "n");
  const prev = el("button", null, "");
  prev.type = "button";
  prev.title = "Previous matching turn";
  const next = el("button", null, "");
  next.type = "button";
  next.title = "Next matching turn";
  prev.disabled = next.disabled = true;
  const tools = el("button", null, "Tools ▸");
  tools.type = "button";
  tools.title = "Open every tool call in the conversation";
  input.addEventListener("input", () => { seekAt = -1; applySeek(); });
  // Enter walks the matches like a find bar does; Shift+Enter walks back.
  // Escape empties it through the input path so the marks and count leave
  // with the text, then hands the page back its keys.
  input.addEventListener("keydown", (e) => {
    if (e.key === "Enter") { e.preventDefault(); seekMove(e.shiftKey ? -1 : 1); }
    else if (e.key === "Escape") {
      e.preventDefault();
      input.value = "";
      input.dispatchEvent(new Event("input"));
      input.blur();
    }
  });
  prev.addEventListener("click", () => seekMove(-1));
  next.addEventListener("click", () => seekMove(1));
  tools.addEventListener("click", () => {
    toolsOpen = !toolsOpen;
    tools.textContent = toolsOpen ? "Tools ▾" : "Tools ▸";
    tools.title = toolsOpen
      ? "Close every tool call in the conversation"
      : "Open every tool call in the conversation";
    applyTools();
  });
  // Compact or comfortable, persisted — the button says what is set, not
  // what a click would do, because a two-state toggle that names its state
  // needs no guessing.
  const dense = el("button");
  dense.type = "button";
  const denseLabel = () => {
    dense.textContent = "Density: " + density;
    dense.title = density === "compact"
      ? "Switch to the roomier spacing"
      : "Tighter turns — more of the conversation per screen";
  };
  denseLabel();
  dense.addEventListener("click", () => {
    density = density === "compact" ? "comfortable" : "compact";
    try { localStorage.setItem("cctop-density", density); } catch (e) {}
    denseLabel();
    applyDensity();
  });
  const hint = el("span", "n", "j/k · n/N · t · 1–4 · /");
  hint.title = "Keys — j/k or arrows move through turns · Enter opens a turn's tools · " +
               "n/N walk find hits · t folds every tool · 1–4 switch views · / focuses find · Esc clears";
  SEEK = { input, count, prev, next, tools };
  bar.append(input, count, prev, next, tools, dense, hint);
  return bar;
}

// What a turn can be found by: its own text, plus the names, arguments and
// results of its tool calls — the same coverage the drawn textContent gave,
// extended to turns the chunking has not drawn.
const turnText = (t) => [
  t.text,
  ...(t.tools || []).flatMap((x) => [x.name, x.detail, x.full, x.result, ...(x.diff || [])]),
].filter(Boolean).join(" ").toLowerCase();

// What the find box currently matches. The search runs over every fetched
// turn rather than the drawn ones — a hit the chunking hides is still a hit,
// and walking to it draws the window it lives in. Marks are re-applied after
// every drawChat because the poll's rebuild throws the nodes away.
function applySeek() {
  if (!SEEK) return;
  const q = SEEK.input.value.trim().toLowerCase();
  seekHits = q ? TURNS.filter((t) => turnText(t).includes(q)).map((t) => t.seq) : [];
  const hitSet = new Set(seekHits);
  const pane = document.getElementById("talk");
  if (pane) {
    for (const node of pane.querySelectorAll(".turn[id^=turn-]")) {
      node.classList.toggle("hit", hitSet.has(Number(node.id.slice(5))));
      node.classList.remove("current");
    }
  }
  if (seekAt >= seekHits.length) seekAt = seekHits.length - 1;
  if (seekAt >= 0) {
    const on = document.getElementById("turn-" + seekHits[seekAt]);
    if (on) on.classList.add("current");
  }
  SEEK.prev.disabled = SEEK.next.disabled = !seekHits.length;
  // The count covers every turn fetched — only turns the transcript holds
  // that no fetch has reached stay outside it, and the note says so.
  const unsearched = earlierCount();
  SEEK.count.textContent = q
    ? seekHits.length + (seekHits.length === 1 ? " turn" : " turns") +
      (unsearched ? " · earlier not searched" : "")
    : "";
}

// ↑/↓ walk the hits. Landing opens the turn's tool calls too — a match whose
// text lives inside a closed <details> would otherwise scroll to a turn that
// does not show why it matched.
function seekMove(dir) {
  if (!seekHits.length) return;
  // -1 is "not on a hit yet": the first ↓ lands on the first, the first ↑ on
  // the last — the direction the reader asked for, not a step from nowhere.
  seekAt = seekAt < 0
    ? (dir > 0 ? 0 : seekHits.length - 1)
    : (seekAt + dir + seekHits.length) % seekHits.length;
  gotoTurn(seekHits[seekAt]);
}

// The fold is a choice about the conversation, not about the nodes — the poll
// throws the nodes away, so the choice is kept here and replayed onto
// whatever is currently drawn.
function applyTools() {
  const pane = document.getElementById("talk");
  if (!pane) return;
  for (const d of pane.querySelectorAll("details.tool")) d.open = toolsOpen;
}

// A "#chat/turn-N" link names a turn by its transcript seq. One the chunking
// has not drawn is reached by growing the window, and one no fetch has
// reached is paged back to — a deep link into a long conversation lands on
// its turn rather than reporting a miss.
async function gotoTurn(seq) {
  // Each hop is a full transcript parse server-side, so the page-back is
  // bounded: enough to reach any plausible link, not a way to spend the
  // server in a loop.
  let guard = 8;
  while (earlierCount() > seq && guard-- > 0) {
    try {
      const chat = await ask(
        "/api/chat/" + encodeURIComponent(ID) +
          (QUERY ? QUERY + "&" : "?") + "before=" + earlierCount(),
      ).then(asJson);
      mergeChat(chat);
    } catch (e) {
      break;
    }
  }
  // >= rather than ===: a filtered empty turn leaves a gap in the seqs, and
  // the next real turn is the honest landing for a link that names one.
  const pos = TURNS.findIndex((t) => t.seq >= seq);
  if (pos < 0) {
    saidFlash("That turn is not in this conversation", false);
    return;
  }
  if (pos < TURNS.length - chatShown) {
    chatShown = TURNS.length - pos;
    drawChat();
  }
  const turn = document.getElementById("turn-" + TURNS[pos].seq);
  if (!turn) return;
  for (const t of document.querySelectorAll("#talk .turn.current")) {
    t.classList.remove("current");
  }
  turn.classList.add("current");
  for (const d of turn.querySelectorAll("details.tool")) d.open = true;
  turn.scrollIntoView({ block: "center" });
}

// The address bar's token was stripped after load, so the bar gets the bare
// anchor while the clipboard gets the link that opens for someone else.
function linkTurn(seq) {
  const hash = "#chat/turn-" + seq;
  try { history.replaceState(null, "", location.pathname + hash); }
  catch (e) { /* a context that forbids it keeps the URL it had */ }
  copyText(location.origin + location.pathname + QUERY + hash)
    .then(() => saidFlash("Copied — a link to this turn", true))
    .catch((e) => saidFlash("Copy failed: " + String((e && e.message) || e), false));
}

// The redraw, shared by the poll, "show earlier" and the deep links — all of
// them draw the same held conversation, so it takes no argument.
function drawChat() {
  const pane = document.getElementById("talk");
  const say = pane.querySelector("form.say");
  pane.replaceChildren(conversation(LAST_CHAT));
  // The composer is part of this pane and holds what someone is typing, so it
  // is moved across rather than rebuilt underneath them.
  if (say) pane.appendChild(say);
  // Per-turn state the rebuilt nodes cannot keep: the fold choice and the
  // find box's marks are replayed onto whatever was just drawn.
  applyTools();
  applySeek();
  // Marked against the stored seq first, then the ledger moves to the newest
  // fetched seq — in that order, so the marks this draw made are the ones a
  // reader was just shown.
  seenRecord();
  // The keyboard selection is kept as a seq for exactly this: the nodes are
  // new, the seq is not.
  if (selSeq !== null) {
    const sel = document.getElementById("turn-" + selSeq);
    if (sel) sel.classList.add("sel");
  }
}

async function refreshChat() {
  const pane = document.getElementById("talk");
  if (!pane) return;
  try {
    const response = await ask("/api/chat/" + encodeURIComponent(ID) + QUERY);
    const chat = await asJson(response);
    const sig = chatSig(chat);
    if (sig === CHAT_SIG) {
      // A poll that changed nothing must not redraw: every rebuild closes the
      // <details> a reader has open under them.
      offline(null);
      return;
    }
    const first = CHAT_SIG === null;
    const wasNear = nearBottom();
    CHAT_SIG = sig;
    LAST_CHAT = chat;
    mergeChat(chat);
    drawChat();
    if (wasNear) {
      // Pinned to the tail: a rebuild must not scroll the newest turn out from
      // under someone watching it arrive.
      window.scrollTo(0, document.documentElement.scrollHeight);
      moreActivity(false);
    } else if (!first) {
      // Scrolled up on purpose: say there is more rather than taking the page
      // somewhere nobody asked it to go. The first fill is exempt — it is the
      // whole conversation arriving, not new activity.
      moreActivity(true);
    }
    offline(null);
  } catch (e) {
    // A poll that fails when there is already a conversation on screen is a
    // connection problem, not an empty session: keep what is there and say so.
    if (pane.querySelector(".card")) offline(String(e.message || e));
    else {
      pane.replaceChildren(el("div", "empty", String(e.message || e)));
      // The turns are gone, so the find box's marks and count go with them.
      applySeek();
    }
  }
}

// --- live state ------------------------------------------------------------

// What the session is doing now, drawn the way the dashboard's rows draw it —
// the same dot, the same pill words. "working" is a pill here and not a colour
// alone because this header has no other sign the page is still live.
function liveState(s) {
  const dot = document.getElementById("live-dot");
  if (dot) dot.className = "dot " + (s.running || s.state === "error" ? s.state : "idle");
  const holder = document.getElementById("live-pill");
  if (!holder) return;
  holder.replaceChildren();
  let text = null, cls = "pill";
  if (s.running && s.state === "working") { text = "working"; cls = "pill ok"; }
  else if (s.running && s.state === "waiting") { text = "waiting on you"; cls = "pill warn"; }
  // Louder than "waiting on you", deliberately: that one is your move whenever
  // you get to it, this one is an agent stopped mid-tool until you say.
  else if (s.running && s.state === "asking") { text = "needs permission"; cls = "pill bad"; }
  // Present tense is a claim about now; for a stopped session the error is
  // something that happened, and the "ago" beside it already says when.
  else if (s.state === "error") { text = s.running ? "api error" : "ended on an api error"; cls = "pill bad"; }
  if (text) holder.appendChild(el("span", cls, text));
}

// The composer was drawn from the report's once-read `running`; the stream is
// the truth after that, so a session that stops stops looking answerable and
// one that starts becomes answerable without a reload.
function liveComposer(s) {
  const form = document.getElementById("say");
  if (!form) return;
  composerMode(form.querySelector("input"), form.querySelector("button"), !!s.running);
}

// One entry of the array every `sessions` event carries.
function applyLive(list) {
  const s = list.find((row) => row.session_id === SESSION) ||
            list.find((row) => row.session_id.startsWith(SESSION));
  if (!s) return;
  const was = LIVE;
  LIVE = { running: !!s.running, state: s.state };
  liveState(s);
  liveComposer(s);
  // The poll follows the stream rather than the report's once-read `running`:
  // a session that starts after the page opened gets followed, and one that
  // stops stops costing a transcript read every five seconds. The read on the
  // transition is because the final turns can postdate the last poll — they
  // land here rather than asking anyone to reload.
  const loaded = !!(PANES.chat && PANES.chat.dataset.loaded);
  if (s.running && loaded) startChatPoll();
  if (!s.running) {
    stopChatPoll();
    if (loaded && was && was.running) refreshChat();
  }
}

// The subscription is the dashboard's: one `sessions` event per refresh.
// EventSource reconnects on its own, but only from a stream that broke — an
// answer that was never a stream (the 502 page a tunnel serves once its far
// end is gone) closes it for good, so a closed source is reopened on a timer.
let source;
function connect() {
  source = new EventSource("/api/events" + QUERY);
  source.addEventListener("sessions", (event) => {
    try { applyLive(JSON.parse(event.data)); } catch (e) { /* a bad event is skipped, not fatal */ }
  });
  source.addEventListener("error", () => {
    if (source.readyState === EventSource.CLOSED) setTimeout(connect, 5000);
  });
}

// The page's one blocking read. It is wrapped rather than run bare because a
// connection that drops during it leaves nothing on screen to recover from,
// so it comes back on its own instead of asking someone to reload.
function load() {
  ask("/api/report/" + encodeURIComponent(ID) + QUERY)
    .then(asJson)
    .then(async (r) => {
      document.title = "cctop — " + (r.title || r.project || r.session_id);
      // The token has done its job: the page carries it in TOKEN for every
      // request it will ever make, so it need not keep sitting in the address
      // bar and in every screenshot of it.
      try {
        history.replaceState(null, "", location.pathname + location.hash);
      } catch (e) { /* a context that forbids it keeps the URL it opened with */ }
      const main = document.getElementById("main");
      main.replaceChildren();
      main.appendChild(subject(r));
      REPORT = r;
      SESSION = r.session_id;
      // The report's own reading is the state until the stream says otherwise —
      // unless the stream already has, which is the fresher of the two.
      if (!LIVE) LIVE = { running: !!r.running, state: r.state };
      liveState(LIVE);

      // Which agents this machine has, and whether this run acts at all. Asked
      // once: it is a property of the server, not of the session.
      let agents = [];
      if (CAN_ACT) {
        try {
          agents = (await asJson(await ask("/api/agents" + QUERY))).agents || [];
        } catch (e) { /* the buttons that need it simply do not appear */ }
      }
      const bar = actionBar(r, agents);
      if (bar) main.appendChild(bar);
      // The one place the page reports what it did — an action's answer or the
      // copy note. Always there rather than only when this run can act, because
      // "copied" wants the same home.
      const said = el("div", "said", "");
      said.id = "said";
      main.appendChild(said);

      const nav = el("nav", "views");
      main.appendChild(nav);
      if (r.error) main.appendChild(el("div", "banner", "This transcript could not be fully read: " + r.error));

      for (const name of ["chat", "changes", "access", "report"]) {
        const pane = el("div");
        pane.hidden = true;
        PANES[name] = pane;
        main.appendChild(pane);
      }

      // The conversation is one column of the chat view rather than the whole
      // of it, so the terminal can take the other without the poll below
      // throwing the frame away every five seconds.
      const split = el("div", "split");
      split.id = "split";
      const talk = el("div", "talk");
      talk.id = "talk";
      const side = el("aside", "termside");
      side.id = "termside";
      side.hidden = true;
      split.append(talk, side);
      // The pane's controls sit beside the split rather than inside #talk,
      // which the poll rebuilds — in there they would not survive five
      // seconds, let alone a typing reader.
      PANES.chat.appendChild(chatTools());
      PANES.chat.appendChild(split);
      applyDensity();

      // The report's own sections, split between the two views they belong to.
      // Cost, failures and the window are a report; a diff and a file list are
      // what changed. Nothing is rendered twice.
      PANES.changes.replaceChildren(
        ...[diffs, files].map((part) => part(r)).filter(Boolean)
      );
      PANES.report.replaceChildren(
        tiles(r),
        ...[failures, breakdown, windowChart, heaviest, spend, slowest, toolTable, callLog, subagents]
          .map((part) => part(r))
          .filter(Boolean)
      );

      const labels = {
        chat: ["Conversation", ""],
        changes: ["Changes", r.diffs ? r.diffs.length : 0],
        access: ["Access", ""],
        report: ["Report", ""],
      };
      for (const [name, [label, count]] of Object.entries(labels)) {
        const button = el("button", null, label);
        button.dataset.view = name;
        button.setAttribute("aria-selected", "false");
        if (count) button.appendChild(el("span", "n", count));
        button.addEventListener("click", () => open_view(name, r));
        nav.appendChild(button);
      }

      // Not a view: the point of the terminal is to be beside the conversation
      // rather than instead of it, and a fifth button in the same row that
      // switched views could only replace what it is meant to sit next to.
      // Disabled rather than clickable when the report already knows there is
      // no terminal to reach — a 409 is a worse way to learn that.
      if (CAN_ACT) {
        const term = terminalButton();
        if (!r.terminal) {
          term.disabled = true;
          term.title = "Nothing to show — the agent is not running in a multiplexer cctop can reach";
        }
        nav.appendChild(term);
      }
      nav.appendChild(copyButton());

      const wanted = location.hash.replace(/^#/, "");
      // "#chat/turn-12" is a link into the conversation: it opens the chat
      // view, and the turn half waits in wantTurn until the chat is drawn.
      const jump = wanted.match(/^chat\/turn-(\d+)$/);
      if (jump) wantTurn = Number(jump[1]);
      open_view(jump ? "chat" : (labels[wanted] ? wanted : "chat"), r);
    })
    .catch((e) => {
      document.getElementById("main").replaceChildren(
        el("div", "empty", String(e.message || e) + " Trying again…")
      );
      setTimeout(load, 5000);
    });
}
load();
connect();

// --- the agent's own terminal -------------------------------------------

// A toggle rather than a view, and only where this run can act at all: the link
// it fetches types into a live agent, and a read-only cctop mints nothing.
function terminalButton() {
  const button = el("button", "toggle", "Terminal");
  button.type = "button";
  button.title = "Show this agent's own terminal beside the conversation";
  button.setAttribute("aria-pressed", "false");
  button.addEventListener("click", () => toggleTerminal(button));
  return button;
}

// Closing removes the frame rather than hiding it. The frame holds a live
// socket to the multiplexer, and one left open behind a `hidden` is a terminal
// still attached to an agent nobody is watching.
function closeTerminal(button) {
  const side = document.getElementById("termside");
  if (side) {
    side.replaceChildren();
    side.hidden = true;
  }
  const split = document.getElementById("split");
  if (split) split.classList.remove("with-term");
  button.setAttribute("aria-pressed", "false");
}

async function toggleTerminal(button) {
  const side = document.getElementById("termside");
  const split = document.getElementById("split");
  if (!side || !split) return;
  if (button.getAttribute("aria-pressed") === "true") return closeTerminal(button);

  button.setAttribute("aria-pressed", "true");
  button.disabled = true;
  side.hidden = false;
  split.classList.add("with-term");
  side.replaceChildren(el("div", "empty", "Opening this agent's terminal…"));
  try {
    // Minted per opening, never cached: the link is a shell credential, and a
    // page that kept one would be handing out the last reader's door.
    const terminal = await act("terminal", {});
    const head = el("div", "head");
    head.appendChild(el("span", null, "This session's terminal"));
    const close = el("button", null, "Close");
    close.type = "button";
    close.addEventListener("click", () => closeTerminal(button));
    head.appendChild(close);

    // A link and not a frame, because rmux's browser terminal refuses to be
    // one: share.rmux.io sends `frame-ancestors 'none'`, so any page that
    // embeds it gets an empty rectangle and a console error. A window of its
    // own is the nearest thing to beside-the-conversation that a page is
    // allowed to open — it floats over the desktop rather than hiding this one
    // behind a tab, and it can be dragged next to it.
    const card = el("div", "card pad termcard");
    const open = el("a", "open", "Open the terminal");
    open.href = terminal.url;
    // Still a real link with a real href: a popup blocker, or a middle click,
    // then does the ordinary thing rather than nothing at all. `noopener` is
    // named in both places — the window must not get a handle on this page.
    open.target = "_blank";
    open.rel = "noopener";
    open.addEventListener("click", (ev) => {
      // Opened from inside the click, with no `await` in between, which is what
      // keeps it a user gesture and out of the blocker.
      const win = window.open(
        terminal.url, "cctop-terminal",
        "popup,noopener,width=1024,height=720,left=" +
          Math.max(0, screen.availWidth - 1044) + ",top=60"
      );
      if (win) ev.preventDefault();
    });
    card.appendChild(open);
    card.appendChild(el(
      "div", "why",
      "It opens in a window of its own, which you can put beside this one: " +
      "rmux's terminal page refuses to be framed, so it cannot be drawn inside."
    ));
    card.appendChild(el(
      "div", "why",
      terminal.tunnelled
        ? "It reaches this machine through rmux's own tunnel, so it works from wherever you are."
        : "It is served from the machine cctop runs on, so it only opens from a browser on it."
    ));
    card.appendChild(el(
      "div", "why bad",
      "Whoever opens that link can type into this agent — it is a shell, not a prompt box."
    ));
    side.replaceChildren(head, card);
  } catch (e) {
    // Reported where every other failed action reports — under the buttons,
    // at the top. Left in the column instead, the sentence would sit below a
    // conversation long enough that nobody would ever see it.
    closeTerminal(button);
    report_said(String(e.message || e), false);
  } finally {
    button.disabled = false;
  }
}

// Fetched on first sight rather than up front: a conversation and an access
// reading are each another pass over the disk, and the report is already one.
async function open_view(name, r) {
  show(name);
  if (name === "chat" && !PANES.chat.dataset.loaded) {
    PANES.chat.dataset.loaded = "1";
    document.getElementById("talk").replaceChildren(el("div", "empty", "Reading the conversation…"));
    await refreshChat();
    const say = composer(r);
    if (say) document.getElementById("talk").appendChild(say);
    // Drawn from the report's `running`, corrected by the stream if it already
    // knows better — a session that started or stopped since the page loaded.
    if (LIVE) liveComposer(LIVE);
    // A running session is still saying things, so its conversation follows
    // along. Which it is, the stream says — not the once-read report: a session
    // that stopped since the page opened would otherwise be polled forever,
    // and one that started would never be.
    if (LIVE ? LIVE.running : r.running) startChatPoll();
    // A deep link's turn can only be scrolled to once the conversation is
    // drawn, so it waited for this rather than racing the fetch.
    if (wantTurn !== null) {
      const index = wantTurn;
      wantTurn = null;
      gotoTurn(index);
    }
    // A "?find=" seeds the box on the first draw — through the input path so
    // the marks and count behave as if it were typed — then walks to the
    // first hit, which is what the dashboard's search link was pointing at.
    if (findSeed) {
      const seed = findSeed;
      findSeed = "";
      SEEK.input.value = seed;
      SEEK.input.dispatchEvent(new Event("input"));
      seekMove(1);
    }
  }
  if (name === "access" && !PANES.access.dataset.loaded) {
    PANES.access.dataset.loaded = "1";
    PANES.access.replaceChildren(el("div", "empty", "Reading what it can reach…"));
    try {
      const response = await ask("/api/access/" + encodeURIComponent(ID) + QUERY);
      PANES.access.replaceChildren(...accessView(await asJson(response)));
    } catch (e) {
      // Read once and kept — but a read that failed is not a reading, so the
      // next visit to this view asks again rather than showing the error for
      // as long as the page is open.
      delete PANES.access.dataset.loaded;
      PANES.access.replaceChildren(el("div", "empty", String(e.message || e)));
    }
  }
}

// --- the keys ---------------------------------------------------------------

// Every page-level key shares this guard — the same one the dashboard uses:
// none of them may fire while the reader is typing, in the find box, the
// composer, or anything editable.
const typing = (t) =>
  t instanceof HTMLElement &&
  (t.isContentEditable || /^(INPUT|SELECT|TEXTAREA)$/.test(t.tagName));

// The keyboard selection, kept as a seq rather than a node — the poll
// rebuilds the turn nodes and a seq is the name that survives the rebuild.
let selSeq = null;
const listedTurns = () => [...document.querySelectorAll("#talk .turn")];
const chatVisible = () => !!(PANES.chat && !PANES.chat.hidden);

function moveSel(dir) {
  const turns = listedTurns();
  if (!turns.length) return;
  const at = turns.findIndex((n) => n.id === "turn-" + selSeq);
  // From nothing, j lands on the first turn and k on the last; past either
  // end the mark just stays where it is.
  const next = at < 0
    ? (dir > 0 ? turns[0] : turns[turns.length - 1])
    : turns[Math.min(turns.length - 1, Math.max(0, at + dir))];
  selSeq = Number(next.id.slice(5));
  for (const n of turns) n.classList.toggle("sel", n === next);
  next.scrollIntoView({ block: "nearest" });
}

function clearSel() {
  selSeq = null;
  for (const n of listedTurns()) n.classList.remove("sel");
}

document.addEventListener("keydown", (e) => {
  if (e.ctrlKey || e.metaKey || e.altKey || typing(e.target)) return;
  // The view digits work from anywhere on the page; the rest are the
  // conversation's, and a hidden conversation takes no keys.
  if (/^[1-4]$/.test(e.key)) {
    const buttons = [...document.querySelectorAll("nav.views button[data-view]")];
    const button = buttons[Number(e.key) - 1];
    if (button) {
      e.preventDefault();
      button.click();
    }
    return;
  }
  if (!chatVisible()) return;
  if (e.key === "j" || e.key === "ArrowDown") {
    e.preventDefault();
    moveSel(1);
  } else if (e.key === "k" || e.key === "ArrowUp") {
    e.preventDefault();
    moveSel(-1);
  } else if (e.key === "Enter" && selSeq !== null) {
    // A focused link or button already owns Enter; the selection borrows it
    // only when nothing else is answering.
    if (/^(A|BUTTON|SUMMARY)$/.test(e.target.tagName)) return;
    const node = document.getElementById("turn-" + selSeq);
    if (!node) return;
    e.preventDefault();
    const tools = [...node.querySelectorAll("details.tool")];
    if (tools.length) {
      // "Toggle" means open them all unless they already are: flipping each
      // on a half-open turn would trade one mixed state for its mirror.
      const opening = tools.some((d) => !d.open);
      for (const d of tools) d.open = opening;
    }
  } else if (e.key === "n") {
    seekMove(1);
  } else if (e.key === "N") {
    seekMove(-1);
  } else if (e.key === "t" && SEEK && SEEK.tools) {
    SEEK.tools.click();
  } else if (e.key === "/" && SEEK) {
    e.preventDefault();
    SEEK.input.focus();
    if (SEEK.input.value) SEEK.input.select();
  } else if (e.key === "Escape") {
    let used = false;
    if (SEEK && SEEK.input.value) {
      SEEK.input.value = "";
      SEEK.input.dispatchEvent(new Event("input"));
      used = true;
    }
    if (selSeq !== null) {
      clearSel();
      used = true;
    }
    if (used) e.preventDefault();
  }
});
</script>