cctop 0.7.0

An htop-like terminal monitor for AI coding agent sessions (Claude Code, Codex, Cursor, 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
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
//! Terminal UI: application state, the worker thread, and the event loop.

pub mod columns;
mod input;
pub mod menu;
mod modals;
pub mod panels;
pub mod render;
pub mod spark;
mod table;
pub mod tabs;
pub mod theme;

use crate::cache::UiPrefs;
use crate::cli::Args;
use crate::loader::{Loader, Stats};
use crate::pricing::{Plan, Provider};
use crate::quota::Quota;
use crate::session::{Session, SessionData};
use columns::ColumnId;
use ratatui::crossterm::cursor::Show;
use ratatui::crossterm::event::{
    self, DisableBracketedPaste, DisableMouseCapture, EnableBracketedPaste, EnableMouseCapture,
    Event,
};
use ratatui::crossterm::execute;
use spark::History;
use std::collections::{HashMap, HashSet};
use std::sync::mpsc::{Receiver, Sender, TryRecvError, channel};
use std::time::{Duration, Instant};

/// Baseline gap between usage checks.
///
/// Quota moves slowly, and the endpoints throttle aggressively — a 30s poll was
/// enough to earn a sustained 429 with a ~15 minute `retry-after`. When a
/// provider asks for longer, `retry_delay_secs` honours that instead.
const QUOTA_INTERVAL_SECS: u64 = 300;

/// How often the poller wakes to see whether any provider is due.
const QUOTA_TICK: Duration = Duration::from_secs(10);

/// Gap between full directory walks.
///
/// Only a walk can notice a session that didn't exist before, and it costs one
/// `stat` per transcript ever recorded — thousands of them, nearly all belonging
/// to sessions that ended long ago. A filesystem watch reports creations and
/// removals as they happen, so this is the safety net for whatever the watch
/// misses (or for when no watch could be established at all) rather than the way
/// new sessions are normally found. `r` still forces one immediately.
const FULL_WALK_INTERVAL: Duration = Duration::from_secs(60);

/// Gap between walks while a created file has yet to become a session.
///
/// Short, because this is the window in which a session the user just started is
/// missing from the table; bounded, because the walk is the expensive one and a
/// file may sit there for a while before the model first answers.
const PENDING_WALK_INTERVAL: Duration = Duration::from_secs(3);

/// How long typing has to pause before the query is scanned for.
///
/// A scan reads every transcript on disk, so it waits for a word rather than
/// chasing each character of one. Short enough that finishing a word and
/// looking up finds the results already there.
const SCAN_DEBOUNCE: Duration = Duration::from_millis(300);

/// How long a freshly launched agent is given before a handoff brief is typed
/// at it.
///
/// Tuned against Claude Code and Codex, both of which print a banner and build
/// their prompt before the first keystroke registers. Too short and the line is
/// lost; too long and the user is left looking at an idle agent wondering
/// whether the handoff worked.
const HANDOFF_SETTLE: Duration = Duration::from_secs(3);

/// Shortest query worth reading every transcript for.
const MIN_SCAN_CHARS: usize = 3;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mode {
    List,
    Help,
    Search,
    SortBy,
    AgeFilter,
    /// Confirming deletion of the selected session.
    DeleteConfirm,
    /// Explaining why a running session can't be deleted.
    DeleteBlocked,
    /// Confirming termination of the selected live session.
    KillConfirm,
    /// Confirming that a session already running elsewhere should be resumed
    /// anyway, which puts a second agent on the same transcript.
    ResumeConfirm,
    /// Confirming a quit that would take the hosted agent down with it.
    QuitConfirm,
    /// Explaining why a live session cannot be terminated locally.
    KillBlocked,
    /// Confirming a batch action over all marked sessions.
    BatchConfirm,
    /// Explaining why a batch delete couldn't proceed (a marked session is running).
    BatchDeleteBlocked,
    /// Explaining why a batch kill couldn't proceed (a marked session has no root PID).
    BatchKillBlocked,
    /// Numeric input for the cost floor filter.
    CostFilter,
    /// Text input typed into the selected session's tmux pane.
    SendKeys,
    /// Picking which agent a new tab or split should run.
    Launch,
    /// Everything that can be done to the selected row, in one list.
    RowMenu,
    /// Typing the directory the launcher's pick will start in. Drawn as the
    /// launcher with its `in` line in an editable state, so the list of agents
    /// stays visible while the path is being changed.
    LaunchCwd,
    /// The agent-integration panel: what is installed where, and whether the
    /// agents are actually reporting in.
    Hooks,
    /// Offering to install tmux, a launch having found it missing.
    TmuxInstall,
}

/// Everything [`App::open_tab`] needs beyond the command itself.
///
/// A struct rather than six more parameters: they had already outgrown a
/// readable call, and at a call site `verb: "Attached to"` says what the
/// fifth positional string never did.
struct NewTab<'a> {
    cwd: Option<std::path::PathBuf>,
    /// The thing being opened, as a status message would name it.
    what: &'a str,
    own: tabs::Own,
    /// What happened, for the status line: resumed, reattached, attached.
    verb: &'a str,
    /// The session this pane resumes, when it resumes one.
    resumed: Option<String>,
    /// What to call the tab, when the command would call it badly.
    ///
    /// A launch is its command — a `claude` tab is called `claude`, which is
    /// both true and short. A *resume* is not: its command carries the session
    /// id, and `claude --resume 4ebf1ab4-2ef8-4fb2-a7d5-d445b5026dc9` is 45
    /// characters of tab bar whose only variable part is a uuid nobody reads.
    /// The caller that knows which session this is passes its name instead.
    label: Option<String>,
}

/// How much of a session's name a resumed tab's label carries.
///
/// The bar elides labels itself once it is crowded, but only then — with two
/// tabs open there is room for a whole title, and a title can be a sentence.
/// This is the point past which a tab name stops identifying the session and
/// starts being its own paragraph.
pub(super) const TAB_LABEL_CHARS: usize = 24;

/// A launch that stopped to ask about tmux, and how to pick it up again.
///
/// The launch is re-run from the top rather than resumed mid-way, because
/// answering the question changes the first thing it decides — where the agent
/// is going to live. Both entry points derive everything they need from state
/// the modal does not touch (the table selection, the launcher's snapshot), so
/// running them twice starts one agent, not two.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Deferred {
    /// [`App::resume_selected`], stopped at the ownership decision.
    Resume,
    /// [`App::launch_selected`], stopped at the same place.
    Launch,
}

/// Where the agent picked in `Mode::Launch` ends up.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LaunchInto {
    /// A tab of its own.
    Tab,
    /// Alongside the panes already in the current tab, arranged the given way.
    Split { stacked: bool },
}

/// The pending batch action shown in `Mode::BatchConfirm`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BatchKind {
    Delete,
    Kill,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AgeFilter {
    Day,
    Week,
    Month,
}

impl AgeFilter {
    pub fn max_age_ms(&self) -> i64 {
        match self {
            AgeFilter::Day => 86_400_000,
            AgeFilter::Week => 604_800_000,
            AgeFilter::Month => 2_592_000_000,
        }
    }

    pub fn label(&self) -> &'static str {
        match self {
            AgeFilter::Day => "Last 24 hours",
            AgeFilter::Week => "Last 7 days",
            AgeFilter::Month => "Last 30 days",
        }
    }

    pub fn short(&self) -> &'static str {
        match self {
            AgeFilter::Day => "1 day",
            AgeFilter::Week => "1 week",
            AgeFilter::Month => "1 month",
        }
    }

    pub fn key(&self) -> &'static str {
        match self {
            AgeFilter::Day => "1d",
            AgeFilter::Week => "1w",
            AgeFilter::Month => "1mo",
        }
    }

    pub fn parse(s: &str) -> Option<Self> {
        match s {
            "1d" => Some(AgeFilter::Day),
            "1w" => Some(AgeFilter::Week),
            "1mo" => Some(AgeFilter::Month),
            _ => None,
        }
    }
}

/// Options offered by the age-filter modal, "no filter" last.
pub const AGE_OPTIONS: [Option<AgeFilter>; 4] = [
    Some(AgeFilter::Day),
    Some(AgeFilter::Week),
    Some(AgeFilter::Month),
    None,
];

// ---------------------------------------------------------------------------
// Worker protocol
// ---------------------------------------------------------------------------

enum Request {
    Refresh,
    /// Update the running sessions without re-walking every provider directory.
    RefreshLive,
    /// Extract full data for one session, to populate the bottom panels.
    Data(Box<Session>),
    Delete(Box<Session>),
    Terminate {
        session_key: String,
        pid: u32,
    },
    /// Type a line into the terminal hosting a live session.
    SendKeys {
        pid: u32,
        text: String,
    },
    /// Look for `query` inside every listed session's transcript.
    Scan {
        query: String,
        targets: Vec<crate::session::search::Target>,
    },
    Shutdown,
}

enum Response {
    /// Cheap discovery result, shown before transcript extraction completes.
    Discovered(Vec<Session>),
    /// One row whose transcript has finished loading.
    Annotated(Box<Session>),
    Sessions(Box<(Vec<Session>, Stats)>),
    /// Only the rows that moved during a light refresh, plus recomputed totals.
    /// Shipping these instead of the whole table is the point of the light path:
    /// copying thousands of rows back every couple of seconds is the cost being
    /// avoided.
    LiveRows(Box<(Vec<Session>, Stats)>),
    Data(String, Box<SessionData>),
    Quota(Box<Quota>),
    /// Pricing landed, so cached costs are stale and a reload is due.
    PricingReady,
    /// A newer release exists. Reported once; cctop never updates itself.
    UpdateAvailable(String),
    Terminated {
        session_key: String,
        result: Result<(), String>,
    },
    Deleted {
        session_key: String,
        result: Result<(), String>,
    },
    KeysSent {
        result: Result<(), String>,
    },
    /// One remote machine's snapshot, or why it could not be read.
    Remote {
        host: String,
        snapshot: crate::fleet::Snapshot,
    },
    /// A finished transcript scan: session key -> the text around its match.
    /// The query comes back with it, because the user has usually typed more by
    /// the time a scan over thousands of transcripts lands.
    Scanned {
        query: String,
        hits: HashMap<String, String>,
    },
}

/// Remembered scan results, keyed by session and query. `None` is a remembered
/// *miss*, which is the answer worth caching most: a miss costs a full read of
/// the transcript, a hit usually stops early.
type ScanCache = HashMap<(String, String), Option<String>>;

/// Entries kept before the scan cache is dropped wholesale.
///
/// Reached only by someone who has run many distinct queries over many
/// sessions; forgetting everything then costs one re-scan rather than the
/// bookkeeping an eviction policy would need for a cache this cheap to refill.
const MAX_SCAN_CACHE: usize = 20_000;

/// Search every target's transcript for `needle`, in parallel.
///
/// Running sessions are never cached: their transcripts grow, so today's "not
/// found" is not tomorrow's, and the one case where a stale answer is most
/// visible is the session the user is watching right now.
fn scan(
    cache: &mut ScanCache,
    targets: &[crate::session::search::Target],
    needle: &str,
) -> HashMap<String, String> {
    use rayon::prelude::*;
    let found: Vec<(&crate::session::search::Target, Option<String>)> = targets
        .par_iter()
        .map(|target| {
            let memo = (!target.running)
                .then(|| cache.get(&(target.key.clone(), needle.to_string())))
                .flatten();
            match memo {
                Some(remembered) => (target, remembered.clone()),
                None => (
                    target,
                    crate::session::search::find(target, needle).map(|hit| hit.snippet),
                ),
            }
        })
        .collect();

    if cache.len() + found.len() > MAX_SCAN_CACHE {
        cache.clear();
    }
    let mut hits = HashMap::new();
    for (target, snippet) in found {
        if !target.running {
            cache.insert((target.key.clone(), needle.to_string()), snippet.clone());
        }
        if let Some(snippet) = snippet {
            hits.insert(target.key.clone(), snippet);
        }
    }
    hits
}

/// Owns the `Loader` and does all filesystem and parsing work off the UI thread,
/// so a slow scan can never stall input or rendering.
fn spawn_worker(
    plan: Plan,
    rx: Receiver<Request>,
    tx: Sender<Response>,
) -> std::thread::JoinHandle<()> {
    std::thread::spawn(move || {
        let mut loader = Loader::new();
        let mut sent_initial_discovery = false;
        // The last full walk's rows, kept so a light refresh has something to
        // update in place.
        let mut live_rows: Vec<Session> = Vec::new();
        // What earlier transcript scans found, so refining a query re-reads only
        // what it has to. See `scan`.
        let mut scans: ScanCache = HashMap::new();
        while let Ok(req) = rx.recv() {
            match req {
                Request::Refresh => {
                    // Row-by-row publishing exists so the first table isn't
                    // withheld for the slowest transcript. Later refreshes end
                    // with a `Sessions` payload that replaces everything anyway,
                    // so streaming them too only buys a redundant repaint — at the
                    // cost of one message and one table scan per session, per
                    // refresh, forever.
                    let first_load = !sent_initial_discovery;
                    sent_initial_discovery = true;
                    let sessions = loader.load_progressive(
                        plan,
                        // Only the first table has someone waiting for it.
                        first_load,
                        |sessions| {
                            if first_load {
                                let _ = tx.send(Response::Discovered(sessions.to_vec()));
                            }
                        },
                        |session| {
                            if first_load {
                                let _ = tx.send(Response::Annotated(Box::new(session.clone())));
                            }
                        },
                    );
                    let stats = crate::loader::compute_stats(&sessions);
                    // The light path needs its own copy to carry forward; one clone
                    // per full walk replaces one per refresh.
                    live_rows = sessions.clone();
                    if tx
                        .send(Response::Sessions(Box::new((sessions, stats))))
                        .is_err()
                    {
                        break;
                    }
                }
                Request::RefreshLive => {
                    if live_rows.is_empty() {
                        // Nothing walked yet, so there is nothing to update.
                        continue;
                    }
                    let moved = loader.refresh_live(plan, &mut live_rows);
                    let stats = crate::loader::compute_stats(&live_rows);
                    if tx
                        .send(Response::LiveRows(Box::new((moved, stats))))
                        .is_err()
                    {
                        break;
                    }
                }
                Request::Data(session) => {
                    // The open panels are the one view where staleness shows, so
                    // this path never accepts a backed-off entry.
                    let data = loader.store().session_data_fresh(&session);
                    if tx
                        .send(Response::Data(session.key(), Box::new(data)))
                        .is_err()
                    {
                        break;
                    }
                }
                Request::Delete(session) => {
                    let result = match session.provider {
                        Provider::Claude => crate::session::claude::delete(&session)
                            .map_err(|error| error.to_string()),
                        Provider::Codex => crate::session::codex::delete(&session)
                            .map_err(|error| error.to_string()),
                        Provider::Cursor => crate::session::cursor::delete(&session)
                            .map_err(|error| error.to_string()),
                        Provider::Gemini => crate::session::gemini::delete(&session)
                            .map_err(|error| error.to_string()),
                        Provider::OpenCode => crate::session::opencode::delete(&session)
                            .map_err(|error| error.to_string()),
                        Provider::Pi => {
                            crate::session::pi::delete(&session).map_err(|error| error.to_string())
                        }
                        Provider::Windsurf => crate::session::windsurf::delete(&session)
                            .map_err(|error| error.to_string()),
                    };
                    if result.is_ok() {
                        loader.store().evict(&session);
                    }
                    if tx
                        .send(Response::Deleted {
                            session_key: session.key(),
                            result,
                        })
                        .is_err()
                    {
                        break;
                    }
                }
                Request::Terminate { session_key, pid } => {
                    let result = crate::proc::terminate(pid);
                    if tx
                        .send(Response::Terminated {
                            session_key,
                            result,
                        })
                        .is_err()
                    {
                        break;
                    }
                }
                Request::SendKeys { pid, text } => {
                    let result = crate::inject::send_line(pid, &text);
                    if tx.send(Response::KeysSent { result }).is_err() {
                        break;
                    }
                }
                Request::Scan { query, targets } => {
                    let needle = query.to_ascii_lowercase();
                    let hits = loader.gently(|| scan(&mut scans, &targets, &needle));
                    if tx.send(Response::Scanned { query, hits }).is_err() {
                        break;
                    }
                }
                Request::Shutdown => break,
            }
        }
        loader.store().save();
    })
}

// ---------------------------------------------------------------------------
// Application state
// ---------------------------------------------------------------------------

/// One line of the table: a session, or a subagent shown beneath its parent.
///
/// Rows rather than session indices, because an expanded session occupies
/// several lines and everything that walks the table — scrolling, the cursor,
/// search, the mouse — has to agree on how many there are.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Row {
    Session(usize),
    /// `index` is into the parent's own `subagents`, which is the only place
    /// they exist; they are not sessions and have no entry in `sessions`.
    Subagent {
        parent: usize,
        index: usize,
    },
}

impl Row {
    /// The session this row belongs to, which for a child is its parent.
    ///
    /// Actions are addressed to sessions — a subagent has no process to signal
    /// and no transcript of its own to delete — so every row resolves to one.
    pub fn session(self) -> usize {
        match self {
            Row::Session(i) => i,
            Row::Subagent { parent, .. } => parent,
        }
    }

    pub fn is_subagent(self) -> bool {
        matches!(self, Row::Subagent { .. })
    }
}

pub struct App {
    pub sessions: Vec<Session>,
    /// Whether a first load has landed. Discovery is asynchronous, so an empty
    /// `sessions` means "still looking" until this flips — and "you have none"
    /// is a very different thing to tell someone.
    pub loaded: bool,
    /// The table's lines, after filtering, sorting and expansion.
    pub visible: Vec<Row>,
    /// Subagents whose own `SubagentStop` has arrived.
    ///
    /// Held for the run rather than per session: this is the only word cctop
    /// gets that a background subagent has finished, and the transcript it would
    /// otherwise be inferred from cannot say it. Ids are unique per run, so the
    /// set does not need scoping to a parent.
    pub finished_agents: std::collections::HashSet<String>,
    /// Keys of the sessions showing their subagents.
    ///
    /// Keyed rather than indexed because `sessions` is rebuilt wholesale on
    /// every walk, which would leave an index pointing at whatever sorted into
    /// that slot next.
    pub expanded: std::collections::HashSet<String>,
    pub stats: Stats,
    pub selected: usize,
    pub scroll: usize,
    pub plan: Plan,
    pub mode: Mode,

    pub sort_col: ColumnId,
    pub sort_asc: bool,
    pub sortby_cursor: usize,

    pub search: String,
    /// Search the transcripts as well as the columns.
    ///
    /// Off by default, and deliberately: the metadata filter answers instantly
    /// from memory, while this one reads every transcript on disk. Turning it on
    /// is how you say the reading is worth it.
    pub search_content: bool,
    /// The query [`App::scan_hits`] belongs to.
    ///
    /// Kept because a scan over thousands of transcripts outlives the keystroke
    /// that started it: hits for "flyw" must not be applied to "flywheel".
    pub scan_query: String,
    /// Session key -> the transcript text around its match.
    pub scan_hits: HashMap<String, String>,
    /// A scan is out with the worker.
    pub scanning: bool,
    /// When the query last changed, so a burst of typing costs one scan.
    scan_typed_at: Option<Instant>,
    /// Queries run before, newest first, walked with ↑/↓ in the filter modal.
    pub search_history: Vec<String>,
    /// Where ↑/↓ has walked to in `search_history`, and the query that was
    /// being typed before the walk started, so ↓ can put it back.
    history_cursor: Option<(usize, String)>,
    pub age_filter: Option<AgeFilter>,
    pub age_cursor: usize,
    pub live_only: bool,

    /// Session keys the user has marked (Space) for a batch action.
    pub marked: HashSet<String>,
    /// Sessions whose deletion has been accepted by the worker but not yet
    /// completed. They remain visible until the provider reports success.
    pub deleting: HashSet<String>,
    /// The action pending confirmation in `Mode::BatchConfirm`.
    pub batch: BatchKind,
    /// Follow mode: keep the selected row centered.
    pub follow: bool,
    /// Seconds between automatic refreshes (adjustable live with +/-/=).
    pub refresh_secs: f64,
    /// Only show sessions whose total cost reaches this floor.
    pub cost_floor: f64,
    /// Which Claude profile the launcher will start an agent under, as an index
    /// into [`crate::config::CLAUDE_PROFILES`].
    pub launch_profile: usize,
    /// Which entry of the row menu is under the cursor.
    ///
    /// Only ever points at an entry that can run: the menu draws the blocked
    /// ones to explain them and never lets the cursor rest there. See
    /// [`menu::step`].
    pub menu_cursor: usize,
    /// Raw digits being typed into the cost-floor modal.
    pub cost_input: String,
    /// The directory being typed into the launcher, spelled as the user is
    /// spelling it — `~` and all, expanded only when it is accepted.
    pub launch_cwd_input: String,
    /// Set when the typed directory does not name one, so the field can say so
    /// where it is rather than behind the modal that covers the status line.
    pub launch_cwd_bad: bool,
    /// Line being typed into the selected session's terminal.
    pub send_input: String,
    /// Table viewport height (rows), recorded during draw so Ctrl+U/Ctrl+D can
    /// page by half a screen.
    pub list_height: u16,

    /// Columns the user has hidden outright (`$CCTOP_COLUMNS_HIDE`). These win
    /// over the automatic width-based dropping in [`columns::visible_columns`].
    pub hidden_columns: Vec<ColumnId>,

    /// Scroll offset of the help overlay, which is taller than most terminals.
    pub help_scroll: u16,
    /// Last computed bottom of the help overlay, recorded during draw.
    pub help_max_scroll: u16,

    pub bottom_tab: usize,
    pub panel_data: Option<SessionData>,
    panel_key: String,
    /// `last_active` of the session when its panel data was requested, so an
    /// append can be told apart from an unchanged session.
    panel_stamp: String,
    pub info_scroll: u16,
    pub cost_scroll: u16,
    pub config_scroll: u16,
    pub proc_scroll: u16,
    pub context_scroll: u16,
    pub subagent_scroll: u16,
    pub tool_scroll: u16,
    /// Pin the tool log to its newest entry. Tool Activity is an append-only
    /// feed, so following the tail is the useful default; scrolling up releases
    /// the pin, and scrolling back to the bottom restores it.
    pub tool_follow: bool,
    /// Last computed maximum scroll for the tool log, recorded during draw so
    /// the key handler knows where the bottom is.
    pub tool_max_scroll: u16,
    pub tool_tab: usize,
    pub tool_live_only: bool,
    /// Show each edit's diff inline beneath its row.
    pub tool_show_diff: bool,
    /// Invocation whose full argument is expanded, keyed by `detail_key`.
    pub tool_expanded: Option<String>,
    /// Which invocation owns each rendered line, so a click maps to an entry.
    pub tool_owners: Vec<Option<String>>,
    pub subagent_sort: (panels::SubagentSort, bool),

    pub cpu_history: HashMap<String, History>,
    pub mem_history: HashMap<String, History>,
    pub global_cpu: History,
    pub global_spend: History,

    pub quota: Quota,
    /// Version of a newer published release, when one exists.
    pub update_available: Option<String>,
    pub status: Option<(String, Instant)>,
    /// When cctop started, used by the tool-activity "live" filter.
    pub started_at: String,
    /// The same moment as an `Instant`, which is what the tab-bar blink is
    /// phased against — a wall clock can jump, and a blink that stutters when
    /// NTP steps the clock looks like a bug.
    started: Instant,

    /// Bell and desktop notifications, and who rang last.
    pub notify: crate::notify::Notifier,

    /// The last snapshot from each machine named with `--host`, keyed by the
    /// target as the user spelled it.
    ///
    /// Held apart from `sessions` rather than merged once, because `sessions`
    /// is replaced wholesale by every walk and would drop them; `merge_remotes`
    /// puts the current snapshots back after each replacement.
    pub remotes: HashMap<String, Vec<Session>>,
    /// Machines that failed their last poll, and why.
    ///
    /// Shown rather than logged. A host that has quietly dropped out is worse
    /// than one that was never added: the totals still look complete.
    pub remote_errors: HashMap<String, String>,

    /// Which live sessions are working the same ground, recomputed whenever
    /// rows move. The level also rides on each row so the table can sort by it;
    /// this holds the part only the footer and the Info panel need — who, and
    /// which files.
    pub collisions: crate::collide::Map,

    /// Workspace tabs beyond the dashboard, each holding one or more terminals.
    pub tabs: Vec<tabs::Tab>,
    /// Which tab is on screen: `0` is the dashboard, `1..=tabs.len()` index
    /// `tabs`. Zero-length `tabs` is the ordinary case: the bar still shows the
    /// dashboard and its new-tab button, so the feature is findable.
    pub tab: usize,
    /// When the tab bar was last reconciled against the tmux sessions on this
    /// machine. See [`App::sync_shared_tabs`].
    shared_at: Option<Instant>,
    /// The tab being dragged along the bar, indexed as the bar is: `1..=len`,
    /// and never `0` because the dashboard does not move.
    ///
    /// Set on the press and cleared on the release, which is also what makes the
    /// release the bar's rather than the agent's: a drag that started on the bar
    /// and ended over a pane must not be delivered as a click inside it.
    pub(super) drag_tab: Option<usize>,
    /// What each session's own hooks last said about it, keyed by session id.
    ///
    /// Only sessions whose agent has cctop's hooks installed appear here, so an
    /// absent entry is the ordinary case and means "fall back to the transcript"
    /// rather than "nothing is happening".
    pub hooked: HashMap<String, crate::hook::Reported>,
    /// The integration's state, as of the last time the panel was opened.
    ///
    /// Rebuilt on opening and after every action rather than every frame: it
    /// reads three files off disk and scans a directory, which is nothing to do
    /// once and wasteful to do sixty times a second behind a closed panel.
    pub hooks: Option<crate::hook::Report>,
    /// The socket the agents push their events to. `None` only where there is
    /// none to be had — a non-unix build — in which case every estimate carries
    /// on exactly as it did before hooks existed.
    pub listener: Option<crate::hook::Listener>,
    /// The command highlighted in the launcher.
    pub launch_cursor: usize,
    /// What the launcher is offering, as it was when it opened.
    ///
    /// A snapshot rather than a live look, for correctness before cost: the list
    /// includes agents that can finish while the modal is up, and a list that
    /// reshuffles under a cursor means Enter starts something other than the row
    /// highlighted. It also keeps a `tmux` subprocess out of the draw loop.
    pub launch_offer: Vec<tabs::Choice>,
    /// Where the launcher's pick will go.
    pub launch_into: LaunchInto,
    /// Directory cctop was started in. Fresh tabs start here, rather than in
    /// whichever historical session happens to be selected in the dashboard.
    pub launch_root: Option<std::path::PathBuf>,
    /// Directory a launched agent starts in, captured when the launcher opens.
    /// Splits retain their tab's directory; a handoff deliberately overrides
    /// this with the source session's project.
    pub launch_cwd: Option<std::path::PathBuf>,
    /// The install the tmux offer is currently showing, so the modal draws the
    /// command that will actually run rather than working it out again.
    pub tmux_install: Option<crate::tmux::Install>,
    /// The launch waiting on the tmux question, or on the install it started.
    pub tmux_deferred: Option<Deferred>,
    /// Whether the offer has been turned down. One "no" holds for the run:
    /// asking again on the next tab would make declining tmux cost more than
    /// accepting it, which is a way of not really offering a choice.
    ///
    /// Not persisted — a decision about this machine belongs in whether tmux is
    /// installed on it, and cctop already reads that directly.
    pub tmux_declined: bool,
    /// The pane running the install, while one is running.
    ///
    /// Watched for two endings: tmux appearing, which releases the deferred
    /// launch into a tmux-backed pane, and the pane going away without it,
    /// which means the install failed and the launch should stop waiting.
    pub tmux_installing: Option<u32>,
    /// A handoff brief waiting for the agent the launcher is about to start.
    ///
    /// Held across the launcher rather than typed at the moment `H` is pressed,
    /// because the agent that will receive it does not exist yet: `H` writes the
    /// brief and opens the launcher, and whichever agent is picked inherits it.
    pub pending_brief: Option<std::path::PathBuf>,
    /// A brief handed to an agent that is still starting up, as
    /// `(pid, line, not before)`.
    ///
    /// An agent cannot be typed at until its TUI is reading the keyboard, and
    /// there is no signal for that — a line sent into the first half-second of
    /// startup is swallowed by whatever the harness prints over it. So the line
    /// waits here and the loop delivers it once the agent has had time to draw.
    pub handoff_send: Option<(u32, String, Instant)>,
    /// The agent this cctop launched, as `(pid, label)`.
    ///
    /// Set only for `cctop <agent>`, and only while it is alive — the loop exits
    /// as soon as it is not. It is what `A` goes back to after F12, and the
    /// reason quitting asks first: the agent is on a pty this process owns and
    /// does not survive it.
    pub hosted: Option<(u32, String)>,

    prefs: UiPrefs,
    tx: Sender<Request>,
    pub needs_redraw: bool,
    pub should_quit: bool,
}

impl App {
    fn new(plan: Plan, tx: Sender<Request>) -> Self {
        Self::with_prefs(plan, tx, UiPrefs::load())
    }

    /// Build with explicit preferences.
    ///
    /// Tests use this with `UiPrefs::default()`; going through `new` would load
    /// whatever is on the developer's disk and make results machine-dependent.
    fn with_prefs(plan: Plan, tx: Sender<Request>, prefs: UiPrefs) -> Self {
        let age_filter = prefs
            .inactivity_filter
            .as_deref()
            .and_then(AgeFilter::parse);
        let age_cursor = AGE_OPTIONS
            .iter()
            .position(|o| *o == age_filter)
            .unwrap_or(AGE_OPTIONS.len() - 1);

        App {
            sessions: Vec::new(),
            loaded: false,
            visible: Vec::new(),
            finished_agents: std::collections::HashSet::new(),
            expanded: prefs
                .expanded
                .iter()
                .cloned()
                .collect::<std::collections::HashSet<_>>(),
            stats: Stats::default(),
            selected: 0,
            scroll: 0,
            plan,
            mode: Mode::List,
            // Newest first: `Last` compares reversed, so ascending is most
            // recently active at the top.
            sort_col: ColumnId::Last,
            sort_asc: true,
            sortby_cursor: 0,
            search: String::new(),
            search_content: false,
            scan_query: String::new(),
            scan_hits: HashMap::new(),
            scanning: false,
            scan_typed_at: None,
            search_history: prefs.search_history.clone(),
            history_cursor: None,
            age_filter,
            age_cursor,
            live_only: prefs.live_only,
            marked: HashSet::new(),
            deleting: HashSet::new(),
            batch: BatchKind::Delete,
            follow: false,
            refresh_secs: 2.0,
            cost_floor: prefs.cost_floor,
            // The one used last, or the default when that profile has since
            // gone: a name that no longer resolves must not silently launch
            // under somebody else's account.
            launch_profile: prefs
                .claude_profile
                .as_deref()
                .and_then(|name| {
                    crate::config::CLAUDE_PROFILES
                        .iter()
                        .position(|p| p.name == name)
                })
                .unwrap_or(0),
            menu_cursor: 0,
            cost_input: String::new(),
            send_input: String::new(),
            list_height: 0,
            hidden_columns: hidden_columns(&prefs),
            help_scroll: 0,
            help_max_scroll: 0,
            bottom_tab: prefs.bottom_tab.min(panels::TABS.len() - 1),
            panel_data: None,
            panel_key: String::new(),
            panel_stamp: String::new(),
            info_scroll: 0,
            cost_scroll: 0,
            config_scroll: 0,
            proc_scroll: 0,
            context_scroll: 0,
            subagent_scroll: 0,
            tool_scroll: 0,
            tool_follow: true,
            tool_max_scroll: 0,
            tool_tab: 0,
            tool_live_only: prefs.agent_live_filter,
            tool_show_diff: prefs.tool_show_diff,
            tool_expanded: None,
            tool_owners: Vec::new(),
            subagent_sort: (
                panels::SubagentSort::parse(&prefs.subagent_sort_col),
                prefs.subagent_sort_asc,
            ),
            cpu_history: HashMap::new(),
            mem_history: HashMap::new(),
            global_cpu: History::default(),
            global_spend: History::default(),
            quota: Quota::default(),
            notify: crate::notify::Notifier::new(prefs.notify),
            collisions: crate::collide::Map::new(),
            remotes: HashMap::new(),
            remote_errors: HashMap::new(),
            update_available: None,
            status: None,
            started_at: chrono::Utc::now().to_rfc3339(),
            started: Instant::now(),
            prefs,
            tx,
            tabs: Vec::new(),
            tab: 0,
            shared_at: None,
            drag_tab: None,
            hooked: HashMap::new(),
            hooks: None,
            listener: None,
            launch_cursor: 0,
            launch_offer: Vec::new(),
            launch_into: LaunchInto::Tab,
            launch_root: std::env::current_dir().ok(),
            launch_cwd: None,
            launch_cwd_input: String::new(),
            launch_cwd_bad: false,
            tmux_install: None,
            tmux_deferred: None,
            tmux_declined: false,
            tmux_installing: None,
            pending_brief: None,
            handoff_send: None,
            hosted: None,
            needs_redraw: true,
            should_quit: false,
        }
    }

    /// The highlighted session, if there is one.
    ///
    /// `visible` holds indices into `sessions`, and a refresh replaces
    /// `sessions` before `refilter` rebuilds `visible` — so between those two
    /// steps the indices can outrun the list. Resolving through `get` keeps this
    /// accessor total instead of panicking on that window.
    pub fn selected_session(&self) -> Option<&Session> {
        self.visible
            .get(self.selected)
            .and_then(|row| self.sessions.get(row.session()))
    }

    /// The footer's warning that two live agents have written the same file.
    ///
    /// Only the file-level overlaps. A shared repository is worth the cell in
    /// the `!` column and no more — agents share repositories all day and
    /// nothing has gone wrong yet, whereas two of them writing one file means
    /// one has already lost an edit or is about to.
    ///
    /// Unlike the bell's line this does not clear when you select the row: the
    /// bell reports a moment that has passed, and this reports a state that is
    /// still true whether or not you are looking at it.
    pub fn conflict_footer(&self) -> Option<String> {
        use std::collections::BTreeSet;
        let mut agents = 0;
        let mut files: BTreeSet<&str> = BTreeSet::new();
        for c in self.collisions.values() {
            if c.level != crate::collide::Overlap::File {
                continue;
            }
            agents += 1;
            files.extend(c.files.iter().map(String::as_str));
        }
        let first = files.iter().next()?;
        let more = match files.len() {
            1 => String::new(),
            n => format!(" +{} more", n - 1),
        };
        Some(format!(
            "Conflict: ⚠ {}{more} — {agents} agents have written it",
            crate::util::path_tail(first, 2)
        ))
    }

    /// Put the current remote snapshots back into the table.
    ///
    /// Every wholesale replacement of `sessions` — a full walk, a discovery —
    /// drops the remote rows, because the loader only ever knows about this
    /// machine. Rather than teaching the loader about ssh, the rows are
    /// re-appended here and the totals recomputed over both.
    ///
    /// A no-op with no hosts configured, so the ordinary single-machine run
    /// pays nothing for this.
    pub fn merge_remotes(&mut self) {
        if self.remotes.is_empty() {
            return;
        }
        self.sessions.retain(|s| s.remote.is_none());
        for rows in self.remotes.values() {
            self.sessions.extend(rows.iter().cloned());
        }
        self.stats = crate::loader::compute_stats(&self.sessions);
        self.refilter();
    }

    /// Take the worker's totals, unless remote rows mean they are not the whole
    /// picture. The worker only ever sees this machine.
    fn adopt_stats(&mut self, stats: Stats) {
        self.stats = match self.remotes.is_empty() {
            true => stats,
            false => crate::loader::compute_stats(&self.sessions),
        };
    }

    /// Whether an action that reaches into this machine can apply to a row.
    ///
    /// Returns the refusal to show, or `None` when the row is local. Every
    /// caller is a path that signals a process, deletes a file, or opens a pty,
    /// and each would otherwise do it to whatever sits at the same path here.
    pub fn remote_refusal(session: &Session) -> Option<String> {
        let r = session.remote.as_ref()?;
        Some(format!(
            "{} is on {} — cctop reads other machines but only acts on this one",
            session.display_label(),
            r.host
        ))
    }

    /// The footer's note that a machine is not answering.
    pub fn remote_footer(&self) -> Option<String> {
        let mut hosts: Vec<&str> = self.remote_errors.keys().map(String::as_str).collect();
        hosts.sort();
        let first = hosts.first()?;
        // One host names its reason, which is nearly always the whole fix
        // ("Permission denied", "command not found"). Several would not fit, so
        // they are counted and the panel is where the rest live.
        Some(match hosts.len() {
            1 => format!("{first}: {}", self.remote_errors[*first]),
            n => format!(
                "{n} hosts unreachable ({first}: {})",
                self.remote_errors[*first]
            ),
        })
    }

    /// What one session collides with, with its peers named the way the table
    /// names them.
    pub fn clash_of(&self, session: &Session) -> Option<panels::Clash> {
        let c = self.collisions.get(&session.key())?;
        let peers = c
            .peers
            .iter()
            .filter_map(|key| self.sessions.iter().find(|s| &s.key() == key))
            .map(|s| s.display_label().to_string())
            .collect();
        Some(panels::Clash {
            level: c.level,
            peers,
            files: c.files.clone(),
        })
    }

    /// The highlighted row, whatever kind it is.
    pub fn selected_row(&self) -> Option<Row> {
        self.visible.get(self.selected).copied()
    }

    /// The highlighted subagent, when the cursor is on a child row.
    pub fn selected_subagent(&self) -> Option<&crate::session::Subagent> {
        match self.selected_row()? {
            Row::Session(_) => None,
            Row::Subagent { parent, index } => self.sessions.get(parent)?.subagents.get(index),
        }
    }

    /// Whether the cursor is on a child row.
    ///
    /// The actions that ask this all address the operating system — a signal, a
    /// file, a terminal — and a subagent has none of its own. Refusing is
    /// clearer than silently acting on the parent, which is a live session the
    /// user did not point at.
    pub fn on_subagent(&self) -> bool {
        self.selected_row().is_some_and(Row::is_subagent)
    }

    /// Whether a session is showing its subagents.
    pub fn is_expanded(&self, session: &Session) -> bool {
        self.expanded.contains(&session.key())
    }

    /// Show or hide the selected session's subagents.
    ///
    /// Anchored on the owning session, so pressing it on a child collapses the
    /// parent that child came from rather than doing nothing — the row the
    /// cursor lands on afterwards is then the parent, not a line that no longer
    /// exists.
    pub(super) fn toggle_expanded(&mut self) {
        let Some(row) = self.selected_row() else {
            return;
        };
        let Some(session) = self.sessions.get(row.session()) else {
            return;
        };
        if session.subagents.is_empty() {
            self.set_status("No subagents to show");
            return;
        }
        let key = session.key();
        if !self.expanded.remove(&key) {
            self.expanded.insert(key);
        }
        if row.is_subagent() {
            self.selected = self.selected.saturating_sub(1);
        }
        self.refilter();
        self.save_prefs();
    }

    /// Expand every session that has subagents, or collapse them all.
    ///
    /// Collapses when anything at all is open: with a mixture on screen, "close
    /// them" is the intent that a single key can satisfy unambiguously.
    fn toggle_expanded_all(&mut self) {
        if self.expanded.is_empty() {
            self.expanded = self
                .sessions
                .iter()
                .filter(|s| !s.subagents.is_empty())
                .map(Session::key)
                .collect();
        } else {
            self.expanded.clear();
        }
        self.refilter();
        self.save_prefs();
    }

    fn save_prefs(&mut self) {
        self.prefs.bottom_tab = self.bottom_tab;
        self.prefs.live_only = self.live_only;
        self.prefs.inactivity_filter = self.age_filter.map(|a| a.key().to_string());
        self.prefs.agent_live_filter = self.tool_live_only;
        self.prefs.tool_show_diff = self.tool_show_diff;
        // Sorted so the file does not churn on every save purely because a
        // HashSet iterated in a different order.
        let mut expanded: Vec<String> = self.expanded.iter().cloned().collect();
        expanded.sort();
        self.prefs.expanded = expanded;
        self.prefs.subagent_sort_col = self.subagent_sort.0.key().to_string();
        self.prefs.subagent_sort_asc = self.subagent_sort.1;
        self.prefs.cost_floor = self.cost_floor;
        self.prefs.claude_profile = self.launch_profile().map(|p| p.name.clone());
        self.prefs.notify = self.notify.enabled;
        self.prefs.search_history = self.search_history.clone();
        self.prefs.save();
    }

    fn set_status(&mut self, msg: impl Into<String>) {
        self.status = Some((msg.into(), Instant::now()));
        self.needs_redraw = true;
    }

    /// Apply filters and sorting, then rebuild the visible index list.
    ///
    /// Selection is tracked by session key rather than row number, so a refresh
    /// that reorders the table doesn't move the cursor off whatever the user was
    /// looking at.
    pub fn refilter(&mut self) {
        let anchor = self.selected_row().map(|r| self.row_key(r));
        let now = chrono::Utc::now();
        let now_ms = now.timestamp_millis();
        let query = self.search.to_ascii_lowercase();

        let mut visible: Vec<usize> = (0..self.sessions.len())
            .filter(|&i| {
                let s = &self.sessions[i];
                if self.live_only && !s.is_running() {
                    return false;
                }
                if let Some(age) = self.age_filter {
                    let ts = if s.last_active.is_empty() {
                        &s.started_at
                    } else {
                        &s.last_active
                    };
                    let within = crate::util::parse_ts(ts)
                        .map(|d| now_ms - d.timestamp_millis() <= age.max_age_ms())
                        .unwrap_or(false);
                    if !within {
                        return false;
                    }
                }
                if !self.matches_query(s, &query) {
                    return false;
                }
                if self.cost_floor > 0.0 {
                    // Sessions with unknown cost are kept: the floor can't say
                    // they're below it. "Included" cost (None) counts as zero.
                    let cost = if s.cost_available {
                        s.total_cost.unwrap_or(0.0)
                    } else {
                        // Unknown — can't disqualify.
                        return true;
                    };
                    if cost < self.cost_floor {
                        return false;
                    }
                }
                true
            })
            .collect();

        let col = self.sort_col;
        let asc = self.sort_asc;
        visible.sort_by(|&a, &b| {
            let ord = columns::compare(col, &self.sessions[a], &self.sessions[b], &now);
            if asc { ord } else { ord.reverse() }
        });

        // Sessions are sorted first, then each expanded one has its children
        // spliced in beneath it: subagents belong to their parent's position in
        // the table, not to the ordering the sort column would give them.
        self.visible = visible
            .into_iter()
            .flat_map(|i| {
                let session = &self.sessions[i];
                let children = if self.expanded.contains(&session.key()) {
                    session.subagents.len()
                } else {
                    0
                };
                std::iter::once(Row::Session(i))
                    .chain((0..children).map(move |index| Row::Subagent { parent: i, index }))
            })
            .collect();
        self.selected = anchor
            .and_then(|key| self.visible.iter().position(|&r| self.row_key(r) == key))
            .unwrap_or(self.selected)
            .min(self.visible.len().saturating_sub(1));
        self.ensure_available_tab();
        self.needs_redraw = true;
    }

    /// Identity of a row across refreshes.
    ///
    /// A subagent's own id is unique only within its parent, and a session key
    /// alone cannot tell a parent from its children, so the cursor is anchored
    /// on the pair.
    fn row_key(&self, row: Row) -> String {
        let Some(session) = self.sessions.get(row.session()) else {
            return String::new();
        };
        match row {
            Row::Session(_) => session.key(),
            Row::Subagent { index, .. } => match session.subagents.get(index) {
                Some(sub) => format!("{}/{}", session.key(), sub.agent_id),
                None => session.key(),
            },
        }
    }

    /// Fold this refresh's figures into the overview history buffers.
    fn push_history(&mut self) {
        // This is a rate, not a refresh delta, so its meaning is stable when
        // the user changes --delay or a filesystem scan takes longer.
        self.global_spend.push(self.stats.spend_per_min);
        self.global_cpu.push(self.stats.total_cpu as f64);

        for s in &self.sessions {
            let Some(p) = &s.process else { continue };
            let key = s.key();
            self.cpu_history
                .entry(key.clone())
                .or_default()
                .push(p.cpu as f64);
            self.mem_history
                .entry(key)
                .or_default()
                .push(p.memory as f64 / (1024.0 * 1024.0));
        }
    }

    /// What the bottom panels should describe for a row.
    ///
    /// A subagent gets a stand-in `Session` pointed at its own transcript. That
    /// file is the same JSONL a session writes, so the whole extraction path —
    /// worker, cache, every panel — reads it without knowing the difference, and
    /// the panels describe the subagent rather than the parent it ran under.
    fn panel_subject(&self, row: Row) -> Option<Session> {
        let session = self.sessions.get(row.session())?;
        let Row::Subagent { index, .. } = row else {
            return Some(session.clone());
        };
        let sub = session.subagents.get(index)?;
        // A purged transcript leaves nothing to read; the parent's own data is
        // the only thing left that describes the run.
        if sub.ghost {
            return None;
        }

        let mut stand_in = Session::new(session.provider, sub.agent_id.clone());
        stand_in.surface = session.surface;
        stand_in.model = sub.model.clone();
        stand_in.label_source = session.label_source.clone();
        stand_in.harness = session.harness.clone();
        stand_in.title = Some(sub.description.clone()).filter(|d| !d.is_empty());
        stand_in.started_at = sub.started_at.clone().unwrap_or_default();
        stand_in.data_file = session
            .data_file
            .as_ref()
            .map(|f| f.with_extension("").join("subagents"))
            .map(|dir| dir.join(format!("{}.jsonl", sub.agent_id)));
        // Its own mtime, so the panels refresh while the subagent is working and
        // not merely when its parent writes something.
        stand_in.last_active = stand_in
            .data_file
            .as_ref()
            .map(|f| crate::util::ms_to_rfc3339(crate::config::file_mtime_ms(f) as i64))
            .unwrap_or_default();
        Some(stand_in)
    }

    /// Ask the worker for the selected row's full data if it isn't loaded.
    fn sync_panel_data(&mut self) {
        let Some(row) = self.selected_row() else {
            self.panel_data = None;
            self.panel_key.clear();
            return;
        };
        let Some(session) = self.panel_subject(row) else {
            self.panel_data = None;
            self.panel_key.clear();
            return;
        };
        // Nothing to extract for a row read over ssh: the transcript is a file
        // on the other machine and cctop never fetches it. Asking would hand the
        // worker a session with no `data_file` and get an empty result back that
        // the panels would draw as zeroes.
        if session.remote.is_some() {
            self.panel_data = None;
            self.panel_key = session.key();
            self.panel_stamp = session.last_active.clone();
            return;
        }
        let key = session.key();
        let stamp = session.last_active.clone();
        let switched = key != self.panel_key;
        // A live session keeps growing, so re-request whenever its newest
        // activity moves — otherwise the panels freeze at whatever the session
        // looked like when it was selected.
        let grew = !switched && stamp != self.panel_stamp;
        if !switched && !grew {
            return;
        }

        self.panel_key = key;
        self.panel_stamp = stamp;

        if switched {
            // Only blank the panels when moving to a different session; doing it
            // on every append would flash "Loading…" twice a second.
            self.panel_data = None;
            self.info_scroll = 0;
            self.cost_scroll = 0;
            self.config_scroll = 0;
            self.proc_scroll = 0;
            self.subagent_scroll = 0;
            self.tool_scroll = 0;
            self.tool_follow = true;
            self.tool_tab = 0;
            self.tool_expanded = None;
        }
        let _ = self.tx.send(Request::Data(Box::new(session)));
    }

    fn move_selection(&mut self, delta: isize) {
        if self.visible.is_empty() {
            return;
        }
        let last = self.visible.len() - 1;
        self.selected = (self.selected as isize + delta).clamp(0, last as isize) as usize;
        self.ensure_available_tab();
        self.needs_redraw = true;
    }

    fn tab_available(&self, tab: usize) -> bool {
        match tab {
            // Performance and Processes read a live process tree.
            1 | 2 => self.selected_session().is_some_and(Session::is_running),
            // Only Claude transcripts report the per-request usage the context
            // breakdown is reconstructed from. Gated on the provider rather than
            // on the extracted data, so the tab doesn't vanish while it loads.
            7 => self
                .selected_session()
                .is_some_and(|s| s.provider == Provider::Claude),
            _ => true,
        }
    }

    fn ensure_available_tab(&mut self) {
        if !self.tab_available(self.bottom_tab) {
            self.bottom_tab = 0;
        }
    }

    fn set_sort(&mut self, col: ColumnId) {
        if self.sort_col == col {
            self.sort_asc = !self.sort_asc;
        } else {
            self.sort_col = col;
            self.sort_asc = true;
        }
        self.refilter();
        self.save_prefs();
    }

    /// Expand or collapse the invocation under a clicked log row.
    fn toggle_tool_expansion(&mut self, row_offset: usize) {
        let line = self.tool_scroll as usize + row_offset;
        let Some(Some(key)) = self.tool_owners.get(line) else {
            return;
        };
        let key = key.clone();
        // Clicking the open entry again closes it.
        self.tool_expanded = (self.tool_expanded.as_deref() != Some(key.as_str())).then_some(key);
        // Expanding grows the log, which would otherwise slide the row away.
        self.tool_follow = false;
        self.needs_redraw = true;
    }

    /// Move through the Tool Activity sidebar, which filters the log by tool.
    fn cycle_tool_filter(&mut self, delta: isize) {
        let n = self
            .panel_data
            .as_ref()
            .map(|d| panels::tool_tabs(d).len())
            .unwrap_or(0);
        if n == 0 {
            return;
        }
        let n = n as isize;
        self.tool_tab = (((self.tool_tab as isize + delta) % n + n) % n) as usize;
        // A different filter is a different log, so start at its newest entry.
        self.tool_follow = true;
        self.bottom_tab = 3;
        self.needs_redraw = true;
    }

    /// Move to the next or previous bottom panel, wrapping at both ends.
    fn cycle_tab(&mut self, delta: isize) {
        let n = panels::TABS.len() as isize;
        let mut next = self.bottom_tab;
        for _ in 0..panels::TABS.len() {
            next = (((next as isize + delta) % n + n) % n) as usize;
            if self.tab_available(next) {
                self.bottom_tab = next;
                break;
            }
        }
        self.save_prefs();
        self.needs_redraw = true;
    }

    fn scroll_active_panel(&mut self, delta: i32) {
        let bump = |v: &mut u16| *v = (*v as i32 + delta).max(0) as u16;
        match self.bottom_tab {
            0 => bump(&mut self.info_scroll),
            1 => {} // Performance is a fixed-size chart pair
            2 => bump(&mut self.proc_scroll),
            3 => {
                let next = (self.tool_scroll as i32 + delta).clamp(0, self.tool_max_scroll as i32);
                self.tool_scroll = next as u16;
                // Re-pin once the user scrolls back down to the newest entry.
                self.tool_follow = self.tool_scroll >= self.tool_max_scroll;
            }
            4 => bump(&mut self.subagent_scroll),
            5 => bump(&mut self.cost_scroll),
            6 => bump(&mut self.config_scroll),
            _ => bump(&mut self.context_scroll),
        }
        self.needs_redraw = true;
    }

    /// Copy something useful about the selection to the clipboard.
    fn copy_selection(&mut self) {
        let Some(s) = self.selected_session() else {
            return;
        };
        let text = match self.bottom_tab {
            // From the Info tab, the resume command is the most useful thing —
            // and for the providers that have none, the transcript's path is.
            0 => match s.resume_argv() {
                Some(argv) => argv.join(" "),
                None => s
                    .data_file
                    .as_ref()
                    .map(|p| p.display().to_string())
                    .unwrap_or_else(|| s.session_id.clone()),
            },
            _ => s
                .data_file
                .as_ref()
                .map(|p| p.display().to_string())
                .unwrap_or_else(|| s.session_id.clone()),
        };
        render::copy_to_clipboard(&text);
        self.set_status(format!("Copied: {}", crate::util::truncate(&text, 60)));
    }

    /// Whether the session matches the active text search.
    ///
    /// `refilter` calls [`matches_query`] directly with a query it lowercases
    /// once; this is the same predicate for callers that only have one session
    /// in hand, so the live filter and the `n`/`N` jump cannot drift apart.
    fn matches_search(&self, s: &Session) -> bool {
        self.matches_query(s, &self.search.to_ascii_lowercase())
    }

    /// Whether a session matches `query`, which must already be lowercase.
    ///
    /// Content search widens the filter rather than replacing it: a query that
    /// names a project still finds that project's sessions, and the transcripts
    /// add whatever else mentions it. Hits only count while they belong to the
    /// query being typed — until the scan for a longer query lands, its rows are
    /// the metadata matches alone, which is a filter narrowing as you type
    /// rather than showing results for a query you have moved on from.
    fn matches_query(&self, s: &Session, query: &str) -> bool {
        if query.is_empty() {
            return true;
        }
        // Field by field rather than one joined string. This runs per session
        // per refresh, and lowercasing them all was the whole per-refresh
        // allocation; it also stops a query matching across the seam between
        // two unrelated fields.
        let fields: [&str; 8] = [
            s.display_label(),
            &s.model,
            &s.harness,
            s.provider.as_str(),
            &s.session_id,
            &s.label_source,
            // Empty for this user's own rows, which no query can match, so
            // searching a name finds that person's sessions and nothing else.
            s.owner.as_deref().unwrap_or_default(),
            // Likewise empty for every harness but Claude Code, so `work` finds
            // that login's sessions rather than everything that mentions work.
            s.profile.as_deref().unwrap_or_default(),
        ];
        if fields.iter().any(|f| contains_ascii_ci(f, query)) {
            return true;
        }
        // The branch is derived rather than stored, so it is the one field that
        // cannot be borrowed straight off the session.
        if columns::branch_of(s).is_some_and(|b| contains_ascii_ci(&b, query)) {
            return true;
        }
        self.search_content && self.scan_query == query && self.scan_hits.contains_key(&s.key())
    }

    /// The transcript text around the selected session's content match.
    pub fn selected_snippet(&self) -> Option<&str> {
        let s = self.selected_session()?;
        (self.search_content && self.scan_query == self.search.to_ascii_lowercase())
            .then(|| self.scan_hits.get(&s.key()))
            .flatten()
            .map(String::as_str)
    }

    /// Note that the query changed, so the scan can be rescheduled.
    ///
    /// Every edit lands here, including the ones that only shorten the query:
    /// hits for a longer query are not hits for a shorter one, and leaving them
    /// applied would leave rows on screen that no longer match anything.
    pub(super) fn search_edited(&mut self) {
        self.history_cursor = None;
        self.scan_typed_at = Some(Instant::now());
        self.refilter();
    }

    /// Turn transcript searching on or off.
    pub(super) fn toggle_content_search(&mut self) {
        self.search_content = !self.search_content;
        if !self.search_content {
            // Results for a search nobody is running any more; keeping them
            // would make the next toggle show stale rows for an instant.
            self.scan_hits.clear();
            self.scan_query.clear();
        }
        self.scan_typed_at = Some(Instant::now());
        self.refilter();
    }

    /// Send the current query off to be scanned, once the typing has settled.
    ///
    /// Called every loop iteration rather than on each keystroke: a scan reads
    /// every transcript on disk, and firing one per character would spend the
    /// whole budget on prefixes of the word being typed.
    pub(super) fn tick_scan(&mut self) {
        if !self.search_content || self.scanning {
            return;
        }
        let query = self.search.to_ascii_lowercase();
        if query == self.scan_query {
            self.scan_typed_at = None;
            return;
        }
        // A one- or two-character query matches nearly every transcript, so it
        // is the most expensive scan to run and the least useful to read.
        // Deleting back to that length drops the results with it, rather than
        // leaving a count on screen for a query no longer being asked.
        if query.chars().count() < MIN_SCAN_CHARS {
            if !self.scan_query.is_empty() {
                self.scan_query.clear();
                self.scan_hits.clear();
                self.refilter();
                self.needs_redraw = true;
            }
            return;
        }
        match self.scan_typed_at {
            Some(at) if at.elapsed() < SCAN_DEBOUNCE => return,
            _ => {}
        }
        self.scan_typed_at = None;
        let targets: Vec<crate::session::search::Target> = self
            .sessions
            .iter()
            .map(crate::session::search::Target::of)
            .collect();
        if self.tx.send(Request::Scan { query, targets }).is_ok() {
            self.scanning = true;
            self.needs_redraw = true;
        }
    }

    /// Fold in a finished scan.
    fn scanned(&mut self, query: String, hits: HashMap<String, String>) {
        self.scanning = false;
        self.scan_query = query;
        self.scan_hits = hits;
        self.refilter();
        self.needs_redraw = true;
    }

    /// Record the query that was just run, so ↑ can bring it back.
    pub(super) fn remember_query(&mut self) {
        let query = self.search.trim().to_string();
        if query.is_empty() {
            return;
        }
        // Re-running a query moves it to the front rather than adding a second
        // copy, which is what makes a short history worth walking.
        self.search_history.retain(|q| q != &query);
        self.search_history.insert(0, query);
        self.search_history
            .truncate(crate::cache::MAX_SEARCH_HISTORY);
        self.save_prefs();
    }

    /// Walk the query history: `1` towards older entries, `-1` back towards
    /// what was being typed when the walk started.
    pub(super) fn history_step(&mut self, delta: isize) {
        if self.search_history.is_empty() {
            return;
        }
        let (at, typed) = match self.history_cursor.take() {
            Some((at, typed)) => (at as isize + delta, typed),
            // Nothing walked yet: ↓ has nowhere older to come back from.
            None if delta < 0 => return,
            None => (0, self.search.clone()),
        };
        // Stepping back past the newest entry restores the partial query, which
        // is the one thing the history itself cannot hold.
        if at < 0 {
            self.search = typed;
        } else {
            let at = (at as usize).min(self.search_history.len() - 1);
            self.search = self.search_history[at].clone();
            self.history_cursor = Some((at, typed));
        }
        self.scan_typed_at = Some(Instant::now());
        self.refilter();
        self.needs_redraw = true;
    }

    /// Whether the cursor is on a row read from another machine.
    pub fn selected_is_remote(&self) -> bool {
        self.selected_session().is_some_and(|s| s.remote.is_some())
    }

    /// Open the terminate confirmation for the selected session, explaining
    /// itself when there is nothing this cctop can signal.
    fn confirm_terminate(&mut self) {
        // Kept here rather than at the key, because this is now the only way in:
        // `k` moves the cursor, and Ctrl+K is what asks. A subagent has no
        // process of its own to signal — stopping it means stopping its parent,
        // which is not what the cursor is pointing at.
        if self.on_subagent() {
            self.set_status("A subagent cannot be stopped on its own");
            return;
        }
        if let Some(why) = self.selected_session().and_then(App::remote_refusal) {
            self.set_status(why);
            return;
        }
        match self.selected_session() {
            Some(s) if session_root_pid(s).is_some() => self.mode = Mode::KillConfirm,
            Some(s) if s.is_running() => self.mode = Mode::KillBlocked,
            Some(_) => self.set_status("Selected session is not running"),
            None => {}
        }
    }

    /// Peel off one filter layer, narrowest first, and say which one went.
    ///
    /// One press per layer rather than all at once: filters are combined
    /// deliberately, and clearing four of them on a stray Esc would lose work
    /// that took four deliberate keystrokes to set up. Every layer that paints
    /// a badge in the footer is reachable from here, so nothing can stay on
    /// with no way to turn it off.
    fn clear_one_filter(&mut self) {
        let cleared = if !self.search.is_empty() {
            self.search.clear();
            "Search cleared"
        } else if self.cost_floor > 0.0 {
            self.cost_floor = 0.0;
            "Cost floor cleared"
        } else if self.live_only {
            self.live_only = false;
            "Showing stopped sessions too"
        } else if self.age_filter.is_some() {
            self.age_filter = None;
            "Age filter cleared"
        } else if self.tool_tab != 0 || self.tool_live_only {
            // The Tool Activity sidebar filters a panel rather than the table,
            // so it comes last: it is the layer the user is least likely to
            // have forgotten about.
            self.tool_tab = 0;
            self.tool_live_only = false;
            self.tool_follow = true;
            "Tool Activity filter cleared"
        } else {
            return;
        };
        self.refilter();
        self.save_prefs();
        self.set_status(cleared);
    }

    /// Jump to the next/previous session matching the active search, wrapping
    /// around both ends. With no search active every visible session matches.
    fn cycle_matches(&mut self, delta: isize) {
        if self.visible.is_empty() {
            return;
        }
        // Positions rather than rows: a child row matches on its parent's text,
        // so several rows can share one session and `position` would keep
        // sending the cursor back to the first of them.
        let matches: Vec<usize> = self
            .visible
            .iter()
            .enumerate()
            .filter(|(_, row)| self.matches_search(&self.sessions[row.session()]))
            .map(|(at, _)| at)
            .collect();
        if matches.is_empty() {
            return;
        }
        let pos = matches.iter().position(|&at| at == self.selected);
        let n = matches.len() as isize;
        let next = ((pos.unwrap_or(0) as isize + delta).rem_euclid(n)) as usize;
        self.selected = matches[next];
        self.ensure_available_tab();
        self.needs_redraw = true;
    }

    /// Toggle whether the selected session is marked for a batch action.
    pub(super) fn toggle_mark(&mut self) {
        let Some(s) = self.selected_session() else {
            return;
        };
        let key = s.key();
        if !self.marked.remove(&key) {
            self.marked.insert(key);
        }
        self.needs_redraw = true;
    }

    /// The session keys currently marked, in table order for a stable listing.
    fn marked_sessions(&self) -> Vec<&Session> {
        self.visible
            .iter()
            .filter_map(|row| match row {
                // Child rows would list their parent a second time.
                Row::Session(i) => self.sessions.get(*i),
                Row::Subagent { .. } => None,
            })
            .filter(|s| self.marked.contains(&s.key()))
            .collect()
    }

    /// True when every marked session is ready for the given batch action.
    fn batch_ok(&self, kind: BatchKind) -> bool {
        self.marked_sessions().iter().all(|s| match kind {
            BatchKind::Delete => !s.is_running(),
            BatchKind::Kill => session_root_pid(s).is_some(),
        })
    }

    fn unmark_all(&mut self) {
        if self.marked.is_empty() {
            return;
        }
        self.marked.clear();
        self.needs_redraw = true;
    }

    /// Enter the batch-confirm modal if there's anything to do.
    fn batch(&mut self, kind: BatchKind) {
        if self.marked_sessions().is_empty() {
            self.set_status("No sessions marked — press Space to mark");
            return;
        }
        self.batch = kind;
        self.mode = if self.batch_ok(kind) {
            Mode::BatchConfirm
        } else {
            match kind {
                BatchKind::Delete => Mode::BatchDeleteBlocked,
                BatchKind::Kill => Mode::BatchKillBlocked,
            }
        };
        self.needs_redraw = true;
    }

    /// Confirm and run the pending batch action over all marked sessions.
    fn batch_execute(&mut self) {
        let kind = self.batch;
        let marked: Vec<Session> = self.marked_sessions().into_iter().cloned().collect();
        let mut requested = 0;
        let mut acted_on: Vec<String> = Vec::new();
        let mut failed = 0;
        for s in &marked {
            let key = s.key();
            // Marking spans machines because the table does; acting does not.
            if s.remote.is_some() {
                failed += 1;
                continue;
            }
            match kind {
                BatchKind::Delete => {
                    if self.tx.send(Request::Delete(Box::new(s.clone()))).is_ok() {
                        self.deleting.insert(key.clone());
                        requested += 1;
                        acted_on.push(key);
                    } else {
                        failed += 1;
                    }
                }
                BatchKind::Kill => match session_root_pid(s) {
                    Some(pid) => {
                        self.tx
                            .send(Request::Terminate {
                                session_key: key.clone(),
                                pid,
                            })
                            .ok();
                        acted_on.push(key);
                    }
                    None => failed += 1,
                },
            }
        }
        for key in &acted_on {
            self.marked.remove(key);
        }
        self.set_status(match kind {
            BatchKind::Delete => {
                if failed == 0 {
                    format!("Deleting {requested} session(s)…")
                } else {
                    format!("Deleting {requested} session(s), {failed} failed to start")
                }
            }
            BatchKind::Kill => format!(
                "Kill sent to {} session(s){}",
                acted_on.len(),
                if failed > 0 {
                    format!(" ({} skipped)", failed)
                } else {
                    String::new()
                }
            ),
        });
    }

    /// Let the notifier see this refresh, and ring if anything crossed.
    ///
    /// Called from the event loop only when the rows actually moved. It has to
    /// run on this thread: the bell and the OSC 9 sequence go straight to
    /// stdout, which ratatui owns, and only here is it certain that no frame is
    /// halfway through being flushed.
    fn check_bells(&mut self) {
        self.notify.observe(&self.sessions);
    }

    /// Turn the bell on or off, and remember which.
    fn toggle_notifications(&mut self) {
        self.notify.enabled = !self.notify.enabled;
        self.save_prefs();
        self.set_status(if self.notify.enabled {
            "Notifications on — bell and desktop alert when a session needs you"
        } else {
            "Notifications off"
        });
    }

    /// Jump the selection to whichever session rang last.
    fn jump_to_bell(&mut self) {
        let Some(key) = self.notify.last.as_ref().map(|r| r.key.clone()) else {
            self.set_status("Nothing has rung yet");
            return;
        };
        // The parent row, not a child of it: the bell rang for the session.
        match self
            .visible
            .iter()
            .position(|&r| !r.is_subagent() && self.sessions[r.session()].key() == key)
        {
            Some(row) => {
                self.selected = row;
                self.ensure_available_tab();
                self.needs_redraw = true;
            }
            // Answering it is the point, so say why it can't be reached rather
            // than moving the cursor somewhere arbitrary.
            None => self.set_status("The session that rang is hidden by the current filter"),
        }
    }

    /// Adjust the live refresh interval, clamping to sane bounds.
    fn adjust_refresh(&mut self, delta: f64) {
        self.refresh_secs = (self.refresh_secs + delta).clamp(0.5, 60.0);
        self.needs_redraw = true;
    }

    /// Half the visible table height, used by Ctrl+U/Ctrl+D. Falls back to a
    /// page size before the first draw has recorded a viewport.
    fn half_page(&self) -> usize {
        ((self.list_height as usize / 2).max(1)).min(PAGE as usize)
    }
}

/// Rows moved by PageUp/PageDown and the fallback for half-page scrolls.
const PAGE: isize = 10;

/// Half-period of the tab-bar blink. Slow enough to read the title through,
/// fast enough to catch the eye.
const BLINK_MS: u128 = 600;

/// How often the tab bar is reconciled against the tmux sessions on this
/// machine, so a tab opened in one cctop shows up in the others.
///
/// It costs a `tmux list-panes`, so it cannot ride the draw loop. Two seconds is
/// short enough that a tab opened next door is there before you have switched
/// windows to look for it, and long enough that the subprocess is nothing.
const SHARE_EVERY: Duration = Duration::from_secs(2);

// ---------------------------------------------------------------------------
// Workspace tabs
// ---------------------------------------------------------------------------

impl App {
    /// The tab on screen, or `None` on the dashboard.
    pub fn active_tab(&mut self) -> Option<&mut tabs::Tab> {
        self.tabs.get_mut(self.tab.checked_sub(1)?)
    }

    /// The pane the keyboard belongs to, or `None` on the dashboard.
    pub fn focused_pane(&mut self) -> Option<&mut tabs::Pane> {
        self.active_tab()?.focused_mut()
    }

    /// What tab `index` wants, if anything. `0` is the dashboard, which never
    /// asks for itself.
    ///
    /// The tab you are already looking at is excluded — its own focused pane is
    /// in front of you, so blinking its title tells you nothing you cannot see.
    pub fn tab_attention(&self, index: usize) -> Option<tabs::Attention> {
        let tab = self.tabs.get(index.checked_sub(1)?)?;
        tab.attention(index == self.tab, &|pid| self.pane_signal(pid))
    }

    /// Fold in whatever the agents have reported.
    ///
    /// These outrank anything read off disk or off a screen: an agent saying
    /// "my turn is over" is the fact those are both estimating.
    ///
    /// Returns whether anything arrived, and whether the set of sessions itself
    /// changed — one that has just started or just ended is a row to go and
    /// find or forget now, rather than at the next poll.
    fn apply_hooks(&mut self, events: Vec<crate::hook::Event>) -> (bool, bool) {
        let changed = !events.is_empty();
        let mut lifecycle = false;
        for event in events {
            lifecycle |= event.reported.signal.is_lifecycle();
            if let Some(agent) = event.finished_agent {
                self.finished_agents.insert(agent);
            }
            match event.reported.signal {
                // Nothing more will be said about it, and leaving the last
                // signal behind would have the row claim a state forever.
                crate::hook::Signal::Ended => {
                    self.hooked.remove(&event.session_id);
                }
                _ => {
                    self.hooked.insert(event.session_id, event.reported);
                }
            }
        }
        self.apply_finished_agents();
        self.apply_permissions();
        (changed, lifecycle)
    }

    /// Stamp each session with the permission mode its own hooks reported.
    ///
    /// Also run after a walk, because the rows are rebuilt wholesale and a
    /// freshly discovered one has to pick up what was reported before it
    /// existed. `hooked` outlives the rows for exactly this reason.
    fn apply_permissions(&mut self) {
        if self.hooked.is_empty() {
            return;
        }
        for session in &mut self.sessions {
            if let Some(reported) = self.hooked.get(&session.session_id) {
                // Only ever set from a report. A session whose newest event did
                // not carry the field keeps the last mode that did, because the
                // setting has not changed just because one event was quiet
                // about it.
                if reported.permission.is_some() {
                    session.permission = reported.permission;
                }
            }
        }
    }

    /// Mark the subagents whose own hook has reported them finished.
    ///
    /// Stamped onto the rows rather than consulted at each draw, so every reader
    /// of a `Subagent` — the child rows, the Subagents tab, `--json` — agrees
    /// without being handed the UI's state. The hook outranks the transcript
    /// heuristic: it is the agent saying so, where the heuristic is only the
    /// absence of writing.
    fn apply_finished_agents(&mut self) {
        if self.finished_agents.is_empty() {
            return;
        }
        for session in &mut self.sessions {
            for sub in &mut session.subagents {
                // The hook names the bare id; the transcript is `agent-<id>`.
                let id = sub.agent_id.strip_prefix("agent-").unwrap_or(&sub.agent_id);
                if self.finished_agents.contains(id) {
                    sub.status = crate::session::SubagentStatus::Done;
                }
            }
        }
    }

    /// Open the integration panel, reading the current state off disk.
    pub fn open_hooks(&mut self) {
        self.hooks = Some(self.hook_status());
        self.mode = Mode::Hooks;
        self.needs_redraw = true;
    }

    /// The integration's state, scoped to whichever project the cursor is on.
    fn hook_status(&self) -> crate::hook::Report {
        crate::hook::status(self.hook_project().as_deref(), self.listener.as_ref())
    }

    /// The project a `project`-scoped install would write into: the directory
    /// of the selected session, when it has one on this machine.
    pub fn hook_project(&self) -> Option<std::path::PathBuf> {
        self.selected_session()
            .map(|s| std::path::PathBuf::from(&s.label_source))
            .filter(|dir| dir.is_dir())
    }

    /// Install or remove from the panel, and show what happened.
    ///
    /// Every harness at once. The status line gets a count rather than five
    /// paths — the panel underneath is redrawn from disk immediately below, and
    /// that is where the detail belongs.
    pub fn set_hooks(&mut self, scope: crate::hook::Scope, install: bool) {
        let done = match install {
            true => crate::hook::install(&scope),
            false => crate::hook::remove(&scope),
        };
        self.set_status(format!(
            "{} {} agents ({})",
            match install {
                true => "Asked",
                false => "Stopped",
            },
            done.len(),
            scope.label()
        ));
        self.hooks = Some(self.hook_status());
    }

    /// What the agents have actually said, newest state per session, as
    /// `(project, state)` pairs for the panel.
    ///
    /// The project rather than the session id: an id names nothing to a reader,
    /// and this list is the answer to "is the thing I just installed working",
    /// which needs a name you recognise.
    pub fn reporting(&self) -> Vec<(String, &'static str)> {
        let mut rows: Vec<(String, &'static str)> = self
            .hooked
            .values()
            .map(|r| {
                let name = std::path::Path::new(&r.cwd)
                    .file_name()
                    .map(|n| n.to_string_lossy().into_owned())
                    .unwrap_or_else(|| "—".into());
                (name, r.signal.label())
            })
            .collect();
        rows.sort();
        rows
    }

    /// What a session's own hooks last said about it, if it has any.
    fn hooked_signal(&self, session_id: &str) -> Option<crate::hook::Signal> {
        if let Some(reported) = self.hooked.get(session_id) {
            return Some(reported.signal);
        }
        // Gemini CLI reports a full session id, but names the chat file it
        // writes — which is the only identity cctop's rows have, because
        // resuming reuses the id across disjoint files — after the *first eight
        // characters* of it. Without this last step every Gemini event lands on
        // no row at all.
        let tail = gemini_id_tail(session_id)?;
        self.hooked
            .iter()
            .find(|(id, _)| id.starts_with(tail))
            .map(|(_, reported)| reported.signal)
    }

    /// What has been reported about the agent running as `pid`, if anything.
    ///
    /// Hooks first, because the agent said it outright; the transcript second,
    /// which can only report the question and not the finished turn; nothing at
    /// all if the session has not been discovered yet, which leaves the caller
    /// to fall back to the pane's screen.
    ///
    /// Scans the table rather than keeping an index: there are a handful of
    /// panes and this runs once per frame, so a map would be state to keep
    /// correct in exchange for nothing measurable.
    fn pane_signal(&self, pid: u32) -> Option<crate::hook::Signal> {
        self.sessions
            .iter()
            .filter(|session| session_root_pid(session) == Some(pid))
            .find_map(|session| {
                self.hooked_signal(&session.session_id).or({
                    match session.activity_state {
                        crate::session::ActivityState::WaitingForInput => {
                            Some(crate::hook::Signal::NeedsInput)
                        }
                        _ => None,
                    }
                })
            })
    }

    /// Note that you have just typed into the terminal of the agent running as
    /// `pid`, so it is no longer waiting on you.
    ///
    /// The hooks cannot report this themselves. A permission prompt's answer
    /// produces no event of its own — the next thing Claude Code says is
    /// `PostToolUse`, once the tool it just unblocked has *finished*, which for
    /// a long command is a minute of a tab blinking at you about a question you
    /// already answered.
    ///
    /// Only an existing report is overwritten. Inserting one for an agent
    /// without hooks would shadow the transcript, which is that agent's only
    /// source of state and the thing that would otherwise correct this.
    ///
    /// A tool call in flight is overwritten too, even though it is a working
    /// state: [`Signal::Acting`](crate::hook::Signal::Acting) plus a still
    /// screen is how a held permission prompt is recognised, and the keystroke
    /// that answered it is the only sign the prompt is gone.
    fn mark_answered(&mut self, pid: u32) {
        let answered: Vec<String> = self
            .sessions
            .iter()
            .filter(|session| session_root_pid(session) == Some(pid))
            .map(|session| session.session_id.clone())
            .collect();
        for id in answered {
            if let Some(reported) = self.hooked.get_mut(&id)
                && reported.signal.awaits_you()
            {
                reported.signal = crate::hook::Signal::Busy;
            }
        }
    }

    /// Whether any hidden tab is explicitly waiting for input and should blink.
    pub fn any_attention(&self) -> bool {
        (1..=self.tabs.len()).any(|i| self.tab_attention(i) == Some(tabs::Attention::NeedsInput))
    }

    /// Which half of the blink cycle we are in.
    pub fn blink_on(&self) -> bool {
        (self.started.elapsed().as_millis() / BLINK_MS).is_multiple_of(2)
    }

    /// Show `tab`, clamped to what exists.
    pub fn show_tab(&mut self, tab: usize) {
        self.go_to_tab(tab.min(self.tabs.len()));
    }

    /// Move `delta` tabs along, wrapping through the dashboard.
    /// Move the tab at `from` to `to`, both indexed the way the bar is: `0` is
    /// the dashboard, which neither moves nor is displaced.
    ///
    /// The view follows the tab it was on rather than the position it was at —
    /// dragging a tab must not move you to a different agent, and neither must
    /// dragging one past the tab you are watching.
    pub fn move_tab(&mut self, from: usize, to: usize) {
        let (Some(a), Some(b)) = (from.checked_sub(1), to.checked_sub(1)) else {
            return;
        };
        if a == b || a >= self.tabs.len() || b >= self.tabs.len() {
            return;
        }
        let moved = self.tabs.remove(a);
        self.tabs.insert(b, moved);
        self.tab = match self.tab {
            here if here == from => to,
            // Everything the tab was lifted out of shifts one place towards the
            // gap it left.
            here if a < b && here > from && here <= to => here - 1,
            here if b < a && here >= to && here < from => here + 1,
            here => here,
        };
        self.needs_redraw = true;
    }

    /// Move the tab on screen one place along the bar, for the keyboard.
    ///
    /// Clamped rather than wrapped, unlike [`App::cycle_workspace`]: wrapping is
    /// natural when you are stepping *through* tabs and disorienting when you
    /// are rearranging them, where a tab at the end jumping to the front reads
    /// as having lost it.
    pub fn move_workspace(&mut self, delta: isize) {
        let Some(from) = (self.tab > 0).then_some(self.tab) else {
            return;
        };
        let to = (from as isize + delta).clamp(1, self.tabs.len() as isize) as usize;
        self.move_tab(from, to);
    }

    pub fn cycle_workspace(&mut self, delta: isize) {
        let count = self.tabs.len() as isize + 1;
        self.go_to_tab((self.tab as isize + delta).rem_euclid(count) as usize);
    }

    /// Move to `want`, taking the tmux client with you.
    ///
    /// This is what makes one set of tabs work across several cctops. Every tab
    /// in the bar is a tmux session any of them can attach to, but only the one
    /// you are looking at is worth holding a client on — several clients on one
    /// window and tmux has to pick a size that suits none of them. So the client
    /// follows the view: the tab arrived at takes one, the tab left behind gives
    /// its up, and the agent in between never notices either.
    ///
    /// The order matters. Attaching first means a session that has ended since
    /// the last sync leaves you where you were, reading why, rather than on a
    /// blank tab with the one you could see now detached as well.
    pub fn go_to_tab(&mut self, want: usize) {
        self.needs_redraw = true;
        if want == self.tab {
            return;
        }
        if let Some(tab) = want.checked_sub(1).and_then(|i| self.tabs.get_mut(i))
            && tab.detached()
        {
            let title = tab.title();
            if let Err(error) = tab.attach() {
                self.set_status(format!("Could not open {title}: {error}"));
                return;
            }
        }
        if let Some(tab) = self.tab.checked_sub(1).and_then(|i| self.tabs.get_mut(i)) {
            tab.detach();
        }
        self.tab = want;
    }

    /// Open the launcher, remembering where the pick should go and which
    /// directory it should start in.
    pub fn launch_prompt(&mut self, into: LaunchInto) {
        if matches!(into, LaunchInto::Split { .. }) && self.active_tab().is_none() {
            self.set_status("Nothing to split — open a tab first");
            return;
        }
        let offer = tabs::choices(&self.open_tmux());
        if offer.is_empty() {
            self.set_status("No agent found in PATH, and $SHELL is not set");
            return;
        }
        self.launch_offer = offer;
        self.launch_into = into;
        self.launch_cursor = 0;
        // A split lands next to an agent already working somewhere; a fresh tab
        // starts where cctop itself was invoked. The selected dashboard row is
        // for inspecting or resuming that session, not an implicit cwd switch.
        self.launch_cwd = match into {
            LaunchInto::Split { .. } => self.launch_cwd.clone(),
            LaunchInto::Tab => self.launch_root.clone(),
        };
        self.mode = Mode::Launch;
    }

    /// Write the selected session's context brief and offer it to a new agent.
    ///
    /// This is the cross-harness counterpart to `R`. Resuming puts the *same*
    /// harness back on the *same* transcript; a handoff carries what the session
    /// was doing across to a different agent entirely, which is the one thing no
    /// harness can do for itself — each one can only read its own transcripts.
    ///
    /// The brief is written before the launcher opens so a failure to write it
    /// is reported instead of starting an agent that then has nothing to read.
    pub(super) fn handoff_selected(&mut self) {
        let Some(session) = self.selected_session().cloned() else {
            return;
        };
        // The panels already hold the selected session's extraction; a brief
        // built while the row is still loading, or while a subagent row owns the
        // panels, falls back to the header alone rather than to another
        // session's data.
        let data = match self.panel_key == session.key() {
            true => self.panel_data.as_ref(),
            false => None,
        };
        let brief = crate::handoff::build(&session, data);
        let path = match crate::handoff::write(&brief) {
            Ok(path) => path,
            Err(error) => {
                self.set_status(format!("Could not write the handoff brief: {error}"));
                return;
            }
        };
        self.pending_brief = Some(path);
        // The receiving agent belongs in the directory the work is in, whatever
        // row the cursor moves to while the launcher is up.
        self.launch_prompt(LaunchInto::Tab);
        // `launch_prompt` bails on its own when nothing can be launched, and
        // leaving a brief pending for a launcher that never opened would attach
        // it to the next unrelated agent instead.
        if self.mode != Mode::Launch {
            self.pending_brief = None;
            return;
        }
        self.set_status(format!(
            "Handing off {} — pick who takes it",
            brief.summary()
        ));
    }

    /// Deliver a brief to the agent it was launched for, once that agent has had
    /// long enough to start reading its keyboard.
    pub(super) fn tick_handoff(&mut self) {
        let Some((pid, line, due)) = self.handoff_send.clone() else {
            return;
        };
        if Instant::now() < due {
            return;
        }
        self.handoff_send = None;
        match crate::inject::send_line(pid, &line) {
            Ok(()) => self.set_status("Handed the brief over"),
            // The brief is on disk either way, so the failure is recoverable by
            // hand — say where it is rather than only that this did not work.
            Err(error) => self.set_status(format!("Could not hand the brief over: {error}")),
        }
    }

    /// Reopen the selected session in a tab of its own.
    ///
    /// This is the one way into a session cctop did not start. `a` shows an
    /// agent's live terminal, but only for the agents cctop hosts — there is no
    /// pty to borrow otherwise. Resuming instead starts a *new* agent and hands
    /// it the transcript, which is what the harnesses themselves offer and works
    /// whether the session ended an hour ago or is running in another window.
    pub(super) fn resume_selected(&mut self) {
        let Some(session) = self.selected_session() else {
            return;
        };
        let Some(argv) = session.resume_argv() else {
            self.set_status(format!(
                "{} sessions cannot be resumed from a shell",
                session.provider.as_str()
            ));
            return;
        };
        if !crate::shim::is_command(&argv[0]) {
            self.set_status(format!("{} is not installed on this machine", argv[0]));
            return;
        }
        // Two agents appending to one transcript is not something any of the
        // harnesses coordinate, so the running case asks first.
        if session.is_running() {
            self.mode = Mode::ResumeConfirm;
            return;
        }
        self.resume_now();
    }

    /// Resume the selected session, having decided that it should be.
    pub(super) fn resume_now(&mut self) {
        let Some(session) = self.selected_session() else {
            return;
        };
        let Some(argv) = session.resume_argv() else {
            return;
        };
        // The transcript is full of paths relative to where the agent ran, so a
        // resumed session belongs in the same directory.
        let cwd = session.work_dir();
        let what = format!("{} · {}", session.display_label(), argv[0]);
        // What the tab is called: the agent, then which session it is. The
        // command cannot say the second half without spelling out a uuid, and
        // the uuid is the half nobody reads.
        let label = format!(
            "{} · {}",
            argv[0],
            crate::util::truncate(session.display_label(), TAB_LABEL_CHARS)
        );
        // Named after the session, so resuming it a second time reattaches to
        // the agent already doing it rather than starting a rival.
        let tmux = crate::tmux::name_for_session(session.provider.as_str(), &session.session_id);

        // Already on screen: switch to it. tmux would attach a second client to
        // the same agent, which works but leaves two panes fighting over one
        // window's size for no reason.
        //
        // Asked of `resumed` as well as of `tmux`, because without tmux
        // installed every pane's `tmux` is `None` and the question would answer
        // "no" every time — putting a second agent on one transcript, which is
        // the thing `ResumeConfirm` exists to warn about and which would happen
        // here with no warning at all, the session having already stopped.
        if let Some(at) = self.tabs.iter().position(|tab| {
            // `sessions`, not just the panes: the tab may be one this cctop has
            // no client on — another cctop's, or one it detached from itself —
            // and resuming into a second agent is exactly what this guards.
            tab.sessions().any(|name| name == tmux)
                || tab
                    .panes
                    .iter()
                    .any(|p| p.resumed.as_deref() == Some(&tmux))
        }) {
            self.go_to_tab(at + 1);
            self.set_status(format!("Already open: {what}"));
            return;
        }

        let Some(own) = self.own_preferring_tmux(Deferred::Resume, || tmux.clone()) else {
            return;
        };
        // Reattaching is not resuming: the agent was never gone, so saying
        // "resumed" would misdescribe what just happened.
        let verb = match &own {
            tabs::Own::Tmux(name) if crate::tmux::exists(name) => "Reattached to",
            _ => "Resumed",
        };
        self.open_tab(
            &argv,
            NewTab {
                cwd,
                what: &what,
                own,
                verb,
                resumed: Some(tmux),
                label: Some(label),
            },
        );
    }

    /// Where the agent about to start should live, offering to install tmux if
    /// that is the only reason it would not be tmux-backed.
    ///
    /// `None` means the question is on screen and the caller must stop. The
    /// launch is not held anywhere in the meantime — [`Deferred`] records only
    /// which of the two entry points to run again once there is an answer.
    ///
    /// The silent fallback is kept for every machine where the question cannot
    /// be usefully asked — no package manager, or no way to reach root. tmux is
    /// how this is *better*, not how it works, and such a machine gets exactly
    /// the behaviour cctop had before rather than a complaint about a program
    /// the user never asked for. The offer exists for the machine where the
    /// fallback would instead quietly cost the user a feature one keypress away.
    fn own_preferring_tmux(
        &mut self,
        deferred: Deferred,
        name: impl FnOnce() -> String,
    ) -> Option<tabs::Own> {
        if crate::tmux::available() {
            return Some(tabs::Own::Tmux(name()));
        }
        // Asked in this order so that installing tmux in another window still
        // works: `available` above is the live check, and neither a previous
        // "no" nor a running install is consulted until it has said no.
        if self.tmux_declined || self.tmux_installing.is_some() {
            return Some(tabs::Own::Cctop);
        }
        // No package manager to offer means there is nothing to ask about, so
        // this is the plain fallback rather than a refusal: `?` here would
        // return `None`, which the caller reads as "the launch is waiting on an
        // answer" — and no answer would ever come, so the tab never opened.
        let Some(install) = crate::tmux::installer() else {
            return Some(tabs::Own::Cctop);
        };
        self.tmux_install = Some(install);
        self.tmux_deferred = Some(deferred);
        self.mode = Mode::TmuxInstall;
        self.needs_redraw = true;
        None
    }

    /// Answer the tmux offer: run the install in a pane, or give up on tmux for
    /// this run and start the agent on cctop's own pty.
    pub(super) fn tmux_install_answer(&mut self, install: bool) {
        self.mode = Mode::List;
        let Some(offer) = self.tmux_install.take() else {
            return;
        };
        if !install {
            self.tmux_declined = true;
            self.run_deferred_launch();
            return;
        }
        // In a pane, not a subprocess: `sudo` wants a password, and a pane is a
        // pty the user can type it into. It also puts the package manager's
        // output somewhere it can be read, which is the difference between a
        // failed install and a tab that closed for no stated reason.
        match tabs::Pane::launch(&offer.argv, None, tabs::Own::Cctop) {
            Ok(pane) => {
                self.tmux_installing = Some(pane.pid);
                self.tabs.push(tabs::Tab::new(pane));
                self.go_to_tab(self.tabs.len());
                self.set_status(format!("Installing tmux with {}", offer.manager));
            }
            Err(error) => {
                self.set_status(format!("Could not run the install: {error}"));
                self.tmux_declined = true;
                self.run_deferred_launch();
            }
        }
    }

    /// Watch a running install to whichever of its two ends it reaches.
    ///
    /// Called from the poll loop after panes are reaped, so "the pane is gone"
    /// is already true here rather than true one tick later.
    pub(super) fn poll_tmux_install(&mut self) {
        let Some(pid) = self.tmux_installing else {
            return;
        };
        if crate::tmux::available() {
            self.tmux_installing = None;
            self.set_status("tmux installed");
            self.run_deferred_launch();
            return;
        }
        // The pane is gone and tmux is still not here: the install failed, or
        // the user closed it. Either way the launch has waited long enough, and
        // it goes where it would have gone had nothing been offered.
        let open = self
            .tabs
            .iter()
            .flat_map(|tab| tab.panes.iter())
            .any(|pane| pane.pid == pid);
        if !open {
            self.tmux_installing = None;
            self.tmux_declined = true;
            if self.tmux_deferred.is_some() {
                self.set_status("tmux was not installed — starting without it");
            }
            self.run_deferred_launch();
        }
    }

    /// Re-run whichever launch stopped to ask about tmux.
    fn run_deferred_launch(&mut self) {
        match self.tmux_deferred.take() {
            Some(Deferred::Resume) => self.resume_now(),
            Some(Deferred::Launch) => self.launch_selected(),
            None => {}
        }
    }

    /// Start `argv` in a new tab, reporting what happened either way.
    ///
    /// `resumed` names the session the tab is going back to, when it is going
    /// back to one — what the next resume of it looks itself up by.
    fn open_tab(&mut self, argv: &[String], tab: NewTab<'_>) {
        let NewTab {
            cwd,
            what,
            own,
            verb,
            resumed,
            label,
        } = tab;
        let mut pane = match tabs::Pane::launch(argv, cwd.as_deref(), own) {
            Ok(pane) => pane,
            Err(error) => {
                self.set_status(format!("Could not start {what}: {error}"));
                return;
            }
        };
        pane.resumed = resumed;
        if let Some(label) = label {
            pane.label = label;
        }
        // Worth saying once per tab: it changes what quitting cctop means.
        let kept = match pane.outlives_cctop() {
            true => " — it will outlive cctop",
            false => "",
        };
        self.tabs.push(tabs::Tab::new(pane));
        self.go_to_tab(self.tabs.len());
        let where_ = cwd
            .map(|dir| format!(" in {}", crate::util::tildify(&dir.to_string_lossy())))
            .unwrap_or_default();
        self.set_status(format!("{verb} {what}{where_}{kept}"));
    }

    /// Reconcile the tab bar against every cctop-owned tmux session on this
    /// machine, so all the cctops running here show one set of tabs.
    ///
    /// There is no protocol here and no state file, because tmux is already the
    /// shared registry: a tab *is* one of its sessions, the sessions outlive the
    /// cctop that started them, and any cctop can list them. Open a tab in one
    /// window and it appears in the others within [`SHARE_EVERY`]; end its agent
    /// and it leaves them all, for the same reason.
    ///
    /// Only detached tabs are retired here. A tab this cctop is holding a client
    /// on has the reap to notice its agent leaving, which it does the moment the
    /// pty closes rather than at the next sweep.
    ///
    /// New sessions are appended oldest-first, which is the order a cctop that
    /// watched them start already has them in. That is what keeps the bars in
    /// agreement — and with them what Alt+3 means — rather than a cctop opened
    /// later listing the same tabs backwards.
    pub(super) fn sync_shared_tabs(&mut self) {
        if self.shared_at.is_some_and(|at| at.elapsed() < SHARE_EVERY) {
            return;
        }
        self.shared_at = Some(Instant::now());
        let running = crate::tmux::running();

        let mut index = 0;
        let mut retired = false;
        self.tabs.retain(|tab| {
            index += 1;
            let gone = tab.shared.as_ref().is_some_and(|s| {
                // Asked twice, because the listing failing wholesale and every
                // session having ended look identical from here — an empty
                // answer would otherwise empty the tab bar every time the tmux
                // server was restarted. The second question only gets asked
                // about a tab already on its way out, so it costs nothing per
                // sweep.
                !running.iter().any(|agent| agent.name == s.name) && !crate::tmux::exists(&s.name)
            });
            if !gone {
                return true;
            }
            // The tabs after this one shift down by one, so a view sitting on any
            // of them has to follow — the same fixup [`drop_empty_tabs`] does,
            // and for the same reason.
            //
            // [`drop_empty_tabs`]: Self::drop_empty_tabs
            if self.tab >= index {
                self.tab -= 1;
            }
            retired = true;
            false
        });
        self.tab = self.tab.min(self.tabs.len());

        // What tmux now says about the tabs already here. Activity above all:
        // it is how a tab nobody is attached to knows its agent has stopped, and
        // a reading taken once when the tab appeared would have it idle forever.
        for tab in &mut self.tabs {
            let Some(shared) = tab.shared.as_mut() else {
                continue;
            };
            let Some(agent) = running.iter().find(|a| a.name == shared.name) else {
                continue;
            };
            shared.activity = agent.activity;
            // Both can arrive late: the pid in the moment before tmux has
            // spawned the command, the label when the cctop that owns the tab
            // has not written it yet.
            shared.pid = agent.pid.or(shared.pid);
            if let Some(label) = &agent.label {
                shared.label = label.clone();
            }
        }

        let mine = self.open_tmux();
        let mut arrived = false;
        for agent in running.iter().rev() {
            if mine.iter().any(|name| name == &agent.name) {
                continue;
            }
            self.tabs.push(tabs::Tab::shared(agent));
            arrived = true;
        }
        self.needs_redraw |= retired || arrived;
    }

    /// The tmux sessions this cctop already has a pane onto.
    pub fn open_tmux(&self) -> Vec<String> {
        self.tabs
            .iter()
            .flat_map(tabs::Tab::sessions)
            .map(str::to_string)
            .collect()
    }

    /// What the launcher is offering.
    pub fn launch_choices(&self) -> &[tabs::Choice] {
        &self.launch_offer
    }

    /// The profile a launch would use, or `None` when there is only the one and
    /// so nothing to choose between.
    pub fn launch_profile(&self) -> Option<&'static crate::config::ClaudeProfile> {
        let profiles = &*crate::config::CLAUDE_PROFILES;
        (profiles.len() > 1).then(|| profiles.get(self.launch_profile))?
    }

    /// Move to the next profile. Wraps, because with two — which is the case
    /// this exists for — a key that toggles is the whole interaction.
    pub(super) fn cycle_launch_profile(&mut self) {
        let n = crate::config::CLAUDE_PROFILES.len();
        if n > 1 {
            self.launch_profile = (self.launch_profile + 1) % n;
            self.save_prefs();
            self.needs_redraw = true;
        }
    }

    /// Whether `argv` starts Claude Code, and so whether a profile means
    /// anything to it. `$CLAUDE_CONFIG_DIR` is Claude's; setting it in front of
    /// codex would be a promise the env var cannot keep.
    pub(super) fn takes_claude_profile(argv: &[String]) -> bool {
        argv.first()
            .map(|c| c.rsplit(['/', '\\']).next().unwrap_or(c))
            .is_some_and(|c| c == "claude" || c == "claude.exe")
    }

    /// Put the chosen profile in front of the command that will read it.
    ///
    /// `env VAR=value cmd` rather than plumbing an environment through every
    /// spawn path: the same argv is handed to tmux, to a pty cctop owns, and to
    /// `tmux new-session`, and `env` is understood identically by all three.
    /// [`tabs::label_of`] drops the prefix again so the tab is named after the
    /// agent rather than after how it was started.
    fn with_profile(&self, argv: Vec<String>) -> Vec<String> {
        let Some(profile) = self
            .launch_profile()
            .filter(|_| Self::takes_claude_profile(&argv))
        else {
            return argv;
        };
        let mut out = vec![
            "env".to_string(),
            format!("CLAUDE_CONFIG_DIR={}", profile.dir.display()),
        ];
        out.extend(argv);
        out
    }

    /// What a still-running agent in the launcher is doing, if it has said.
    ///
    /// This is the whole reason the offer carries a pid. A list of tmux session
    /// names says which agents exist; this says which one is stuck on a question
    /// and which finished ten minutes ago, from the same hooks the dashboard
    /// reads — so choosing which to go back to is a decision rather than a guess.
    pub fn waiting_state(&self, agent: &crate::tmux::Running) -> Option<crate::hook::Signal> {
        self.pane_signal(agent.pid?)
    }

    /// What to call a still-running agent, when cctop can do better than its
    /// tmux session name.
    ///
    /// That name is an identity and not something written to be read: a resumed
    /// session's carries the whole session id, so it comes out as a timestamp
    /// and a uuid that no two rows differ in until well past the width of the
    /// column. The agent's pid finds its row, and the row already knows what the
    /// dashboard calls it — which is the name the user recognises.
    pub fn waiting_label(&self, agent: &crate::tmux::Running) -> Option<String> {
        let pid = agent.pid?;
        self.sessions
            .iter()
            .find(|session| session_root_pid(session) == Some(pid))
            .map(|session| session.display_label().to_string())
    }

    /// Whether the launcher's pick is an agent already running somewhere.
    ///
    /// Reattaching lands wherever that agent already is, so a directory typed
    /// for it would be accepted and then ignored — which is worse than the key
    /// not being offered.
    pub(super) fn launch_is_reattach(&self) -> bool {
        matches!(
            self.launch_offer.get(self.launch_cursor),
            Some(tabs::Choice::Waiting(_))
        )
    }

    /// Open the launcher's directory field, prefilled with where it would go.
    ///
    /// Prefilled with `~` spelling rather than the absolute path: that is how
    /// the line already reads, and a field that changed what it showed the
    /// moment it became editable would look like it had lost the setting.
    pub(super) fn edit_launch_cwd(&mut self) {
        self.launch_cwd_input = self
            .launch_cwd
            .as_ref()
            .map(|dir| crate::util::tildify(&dir.to_string_lossy()))
            .unwrap_or_default();
        self.launch_cwd_bad = false;
        self.mode = Mode::LaunchCwd;
        self.needs_redraw = true;
    }

    /// Take the typed directory, if it names one.
    ///
    /// Checked here rather than at launch. A path that does not exist fails
    /// somewhere inside the shim with a message about spawning, by which point
    /// the launcher is gone and there is nothing left to correct.
    pub(super) fn accept_launch_cwd(&mut self) {
        let typed = self.launch_cwd_input.trim();
        // Empty means "wherever cctop was started", which is what the launcher
        // offers by default and what the footer calls "this directory".
        let taken = match typed.is_empty() {
            true => None,
            false => {
                let path = std::path::PathBuf::from(crate::util::untildify(typed));
                if !path.is_dir() {
                    self.launch_cwd_bad = true;
                    return;
                }
                Some(path)
            }
        };
        // Cleared on the way out, not only on the way in: a path corrected
        // after a refusal would otherwise carry the mark back to a field that
        // now holds something perfectly good.
        self.launch_cwd_bad = false;
        self.launch_cwd = taken;
        self.mode = Mode::Launch;
    }

    /// Start the launcher's pick.
    pub fn launch_selected(&mut self) {
        let Some(choice) = self.launch_offer.get(self.launch_cursor).cloned() else {
            return;
        };
        let cwd = self.launch_cwd.clone();
        let (argv, own) = match &choice {
            // Reattaching: the agent chose its own command long ago, and the
            // argv here only names the tab.
            tabs::Choice::Waiting(agent) => (
                vec![choice.label()],
                tabs::Own::TmuxExisting(agent.name.clone()),
            ),
            // A fresh agent has no identity to be idempotent about — two
            // `claude` tabs are two agents — so this takes the next free name
            // rather than a derived one.
            tabs::Choice::Start(argv) => {
                let own = self.own_preferring_tmux(Deferred::Launch, || {
                    crate::tmux::free_name(&tabs::label_of(argv))
                });
                // The offer went up instead. This runs again from the top when
                // it is answered, and the launcher's snapshot is still here to
                // run it from.
                let Some(own) = own else { return };
                (self.with_profile(argv.clone()), own)
            }
        };
        // The offer is a snapshot, and an agent can finish in the time the modal
        // is up. Attaching to a session that has gone spawns a client that exits
        // at once — a tab that flickers and vanishes, where the truth is simply
        // that the agent ended while being looked at.
        if let tabs::Choice::Waiting(agent) = &choice
            && !crate::tmux::exists(&agent.name)
        {
            self.set_status(format!("{} has ended", choice.label()));
            return;
        }

        let argv = &argv;
        let mut pane = match tabs::Pane::launch(argv, cwd.as_deref(), own) {
            Ok(pane) => pane,
            Err(error) => {
                self.set_status(format!("Could not start {}: {error}", tabs::label_of(argv)));
                return;
            }
        };
        // The profile is only knowable here: it reached the agent as an
        // environment variable, which nothing downstream can read back.
        if matches!(choice, tabs::Choice::Start(_)) {
            pane.profile = self.launch_profile().map(|p| p.name.clone());
        }
        let label = pane.label.clone();
        // A brief goes to an agent that is starting fresh. Reattaching lands in
        // a conversation already under way, where typing a "read this and
        // continue" line would interrupt whatever it is doing mid-turn.
        if let Some(path) = self.pending_brief.take()
            && matches!(choice, tabs::Choice::Start(_))
        {
            self.handoff_send = Some((
                pane.pid,
                crate::handoff::prompt_for(&path),
                Instant::now() + HANDOFF_SETTLE,
            ));
        }
        let kept = match pane.outlives_cctop() {
            true => " — it will outlive cctop",
            false => "",
        };
        match self.launch_into {
            LaunchInto::Split { stacked } => {
                let Some(tab) = self.active_tab() else { return };
                tab.stacked = stacked;
                tab.panes.push(pane);
                tab.focus = tab.panes.len() - 1;
            }
            LaunchInto::Tab => {
                self.tabs.push(tabs::Tab::new(pane));
                self.go_to_tab(self.tabs.len());
            }
        }
        // Reattaching is not starting, and it does not land in the launcher's
        // directory: the agent has been working somewhere since before any of
        // this and stays there. Saying "Started ... in ~/here" would be wrong
        // twice over.
        self.set_status(match &choice {
            tabs::Choice::Waiting(agent) => {
                let at = agent
                    .cwd
                    .as_ref()
                    .map(|dir| format!(" in {}", crate::util::tildify(&dir.to_string_lossy())))
                    .unwrap_or_default();
                format!("Reattached to {label}{at} — it was never gone")
            }
            tabs::Choice::Start(_) => {
                let where_ = cwd
                    .map(|dir| format!(" in {}", crate::util::tildify(&dir.to_string_lossy())))
                    .unwrap_or_default();
                format!("Started {label}{where_}{kept}")
            }
        });
    }

    /// Close the focused pane, ending the agent behind it.
    ///
    /// Closing used to detach from a tmux-backed agent and leave it running,
    /// which meant the tab came back at the next launch and the only way to be
    /// rid of it was a second key. Closing a window is meant to be the end of
    /// it, so this kills the tmux session outright — the same thing Alt+Shift+W
    /// does, which is now a synonym rather than the only way to stop an agent.
    ///
    /// The exception is a pane opened with `a`, which is a window onto somebody
    /// else's agent. There is nothing here to kill and stopping it was never
    /// cctop's to do, so that one is only closed.
    pub fn close_pane(&mut self) {
        let Some(tab) = self.active_tab() else {
            return;
        };
        // A tab standing for a session no client of ours is on has no pane here
        // to close — but the agent is still cctop's to end, and this tab is the
        // only handle on screen for it. So the key means what it means anywhere
        // else, and the tab leaves every cctop rather than just this one.
        if tab.detached()
            && let Some(shared) = tab.shared.take()
        {
            let stopped = crate::tmux::kill(&shared.name);
            self.drop_empty_tabs();
            self.set_status(match stopped {
                Err(error) => format!("Could not stop {}: {error}", shared.label),
                Ok(()) => format!("Stopped {}", shared.label),
            });
            return;
        }
        if tab.focus >= tab.panes.len() {
            return;
        }
        // Out of the tab first: for a cctop-owned pty, dropping the pane is the
        // kill, and it must happen either way rather than only when tmux agrees.
        let pane = tab.panes.remove(tab.focus);
        tab.focus = tab.focus.min(tab.panes.len().saturating_sub(1));
        let label = pane.label.clone();
        let stopped = pane.owns_agent().then(|| pane.kill_agent());
        drop(pane);
        self.drop_empty_tabs();

        self.set_status(match stopped {
            Some(Err(error)) => format!("Closed {label}, but could not stop it: {error}"),
            Some(Ok(())) => format!("Stopped {label}"),
            None => format!("Closed the view of {label} — it is not cctop's to stop"),
        });
    }

    /// End the focused pane's agent outright. A synonym for [`close_pane`],
    /// kept because it is documented and in muscle memory.
    ///
    /// [`close_pane`]: Self::close_pane
    pub fn kill_pane(&mut self) {
        self.close_pane();
    }

    /// Forget the tabs whose agents have all exited, keeping the view on
    /// something that still exists.
    pub fn drop_empty_tabs(&mut self) {
        let mut index = 0;
        self.tabs.retain(|tab| {
            index += 1;
            // A detached tab holds no pane on purpose; only the sync retires it.
            if !tab.panes.is_empty() || tab.shared.is_some() {
                return true;
            }
            // The tabs after this one shift down by one, so a view sitting on
            // any of them has to follow — otherwise closing tab 1 silently
            // moves you to what used to be tab 2.
            if self.tab >= index {
                self.tab -= 1;
            }
            false
        });
        self.tab = self.tab.min(self.tabs.len());
    }

    /// Put the selected agent's own terminal on screen, in a tab of its own.
    ///
    /// Two ways in, because there are two ways an agent's terminal can belong to
    /// cctop. A shim holding a pty has a copy of the output to give away; an agent
    /// handed to tmux has none, and is reached by becoming another of its clients
    /// instead. Either way this only *looks* at the agent — closing the pane
    /// detaches from it and never ends it.
    pub(super) fn attach_selected(&mut self) {
        let Some(session) = self.selected_session() else {
            return;
        };
        let label = format!("{} · {}", session.abbrev_label, session.model);
        let title = session.display_label().to_string();
        // How a resume names this same session. Recorded on the pane below so
        // that `R` afterwards finds the agent already on screen instead of
        // starting a second one on one transcript — `a` and `R` reach the same
        // agent by different routes, and only this makes them agree.
        let resumed = crate::tmux::name_for_session(session.provider.as_str(), &session.session_id);
        let Some(pid) = session_root_pid(session) else {
            self.set_status("Selected session has no local process");
            return;
        };
        if self.open_view(pid, label.clone()) {
            return;
        }
        // Started by cctop and then handed to tmux. Without this the message
        // below would say cctop did not start an agent cctop started, and send
        // the user to relaunch something that is already running.
        if let Some(name) = crate::tmux::holding(pid) {
            // A second client onto one session leaves the two panes arguing over
            // one window's size, so an agent already on screen is switched to.
            if let Some(at) = self
                .tabs
                .iter()
                .position(|tab| tab.sessions().any(|open| open == name))
            {
                self.go_to_tab(at + 1);
                self.set_status(format!("Already open: {label}"));
                return;
            }
            self.open_tab(
                &[title],
                NewTab {
                    cwd: None,
                    what: &label,
                    own: tabs::Own::TmuxExisting(name),
                    verb: "Attached to",
                    resumed: Some(resumed),
                    // Already a bare agent name, so the command names it right.
                    label: None,
                },
            );
            return;
        }
        self.set_status(
            "Only sessions started by cctop can be attached — start them as `cctop claude`",
        );
    }

    /// Go back to the agent this cctop launched.
    ///
    /// Without this, F12 would be a one-way door: a freshly started agent has
    /// written no transcript yet, so it has no row in the table to press `a` on.
    pub(super) fn attach_hosted(&mut self) {
        let Some((pid, label)) = self.hosted.clone() else {
            self.set_status("No agent was launched by this cctop — start one as `cctop claude`");
            return;
        };
        if !self.open_view(pid, label) {
            self.set_status("The agent's terminal is gone");
        }
    }

    /// Take up the tmux-backed agents already running on this machine — the ones
    /// this cctop left alive on a previous exit, and the ones another cctop has
    /// open right now.
    ///
    /// The tmux session is the durable workspace state: it preserves the agent,
    /// its scrollback, and working directory. There is no difference worth
    /// drawing between a session left by a cctop that has quit and one another
    /// cctop is using, so this makes no attempt to: both are tabs, and both
    /// arrive detached. Only the one put on screen takes a client.
    ///
    /// Oldest first, matching [`sync_shared_tabs`] — a cctop opened now and one
    /// that watched these start must number their tabs the same way.
    ///
    /// [`sync_shared_tabs`]: Self::sync_shared_tabs
    pub(super) fn restore_running_tabs(&mut self) {
        for agent in crate::tmux::running().iter().rev() {
            self.tabs.push(tabs::Tab::shared(agent));
        }
        if !self.tabs.is_empty() {
            self.go_to_tab(1);
        }
    }

    /// Show the agent running as `pid`, reusing the pane already on it rather
    /// than opening a second window onto one terminal.
    ///
    /// A pane is a match on either pid it has: the one cctop hosts, and — for a
    /// tmux-backed pane, where that one is only the client — the agent's own.
    /// Asking about the hosted pid alone missed every tmux-backed pane, so an
    /// agent already on screen got a second window onto it.
    fn open_view(&mut self, pid: u32, label: String) -> bool {
        let shows = |pane: &tabs::Pane| pane.pid == pid || pane.agent() == pid;
        if let Some(index) = self.tabs.iter().position(|tab| tab.panes.iter().any(shows)) {
            let tab = &mut self.tabs[index];
            tab.focus = tab.panes.iter().position(shows).unwrap_or(0);
            self.go_to_tab(index + 1);
            return true;
        }
        // The agent may be one of the shared tabs instead, watched by no client
        // of this cctop. Switching there attaches one, which is the same window
        // onto the same agent that the branch above found — and still not a
        // second one.
        if let Some(index) = self
            .tabs
            .iter()
            .position(|tab| tab.shared.as_ref().is_some_and(|s| s.pid == Some(pid)))
        {
            self.go_to_tab(index + 1);
            return true;
        }
        let Some(pane) = tabs::Pane::view_of(pid, label) else {
            return false;
        };
        self.tabs.push(tabs::Tab::new(pane));
        self.go_to_tab(self.tabs.len());
        true
    }
}

/// Columns the user has hidden outright, which win over the automatic
/// width-based dropping in [`columns::visible_columns`].
///
/// `$CCTOP_COLUMNS_HIDE` is the only source today and is meant to stay an
/// override once a persisted one exists: `UiPrefs` is the natural home for the
/// stored list, but it lives in `cache.rs`, which this module does not own, and
/// carries no such field yet. When it grows one, read it here and let a
/// non-empty env var take precedence.
fn hidden_columns(_prefs: &UiPrefs) -> Vec<ColumnId> {
    columns::parse_hidden(&std::env::var("CCTOP_COLUMNS_HIDE").unwrap_or_default())
}

/// `haystack.to_ascii_lowercase().contains(needle)` without the allocation.
///
/// Comparing bytes is safe on UTF-8 here: ASCII case folding never touches a
/// continuation byte, so a match can only start at a character boundary.
fn contains_ascii_ci(haystack: &str, lowercase_needle: &str) -> bool {
    let (h, n) = (haystack.as_bytes(), lowercase_needle.as_bytes());
    if n.is_empty() {
        return true;
    }
    h.len() >= n.len()
        && h.windows(n.len())
            .any(|w| w.iter().zip(n).all(|(a, b)| a.to_ascii_lowercase() == *b))
}

/// PID of the currently live agent root, excluding briefly retained exits.
fn session_root_pid(session: &Session) -> Option<u32> {
    session
        .process
        .as_ref()?
        .process_list
        .iter()
        .find_map(|process| (process.is_root && !process.ghost).then_some(process.pid))
}

/// The eight characters a Gemini chat file is named after, out of the row id
/// that file produced: `session-2026-05-14T17-34-79709c93` yields `79709c93`.
///
/// `None` for every other harness's ids, which is what keeps this from matching
/// on the tail of a uuid that happens to line up: only a stem shaped like
/// Gemini's is looked up loosely, and only ever against a full id's prefix.
fn gemini_id_tail(session_id: &str) -> Option<&str> {
    let tail = session_id.strip_prefix("session-")?.rsplit_once('-')?.1;
    (tail.len() == 8 && tail.chars().all(|c| c.is_ascii_alphanumeric())).then_some(tail)
}

// ---------------------------------------------------------------------------
// Event handling
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// Entry point
// ---------------------------------------------------------------------------

/// Run the UI. `hosted` is an agent cctop launched for this session, which it
/// shows attached and outlives by nothing: when the agent exits, so does cctop,
/// so `cctop claude` gets you back to your shell the way `claude` would.
pub fn run(args: &Args, hosted: Option<crate::shim::Hosted>) -> anyhow::Result<i32> {
    // Before anything draws, and once: the palette is read by every widget and
    // must not change under them mid-run.
    theme::init_from_env();

    let (req_tx, req_rx) = channel::<Request>();
    let (res_tx, res_rx) = channel::<Response>();
    let worker = spawn_worker(args.plan, req_rx, res_tx.clone());

    // Pricing and quota are network-bound; keep both off the UI thread.
    {
        let tx = res_tx.clone();
        std::thread::spawn(move || {
            crate::pricing::refresh_pricing_blocking();
            let _ = tx.send(Response::PricingReady);
        });
    }
    spawn_quota_poller(res_tx.clone());
    let hosts = crate::fleet::Host::collect(&args.hosts);
    for host in &hosts {
        spawn_host_poller(host.clone(), res_tx.clone());
    }

    // One cached check per day, off the UI thread. Only ever reports: replacing
    // the binary stays behind an explicit `--update`.
    std::thread::spawn(move || {
        if let Some(version) = crate::update::available_update() {
            let _ = res_tx.send(Response::UpdateAvailable(version));
        }
    });

    let mut app = App::new(args.plan, req_tx.clone());
    app.refresh_secs = args.delay;
    // With nothing to put in it, HOST is a column of one repeated word. Hidden
    // through the same mechanism the user has, so `$CCTOP_COLUMNS_HIDE` and this
    // cannot disagree about what is on screen.
    if hosts.is_empty() {
        app.hidden_columns.push(ColumnId::Host);
    }
    // Likewise USER: with only this user's homes in view, every row's owner is
    // the person reading the screen.
    if crate::config::OTHER_HOMES.is_empty() {
        app.hidden_columns.push(ColumnId::User);
    }
    // And PROFILE, which most machines have exactly one of. A column repeating
    // `default` down every row is a column that answers nothing.
    if crate::config::claude_profile_count() <= 1 {
        app.hidden_columns.push(ColumnId::Profile);
    }
    let _ = req_tx.send(Request::Refresh);

    // Tabs backed by tmux outlive cctop. Reattach them before the first frame
    // so reopening the dashboard restores the workspace rather than making the
    // user find and reopen every surviving agent through the launcher.
    app.restore_running_tabs();

    // Attach before the first frame: the agent cctop was asked to launch is the
    // reason it is running, so it should be on screen and not behind a keypress.
    // Its own session row appears later, once it has written a transcript.
    let mut hosted = hosted;
    if let Some(hosted) = hosted.as_ref() {
        app.hosted = Some((hosted.pid, hosted.label.clone()));
        app.attach_hosted();
    }

    // `ratatui::init` installs a hook that leaves the alt screen and raw mode on
    // panic, but it knows nothing about the mouse capture enabled below, nor does
    // its restore path make the cursor visible again. Without this, a panic can
    // leave the user's shell receiving mouse escape sequences or with no cursor.
    // Installed after `init` so it runs before ratatui's restore hook.
    let mut terminal = ratatui::init();
    let previous_hook = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |info| {
        restore_terminal();
        previous_hook(info);
    }));
    let _ = execute!(std::io::stdout(), EnableMouseCapture);
    // Bracketed paste, so a paste arrives as one `Event::Paste` instead of as
    // one `Event::Key` per character. Without it there is no way to tell a paste
    // from typing, and the newlines in a pasted message reach the agent as the
    // Enter that submits it — a five-line paste asking five questions.
    let _ = execute!(std::io::stdout(), EnableBracketedPaste);

    // Established before the loop so the first tick already has it; `None` just
    // means discovery falls back to the periodic walk.
    let watch = crate::watch::Watch::start();
    app.listener = crate::hook::Listener::start();
    // A hook naming a cctop that has since been moved or deleted fires nothing
    // at all, so it is repointed here rather than left to look installed while
    // reporting nothing. Anything narrower than that is left for the panel.
    for fixed in crate::hook::repair(app.hook_project().as_deref()) {
        app.set_status(&fixed);
    }
    // What repair deliberately would not touch: an install registering fewer
    // events than this cctop wants, or a settings file that will not parse.
    // Both look installed and quietly deliver less than they should, so they
    // are worth one line on the way in — an install that is simply absent is
    // not, since that is a choice and nagging about it is what makes people
    // stop reading the status line.
    if app
        .hook_status()
        .entries
        .iter()
        .any(|s| s.health.is_problem())
    {
        app.set_status("Agent hooks need attention — press h");
    }

    let result = event_loop(
        &mut app,
        &mut terminal,
        &res_rx,
        &req_tx,
        watch.as_ref(),
        hosted.as_mut(),
    );

    // Before the terminal is restored, so the agent's hangup does not race the
    // screen being handed back. Clearing the tabs only ends the panes; a
    // tmux-backed one is a client, and the agent behind it is left running —
    // which is the point, and so worth saying out loud on the way out.
    let had_tabs = !app.open_tmux().is_empty();
    app.tabs.clear();
    drop(hosted);

    // Asked after the clients are gone, and asked of tmux rather than of the
    // tabs: an agent left running by an earlier cctop is just as reachable as
    // one from this run, and the line below is the only thing that tells anyone
    // they are there at all.
    let left_running = match had_tabs {
        true => crate::tmux::sessions(),
        // Nothing here ever touched tmux, so nothing here is owed an account of
        // what is in it.
        false => Vec::new(),
    };

    restore_terminal();

    // After the restore, so it lands on the terminal the user is handed back
    // rather than inside the alternate screen that is about to be torn down.
    if !left_running.is_empty() {
        println!(
            "{} agent{} still running in tmux; `cctop` then `t` to get back to {}.",
            left_running.len(),
            if left_running.len() == 1 { "" } else { "s" },
            if left_running.len() == 1 {
                "it"
            } else {
                "them"
            },
        );
    }

    let _ = req_tx.send(Request::Shutdown);
    // The worker persists newly extracted transcript data while shutting down.
    // Joining it matters: returning from main immediately would otherwise kill
    // the detached thread mid-save, forcing every launch to parse all sessions
    // from scratch again.
    let _ = worker.join();
    app.save_prefs();
    result
}

/// Undo every terminal mode the TUI may have changed.
///
/// `ratatui::restore` intentionally only disables raw mode and leaves the
/// alternate screen; it does not restore cursor visibility. Keep this separate
/// so regular exits, input errors, and panics all use the same cleanup path.
fn restore_terminal() {
    let _ = execute!(std::io::stdout(), DisableBracketedPaste);
    let _ = execute!(std::io::stdout(), DisableMouseCapture);
    let _ = execute!(std::io::stdout(), Show);
    ratatui::restore();
    // Send Show once more after leaving the alternate screen. Some terminals
    // scope cursor state to the active screen buffer.
    let _ = execute!(std::io::stdout(), Show);
}

/// Read one machine on a timer until cctop exits.
///
/// A thread rather than a slot in the worker's queue: an ssh round trip can
/// take seconds or hang until its timeout, and the worker is what answers the
/// keyboard's refresh. One wedged host must cost only itself.
fn spawn_host_poller(host: crate::fleet::Host, tx: Sender<Response>) {
    std::thread::spawn(move || {
        loop {
            let snapshot = host.poll();
            if tx
                .send(Response::Remote {
                    host: host.target.clone(),
                    snapshot,
                })
                .is_err()
            {
                // The UI has gone; so should this.
                return;
            }
            std::thread::sleep(crate::fleet::POLL);
        }
    });
}

fn spawn_quota_poller(tx: Sender<Response>) {
    std::thread::spawn(move || {
        let mut quota = Quota::default();
        let (mut claude_due, mut codex_due) = (Instant::now(), Instant::now());

        loop {
            let now = Instant::now();
            let mut changed = false;

            // Each provider is paced by its own last outcome: a throttled one
            // backs off without stalling the other.
            if now >= claude_due {
                // Each profile is its own account with its own limits, so each
                // is asked separately. They share one due time: the interval
                // exists to be polite to the provider, and a machine with two
                // logins is not entitled to twice the requests.
                quota.claude = crate::config::CLAUDE_PROFILES
                    .iter()
                    .map(|profile| crate::quota::ClaudeQuota {
                        profile: profile.name.clone(),
                        status: crate::quota::fetch_claude(profile),
                    })
                    .collect();
                // Paced by whichever account is most throttled, so backing off
                // for one does not keep asking on behalf of another.
                let delay = quota
                    .claude
                    .iter()
                    .map(|q| q.status.retry_delay_secs(QUOTA_INTERVAL_SECS))
                    .max()
                    .unwrap_or(QUOTA_INTERVAL_SECS);
                claude_due = now + Duration::from_secs(delay);
                changed = true;
            }
            if now >= codex_due {
                let status = crate::quota::fetch_codex();
                codex_due = now + Duration::from_secs(status.retry_delay_secs(QUOTA_INTERVAL_SECS));
                quota.codex = status;
                changed = true;
            }

            if changed {
                quota.fetched = true;
                if tx.send(Response::Quota(Box::new(quota.clone()))).is_err() {
                    break;
                }
            }
            std::thread::sleep(QUOTA_TICK);
        }
    });
}

fn event_loop(
    app: &mut App,
    terminal: &mut ratatui::DefaultTerminal,
    res_rx: &Receiver<Response>,
    req_tx: &Sender<Request>,
    watch: Option<&crate::watch::Watch>,
    mut hosted: Option<&mut crate::shim::Hosted>,
) -> anyhow::Result<i32> {
    let mut last_refresh = Instant::now();
    let mut last_full_walk = Instant::now();
    let mut layout = render::Layout::default();
    let mut refresh_in_flight = true;
    let mut last_blink = true;

    loop {
        // Drain everything the workers have produced.
        let mut annotated_rows_changed = false;
        // Only a refresh can move a session between busy and waiting, so the
        // notifier is fed here rather than once per loop iteration — that would
        // rebuild its map five times a second over rows that hadn't moved.
        let mut rows_changed = false;
        loop {
            match res_rx.try_recv() {
                Ok(Response::Discovered(sessions)) => {
                    app.sessions = sessions;
                    app.loaded = true;
                    app.stats = crate::loader::compute_stats(&app.sessions);
                    app.refilter();
                    app.merge_remotes();
                    rows_changed = true;
                }
                Ok(Response::Annotated(session)) => {
                    // Match on the key's two fields rather than on `key()`: that
                    // formats a String per candidate, so a scan over thousands of
                    // rows allocated thousands of times — per arriving row, on the
                    // thread that also has to answer the keyboard.
                    // `remote.is_none()` is part of the identity, not a
                    // nicety: the worker only ever reports local rows, and a
                    // remote session that happened to share an id would be
                    // overwritten by one from this machine.
                    let found = app.sessions.iter_mut().find(|s| {
                        s.remote.is_none()
                            && s.provider == session.provider
                            && s.session_id == session.session_id
                    });
                    if let Some(existing) = found {
                        *existing = *session;
                    } else {
                        app.sessions.push(*session);
                    }
                    annotated_rows_changed = true;
                }
                Ok(Response::Sessions(payload)) => {
                    let (sessions, stats) = *payload;
                    app.sessions = sessions;
                    app.loaded = true;
                    app.stats = stats;
                    app.merge_remotes();
                    app.push_history();
                    app.refilter();
                    refresh_in_flight = false;
                    annotated_rows_changed = false;
                    rows_changed = true;
                }
                Ok(Response::LiveRows(payload)) => {
                    let (rows, stats) = *payload;
                    for row in rows {
                        let found = app.sessions.iter_mut().find(|s| {
                            s.remote.is_none()
                                && s.provider == row.provider
                                && s.session_id == row.session_id
                        });
                        match found {
                            Some(existing) => *existing = row,
                            // A session that started since the last full walk.
                            None => app.sessions.push(row),
                        }
                    }
                    app.adopt_stats(stats);
                    app.loaded = true;
                    app.push_history();
                    app.refilter();
                    refresh_in_flight = false;
                    rows_changed = true;
                }
                Ok(Response::Data(key, data)) => {
                    // Discard results for a session the user has already left.
                    if key == app.panel_key {
                        app.panel_data = Some(*data);
                        app.needs_redraw = true;
                    }
                }
                Ok(Response::Quota(q)) => {
                    app.quota = *q;
                    app.needs_redraw = true;
                }
                Ok(Response::UpdateAvailable(version)) => {
                    app.update_available = Some(version);
                    app.needs_redraw = true;
                }
                Ok(Response::PricingReady) => {
                    // Cached costs were computed without rates; recompute them.
                    let _ = req_tx.send(Request::Refresh);
                    refresh_in_flight = true;
                }
                Ok(Response::Terminated {
                    session_key,
                    result,
                }) => match result {
                    Ok(()) => {
                        app.set_status("Termination signal sent");
                        let _ = req_tx.send(Request::Refresh);
                        refresh_in_flight = true;
                    }
                    Err(error) => {
                        app.set_status(format!("Could not stop {session_key}: {error}"));
                    }
                },
                Ok(Response::Deleted {
                    session_key,
                    result,
                }) => {
                    app.deleting.remove(&session_key);
                    match result {
                        Ok(()) => {
                            app.sessions.retain(|session| session.key() != session_key);
                            app.marked.remove(&session_key);
                            app.stats = crate::loader::compute_stats(&app.sessions);
                            app.refilter();
                            app.set_status("Deleted session");
                        }
                        Err(error) => {
                            app.set_status(format!("Could not delete {session_key}: {error}"))
                        }
                    }
                }
                Ok(Response::KeysSent { result }) => match result {
                    Ok(()) => app.set_status("Sent to the session's terminal"),
                    Err(error) => app.set_status(error),
                },
                Ok(Response::Remote { host, snapshot }) => {
                    match snapshot {
                        crate::fleet::Snapshot::Rows(rows) => {
                            app.remote_errors.remove(&host);
                            app.remotes.insert(host, rows);
                        }
                        // The last good snapshot is kept rather than blanked: a
                        // dropped ssh connection has not stopped those agents,
                        // and an empty machine is a stronger claim than a stale
                        // one. The footer says the reading is old.
                        crate::fleet::Snapshot::Failed(why) => {
                            app.remote_errors.insert(host, why);
                        }
                    }
                    app.merge_remotes();
                    rows_changed = true;
                }
                Ok(Response::Scanned { query, hits }) => app.scanned(query, hits),
                Err(TryRecvError::Empty) | Err(TryRecvError::Disconnected) => break,
            }
        }
        if annotated_rows_changed || rows_changed {
            // Extraction rebuilds each subagent from its transcript, which
            // cannot know what a hook already reported, so the hook's answer is
            // reapplied to every batch of rows that replaces them. The same
            // goes for the permission mode, which no transcript records at all.
            app.apply_finished_agents();
            app.apply_permissions();
            // After the hooks, because a row's liveness is what decides whether
            // it can still race anyone, and cheap enough to redo wholesale:
            // it compares paths already in memory and reads no transcript.
            app.collisions = crate::collide::apply(&mut app.sessions);
        }
        if annotated_rows_changed {
            // A burst can contain hundreds of rows. Recompute and sort once
            // after draining it rather than once per transcript.
            app.stats = crate::loader::compute_stats(&app.sessions);
            app.refilter();
        }
        if rows_changed {
            app.check_bells();
        }

        app.sync_panel_data();
        app.tick_scan();

        // Every tab, not just the visible one: an agent whose output nobody
        // reads eventually blocks on writing it.
        let mut drawn = false;
        for tab in &mut app.tabs {
            drawn |= tab.pump();
        }
        let closed = app.tabs.iter_mut().fold(false, |any, tab| tab.reap() | any);
        if closed {
            app.drop_empty_tabs();
        }
        // After the reap, so a finished install is seen as finished on the same
        // tick its pane goes away.
        app.poll_tmux_install();
        // And after both, so a tab this cctop has just lost is not immediately
        // re-added by a listing taken before its session went.
        app.sync_shared_tabs();
        if drawn || closed {
            app.needs_redraw = true;
        }

        // Hook events arrive whenever an agent hits one, which is not on any
        // tick of ours, so they are drained here alongside everything else.
        if let Some(events) = app.listener.as_ref().map(crate::hook::Listener::drain) {
            let (changed, lifecycle) = app.apply_hooks(events);
            app.needs_redraw |= changed;
            // A session that has just begun or ended is a row to find or forget
            // now. Waiting for the next poll would leave an agent the user just
            // started missing from the table for as long as the interval, which
            // is precisely the moment they are looking for it.
            if lifecycle && !refresh_in_flight {
                let _ = req_tx.send(Request::Refresh);
                refresh_in_flight = true;
                last_refresh = Instant::now();
            }
        }

        // A brief for a just-launched agent comes due on a timer rather than an
        // event, so the loop is the only thing that can notice.
        app.tick_handoff();

        // A blinking tab is the one thing on screen that changes with no event
        // behind it, so the loop has to ask for the frame itself — but only on
        // the half-cycle it actually flips, not on every poll.
        let phase = app.blink_on();
        if phase != last_blink && app.any_attention() {
            app.needs_redraw = true;
        }
        last_blink = phase;

        // Expire the transient status line.
        if let Some((_, at)) = &app.status
            && at.elapsed() > Duration::from_secs(3)
        {
            app.status = None;
            app.needs_redraw = true;
        }

        if app.needs_redraw {
            terminal.draw(|frame| layout = render::draw(frame, app))?;
            app.needs_redraw = false;
        }

        // Wait for input, but never past the next scheduled refresh. The
        // interval is read live so +/- changes apply on the very next poll.
        let refresh_every = Duration::from_secs_f64(app.refresh_secs);
        // Attached, the same wait is what stands between a keystroke and seeing
        // it echoed, so it drops to a frame's worth.
        let idle_wait = match app.tab {
            0 => Duration::from_millis(200),
            _ => Duration::from_millis(16),
        };
        let wait = refresh_every
            .checked_sub(last_refresh.elapsed())
            .unwrap_or(Duration::ZERO)
            .min(idle_wait);
        if event::poll(wait)? {
            match event::read()? {
                Event::Key(key) => app.on_key(key),
                Event::Paste(text) => app.on_paste(&text),
                Event::Mouse(m) => app.on_mouse(m, &layout),
                Event::Resize(_, _) => app.needs_redraw = true,
                _ => {}
            }
        }

        // The agent cctop was launched to run has finished, so cctop has nothing
        // left to do either: hand its exit code back and get out of the way.
        if let Some(hosted) = hosted.as_mut()
            && let Some(code) = hosted.finished()
        {
            return Ok(code);
        }

        if app.should_quit {
            break;
        }

        // Only one refresh in flight: a scan slower than the interval must not
        // queue up behind itself.
        let refresh_every = Duration::from_secs_f64(app.refresh_secs);
        if last_refresh.elapsed() >= refresh_every && !refresh_in_flight {
            last_refresh = Instant::now();
            refresh_in_flight = true;
            // Walking every provider directory is what scales with the number of
            // sessions ever created, while what the user watches scales with the
            // number running now. So the fast tick updates the running rows and
            // the walk — the only thing that can notice a *new* session — runs on
            // its own slower cadence.
            let watched_change = watch.is_some_and(crate::watch::Watch::took_structural_change);
            // A transcript is created before it is summarizable — the model name
            // only arrives with the first assistant message — so the walk the
            // create earned can find nothing. Keep walking, at a cadence between
            // the fast tick and the safety net, until the file becomes a session.
            let awaiting = !watched_change
                && last_full_walk.elapsed() >= PENDING_WALK_INTERVAL
                && watch.is_some_and(|w| {
                    w.awaiting_discovery(|path| {
                        app.sessions
                            .iter()
                            .any(|s| s.data_file.as_deref() == Some(path))
                    })
                });
            let full_due =
                watched_change || awaiting || last_full_walk.elapsed() >= FULL_WALK_INTERVAL;
            if full_due {
                last_full_walk = Instant::now();
            }
            let _ = req_tx.send(if full_due {
                Request::Refresh
            } else {
                Request::RefreshLive
            });
        }
    }
    // Quit was pressed rather than the agent exiting, so there is no exit code
    // to inherit.
    Ok(0)
}

#[cfg(test)]
mod tests {
    use super::*;
    use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

    fn test_app() -> App {
        let (tx, rx) = channel();
        // Keep the receiver alive so sends in tests don't fail.
        std::mem::forget(rx);
        App::with_prefs(Plan::Retail, tx, UiPrefs::default())
    }

    /// A tab dragged along the bar takes its place there, and the view stays on
    /// the agent it was watching — whether that is the tab that moved or one the
    /// move shifted past. Getting the second wrong drops you into somebody
    /// else's terminal for rearranging the bar around it.
    #[test]
    fn a_dragged_tab_moves_without_moving_the_view() {
        let named = |name: &str| {
            tabs::Tab::shared(&crate::tmux::Running {
                name: format!("cctop-{name}"),
                pid: None,
                cwd: None,
                attached: false,
                activity: None,
                label: Some(name.to_string()),
            })
        };
        let titles = |app: &App| -> Vec<String> { app.tabs.iter().map(tabs::Tab::title).collect() };

        let mut app = test_app();
        app.tabs = vec![named("a"), named("b"), named("c")];

        // The tab you are on, dragged to the end: it goes there and you go with
        // it.
        app.tab = 1;
        app.move_tab(1, 3);
        assert_eq!(titles(&app), ["b", "c", "a"]);
        assert_eq!(app.tab, 3);

        // A tab dragged past the one you are watching: the bar changes, the
        // agent in front of you does not.
        app.tab = 1; // "b"
        app.move_tab(3, 1); // "a" back to the front
        assert_eq!(titles(&app), ["a", "b", "c"]);
        assert_eq!(app.tab, 2, "the view followed the position, not the tab");

        // The dashboard is not a tab in the list, and neither end of a move can
        // be it.
        app.move_tab(0, 2);
        app.move_tab(2, 0);
        assert_eq!(titles(&app), ["a", "b", "c"]);

        // The keyboard's half, clamped at both ends rather than wrapping.
        app.tab = 1;
        app.move_workspace(-1);
        assert_eq!(
            titles(&app),
            ["a", "b", "c"],
            "the first tab has nowhere to go"
        );
        app.move_workspace(1);
        assert_eq!(titles(&app), ["b", "a", "c"]);
        assert_eq!(app.tab, 2);
    }

    /// The drag itself: pressing a tab picks it up, moving over another one
    /// carries it there, and the release ends it. The whole gesture is the
    /// bar's, so none of it reaches the agents underneath.
    #[test]
    fn dragging_a_tab_along_the_bar_reorders_it() {
        let named = |name: &str| {
            tabs::Tab::shared(&crate::tmux::Running {
                name: format!("cctop-{name}"),
                pid: None,
                cwd: None,
                attached: false,
                activity: None,
                label: Some(name.to_string()),
            })
        };
        let layout = render::Layout {
            // The dashboard, then a tab per name, as the bar draws them.
            workspace_spans: vec![(0, 11, 0), (11, 15, 1), (15, 19, 2), (19, 23, 3)],
            ..Default::default()
        };
        let at = |kind, column| event::MouseEvent {
            kind,
            column,
            row: 0,
            modifiers: event::KeyModifiers::NONE,
        };
        let press = event::MouseEventKind::Down(event::MouseButton::Left);
        let drag = event::MouseEventKind::Drag(event::MouseButton::Left);
        let release = event::MouseEventKind::Up(event::MouseButton::Left);

        let mut app = test_app();
        app.tabs = vec![named("a"), named("b"), named("c")];
        let titles = |app: &App| -> Vec<String> { app.tabs.iter().map(tabs::Tab::title).collect() };

        // Press on the first tab: it is picked up, and shown — where there is
        // anything to show. These tabs are shared ones, which is to say tmux
        // sessions, and `go_to_tab` attaches before it switches: on a machine
        // with no tmux the attach cannot succeed, and the documented outcome is
        // to stay put and say why rather than to open a blank tab. Both are the
        // gesture working; only one of them is reachable on a given runner.
        app.on_mouse(at(press, 12), &layout);
        assert_eq!(app.drag_tab, Some(1), "the press did not pick the tab up");
        match crate::tmux::available() {
            true => assert_eq!(app.tab, 1, "the press did not show the tab"),
            false => {
                assert_eq!(app.tab, 0, "a tab that cannot be attached moved the view");
                let status = app
                    .status
                    .as_ref()
                    .map(|(s, _)| s.clone())
                    .unwrap_or_default();
                assert!(status.contains("Could not open"), "silently: {status:?}");
            }
        }

        // Carried to the third slot, one tab at a time as the pointer crosses
        // them, with the view following it. The view is what is under test from
        // here, so it starts where the press would have put it — which on a
        // machine without tmux is somewhere the press could not reach.
        app.tab = 1;
        app.on_mouse(at(drag, 16), &layout);
        app.on_mouse(at(drag, 20), &layout);
        assert_eq!(titles(&app), ["b", "c", "a"]);
        assert_eq!(app.tab, 3);

        app.on_mouse(at(release, 20), &layout);
        assert_eq!(app.drag_tab, None);
        // A later drag with nothing picked up moves nothing.
        app.on_mouse(at(drag, 12), &layout);
        assert_eq!(titles(&app), ["b", "c", "a"]);

        // The dashboard is not draggable, and nothing can be dropped onto it.
        app.on_mouse(at(press, 4), &layout);
        assert_eq!(app.tab, 0);
        assert_eq!(app.drag_tab, None);
        app.on_mouse(at(press, 12), &layout);
        app.on_mouse(at(drag, 4), &layout);
        assert_eq!(titles(&app), ["b", "c", "a"]);
        assert_eq!(app.drag_tab, Some(1), "the tab is still in hand");
    }

    /// A paste on the dashboard is typing into whichever one-line box is open,
    /// and the line breaks in it must not go in: none of these inputs can show a
    /// second row or let you delete back onto one.
    #[test]
    fn a_paste_types_into_the_open_input_as_one_line() {
        let mut app = test_app();

        app.mode = Mode::Search;
        app.on_paste("fix the\nlogin bug\r\n");
        assert_eq!(app.search, "fix the login bug ");

        app.mode = Mode::SendKeys;
        app.send_input = "continue".into();
        app.on_paste(" and\ttidy\x07 up");
        assert_eq!(app.send_input, "continue and tidy up");

        // The cost floor is a number, so a paste is filtered the way typing one
        // is rather than flattened.
        app.mode = Mode::CostFilter;
        app.on_paste("$12.50 or so");
        assert_eq!(app.cost_input, "12.50");
    }

    /// The caps the typed path enforces are the paste's too, and a paste with
    /// nowhere to land does nothing rather than something surprising.
    #[test]
    fn a_paste_respects_the_caps_and_does_nothing_with_no_input_open() {
        let mut app = test_app();

        app.mode = Mode::SendKeys;
        app.send_input = "x".repeat(495);
        app.on_paste(&"y".repeat(50));
        assert_eq!(app.send_input.len(), 500);

        app.mode = Mode::CostFilter;
        app.on_paste("123456789012345");
        assert_eq!(app.cost_input, "123456789012");

        // A modal is on screen, so there is no box to type into — and a paste
        // must never stand in for the key one of these is waiting for.
        app.mode = Mode::DeleteConfirm;
        app.on_paste("y");
        assert_eq!(app.mode, Mode::DeleteConfirm);
        app.mode = Mode::List;
        app.on_paste("q");
        assert!(!app.should_quit);
    }

    /// Regression: a click on the launcher used to be answered twice — once by
    /// the modal and once by the dashboard drawn under it — so picking an agent
    /// also switched the bottom panel the modal happened to cover.
    #[test]
    fn a_click_on_a_modal_does_not_reach_what_it_covers() {
        use ratatui::layout::Rect;

        let mut app = test_app();
        app.mode = Mode::Launch;
        let layout = render::Layout {
            modal_rect: Some(Rect::new(10, 8, 20, 6)),
            launch_rows: vec![(9, 0), (10, 1)],
            // The panel tabs sit on a row the modal is covering.
            tab_row: 10,
            tab_spans: vec![(10, 20, 3)],
            ..Default::default()
        };
        let click = |col, row| crossterm::event::MouseEvent {
            kind: event::MouseEventKind::Down(event::MouseButton::Left),
            column: col,
            row,
            modifiers: crossterm::event::KeyModifiers::NONE,
        };

        app.on_mouse(click(15, 10), &layout);
        assert_eq!(app.bottom_tab, 0, "the click went through to the panels");
        assert_eq!(app.launch_cursor, 1, "the click did not pick a choice");
        assert_eq!(app.mode, Mode::Launch, "the launcher closed on a pick");

        // Off the modal dismisses it, and still does not reach the panels.
        app.needs_redraw = false;
        app.on_mouse(click(40, 10), &layout);
        assert_eq!(app.mode, Mode::List);
        assert_eq!(app.bottom_tab, 0);
        // Regression: dismissing it asked for no frame, so the modal stayed
        // drawn over a dashboard that was already taking the clicks again.
        assert!(app.needs_redraw, "the dismissal never repainted");
    }

    /// Regression: the guard above was keyed on "any mode but List", which took
    /// the mouse away from the search box too — an overlay a few lines tall over
    /// a table still being scrolled and clicked while the query is typed. Only a
    /// modal that recorded its rectangle can claim the mouse, because that
    /// rectangle is the only way to tell its clicks from the ones underneath.
    #[test]
    fn the_search_box_leaves_the_table_its_mouse() {
        let mut app = test_app();
        for id in ["a", "b", "c"] {
            app.sessions
                .push(crate::session::Session::new(Provider::Claude, id.into()));
        }
        app.visible = vec![Row::Session(0), Row::Session(1), Row::Session(2)];
        // What `draw_search` leaves behind: no rectangle, so no claim.
        let layout = render::Layout {
            rows_start: 7,
            rows_end: 12,
            // Below the table, or the wheel scrolls a panel instead of the list.
            bottom_start: 14,
            modal_rect: None,
            ..Default::default()
        };
        let at = |kind, row| crossterm::event::MouseEvent {
            kind,
            column: 5,
            row,
            modifiers: crossterm::event::KeyModifiers::NONE,
        };

        app.mode = Mode::Search;
        app.on_mouse(at(event::MouseEventKind::ScrollDown, 9), &layout);
        assert_eq!(app.selected, 1, "the wheel is dead while searching");
        app.on_mouse(
            at(event::MouseEventKind::Down(event::MouseButton::Left), 9),
            &layout,
        );
        assert_eq!(app.selected, 2, "a click cannot reach the row it landed on");
        assert_eq!(app.mode, Mode::Search, "the click closed the search box");
    }

    /// Regression: `launch_prompt` set the mode and nothing asked for a frame, so
    /// clicking the bar's new-tab button — the one advertisement the feature has
    /// — looked like a dead button until an unrelated event repainted.
    #[test]
    fn clicking_the_new_tab_button_paints_the_launcher() {
        let mut app = test_app();
        let layout = render::Layout {
            workspace_new: Some((12, 23)),
            ..Default::default()
        };
        app.needs_redraw = false;
        app.on_mouse(
            crossterm::event::MouseEvent {
                kind: event::MouseEventKind::Down(event::MouseButton::Left),
                column: 15,
                row: 0,
                modifiers: crossterm::event::KeyModifiers::NONE,
            },
            &layout,
        );
        // The launcher opens only where there is something to launch, which on a
        // machine with no agent and no $SHELL there is not — but either way the
        // click has to have asked for the frame that says so.
        assert!(app.needs_redraw, "the click asked for no frame");
        assert!(matches!(app.mode, Mode::Launch | Mode::List));
    }

    /// Closing is a kill now, but only of an agent that is cctop's to kill. On a
    /// pane opened with `a` — a window onto an agent cctop never started — there
    /// is nothing to stop, so the window closes and the status says the agent
    /// was left alone rather than claiming a kill that never happened.
    #[cfg(target_os = "linux")]
    #[test]
    fn closing_a_borrowed_pane_says_the_agent_was_left_running() {
        let (mut child, pid) = crate::shim::test_session(&["sh", "-c", "sleep 30"], (80, 24));
        let pane = tabs::Pane::view_of(pid, "agent".into()).expect("attach");
        assert!(
            !pane.owns_agent(),
            "a borrowed pane claimed the agent as cctop's"
        );

        let mut app = test_app();
        app.tabs.push(tabs::Tab::new(pane));
        app.tab = 1;
        app.kill_pane();

        // The window is gone, the agent is not, and the status says which.
        assert!(app.tabs.is_empty(), "the view outlived its close");
        let (status, _) = app.status.clone().expect("nothing was said");
        assert!(status.contains("not cctop's to stop"), "{status}");
        assert!(
            child.try_wait().ok().flatten().is_none(),
            "closing a borrowed view stopped somebody else's agent"
        );

        let _ = child.kill();
        let _ = child.wait();
        let _ = crate::shim::socket_path(pid).map(std::fs::remove_file);
    }

    /// A tab standing for another cctop's agent has no pane here, so every key
    /// that works through the focused pane does nothing on it. Closing has to
    /// keep working anyway: the tab is the only handle on screen for that agent,
    /// and a `w` that silently did nothing would read as a stuck tab.
    #[test]
    fn a_shared_tab_can_be_closed_without_a_pane_to_close() {
        let mut app = test_app();
        app.tabs.push(tabs::Tab::shared(&crate::tmux::Running {
            name: "cctop-claude-nosuchsession".into(),
            pid: Some(4321),
            cwd: None,
            attached: false,
            activity: None,
            label: Some("claude · Improve super cctop".into()),
        }));
        app.tab = 1;
        // Nothing has emptied it: a tab with no pane is still a tab, or every
        // cctop would drop the ones it is not looking at.
        app.drop_empty_tabs();
        assert_eq!(app.tabs.len(), 1);
        assert_eq!(app.tabs[0].title(), "claude · Improve super cctop");

        app.close_pane();
        assert!(
            app.tabs.is_empty(),
            "closing a shared tab left it in the bar"
        );
        // And the view followed it back rather than pointing past the end.
        assert_eq!(app.tab, 0);
        let (status, _) = app.status.clone().expect("nothing was said");
        assert!(status.contains("Improve super cctop"), "{status}");
    }

    /// Regression: the "already open" guard asked only about `tmux`, which is
    /// `None` on every pane when tmux is not installed — so `R` on a session
    /// already resumed in a tab started a second agent on the one transcript,
    /// and being stopped, it did so without even the confirmation.
    #[cfg(target_os = "linux")]
    #[test]
    fn resuming_a_session_already_in_a_tab_goes_to_that_tab() {
        let (mut child, pid) = crate::shim::test_session(&["sh", "-c", "sleep 30"], (80, 24));
        let mut pane = tabs::Pane::view_of(pid, "claude".into()).expect("attach");
        // What a resumed tab records regardless of who carries the agent. The
        // pane has no tmux, standing in for a machine without it.
        pane.resumed = Some(crate::tmux::name_for_session("claude", "abc"));
        assert!(pane.tmux.is_none());

        let mut app = test_app();
        app.sessions
            .push(crate::session::Session::new(Provider::Claude, "abc".into()));
        app.visible = vec![Row::Session(0)];
        app.selected = 0;
        app.tabs.push(tabs::Tab::new(pane));
        app.tab = 0;

        app.resume_now();

        assert_eq!(
            app.tabs.len(),
            1,
            "a second agent was put on one transcript"
        );
        assert_eq!(app.tab, 1, "the tab already holding it was not shown");
        let (status, _) = app.status.clone().expect("nothing was said");
        assert!(status.contains("Already open"), "{status}");

        let _ = child.kill();
        let _ = child.wait();
        let _ = crate::shim::socket_path(pid).map(std::fs::remove_file);
    }

    /// Regression: the launcher sized itself to its list and let `centered` clamp
    /// the result, so on a short terminal the rows past the bottom were dropped —
    /// and once the cursor walked into them, nothing on screen said what Enter
    /// was about to start.
    #[test]
    fn the_launcher_keeps_its_cursor_on_screen() {
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        let mut app = test_app();
        // More choices than a short terminal can hold at once.
        app.launch_offer = (0..20)
            .map(|i| tabs::Choice::Start(vec![format!("agent-{i}")]))
            .collect();
        app.mode = Mode::Launch;
        let (cols, rows) = (80u16, 14u16);
        let mut terminal = Terminal::new(TestBackend::new(cols, rows)).expect("backend");

        // Every choice, including the ones far past the bottom of the window.
        for cursor in 0..app.launch_offer.len() {
            app.launch_cursor = cursor;
            let mut layout = render::Layout::default();
            terminal
                .draw(|frame| layout = render::draw(frame, &mut app))
                .expect("draw");

            let row = layout
                .launch_rows
                .iter()
                .find(|(_, i)| *i == cursor)
                .map(|(row, _)| *row);
            let row = row.unwrap_or_else(|| panic!("choice {cursor} was not drawn"));
            assert!(row < rows, "choice {cursor} drawn off screen at row {row}");

            // Drawn, and drawn as the selection: the highlight is the only thing
            // saying which of twenty agents Enter starts.
            let buffer = terminal.backend().buffer().clone();
            let label = format!("agent-{cursor}");
            let line: String = (0..cols).map(|x| buffer[(x, row)].symbol()).collect();
            assert!(
                line.contains(&label),
                "row {row} is not choice {cursor}: {line:?}"
            );

            // And what is under the list stays under it, never scrolled away.
            let text: String = (0..rows)
                .map(|y| {
                    (0..cols)
                        .map(|x| buffer[(x, y)].symbol())
                        .collect::<String>()
                })
                .collect();
            assert!(text.contains("Enter start"), "the keys scrolled off");
            assert!(
                text.contains("this directory") || text.contains(" in "),
                "where it would run scrolled off"
            );
        }
    }

    /// The three ways the ownership decision can go, since only one of them is
    /// new: tmux present is unchanged, tmux absent and uninstallable is the old
    /// silent fallback, and only tmux absent but installable stops to ask.
    #[test]
    fn ownership_asks_only_when_tmux_could_actually_be_installed() {
        let mut app = test_app();
        let own = app.own_preferring_tmux(Deferred::Launch, || "cctop-x".into());
        match (crate::tmux::available(), crate::tmux::installer()) {
            (true, _) => assert!(matches!(own, Some(tabs::Own::Tmux(_)))),
            (false, Some(_)) => {
                assert!(own.is_none(), "the launch waits for the answer");
                assert_eq!(app.mode, Mode::TmuxInstall);
            }
            (false, None) => assert!(matches!(own, Some(tabs::Own::Cctop))),
        }
    }

    /// One "no" holds for the run. Asking again on the next tab would make
    /// declining cost more than accepting, which is not offering a choice.
    #[test]
    fn a_declined_offer_is_not_made_again() {
        let mut app = test_app();
        app.tmux_declined = true;
        let own = app.own_preferring_tmux(Deferred::Launch, || "cctop-x".into());
        assert!(own.is_some(), "the launch goes ahead without asking");
        assert_ne!(app.mode, Mode::TmuxInstall);
    }

    /// Declining still starts the agent — the offer interrupted a launch, and
    /// saying no to tmux is not saying no to the agent.
    #[test]
    fn declining_the_offer_releases_the_launch() {
        let mut app = test_app();
        app.mode = Mode::TmuxInstall;
        app.tmux_install = Some(crate::tmux::Install {
            manager: "apt",
            argv: vec!["sh".into(), "-c".into(), "apt-get install -y tmux".into()],
        });
        app.tmux_deferred = Some(Deferred::Launch);

        app.tmux_install_answer(false);

        assert!(app.tmux_declined);
        assert!(app.tmux_install.is_none());
        assert!(
            app.tmux_deferred.is_none(),
            "the launch was run, not dropped"
        );
        assert_eq!(app.mode, Mode::List);
    }

    /// The failure that would otherwise be invisible: an install that ends
    /// without tmux — it errored, or the user closed the tab — leaves a launch
    /// waiting on a pane that no longer exists.
    #[test]
    fn an_install_that_ends_without_tmux_releases_the_launch() {
        let mut app = test_app();
        // A pid no pane has, standing in for the install tab having gone.
        app.tmux_installing = Some(u32::MAX);
        app.tmux_deferred = Some(Deferred::Launch);

        app.poll_tmux_install();

        assert!(app.tmux_installing.is_none());
        assert!(app.tmux_deferred.is_none());
    }

    /// Regression: these tests once read the developer's real prefs file, so a
    /// persisted `live_only` or age filter silently failed unrelated assertions.
    #[test]
    fn test_app_starts_from_default_prefs() {
        let app = test_app();
        assert!(!app.live_only);
        assert!(app.age_filter.is_none());
        assert!(app.search.is_empty());
        assert_eq!(app.sort_col, ColumnId::Last);
    }

    /// The mode is reported by a live agent but drawn on a row rebuilt by every
    /// walk, so the two have to survive arriving in either order.
    #[test]
    fn the_permission_mode_survives_the_rows_being_rebuilt() {
        let reported = |mode: Option<crate::hook::Permission>| crate::hook::Event {
            session_id: "a".into(),
            reported: crate::hook::Reported {
                signal: crate::hook::Signal::Busy,
                cwd: "/w/proj".into(),
                permission: mode,
            },
            finished_agent: None,
        };
        let mut app = test_app();

        // Reported before the row exists, which is the ordinary order: a
        // `SessionStart` beats the walk that discovers its transcript.
        app.apply_hooks(vec![reported(Some(crate::hook::Permission::Bypass))]);
        app.sessions = vec![session("a", true, "proj")];
        assert_eq!(app.sessions[0].permission, None, "not stamped yet");

        app.apply_permissions();
        assert_eq!(
            app.sessions[0].permission,
            Some(crate::hook::Permission::Bypass),
            "a row discovered after the report still picks it up"
        );

        // An event that says nothing about the mode must not erase it: the
        // setting has not changed just because one event was quiet.
        app.apply_hooks(vec![reported(None)]);
        assert_eq!(
            app.sessions[0].permission,
            Some(crate::hook::Permission::Bypass)
        );

        // A real change is followed.
        app.apply_hooks(vec![reported(Some(crate::hook::Permission::Plan))]);
        assert_eq!(
            app.sessions[0].permission,
            Some(crate::hook::Permission::Plan)
        );
    }

    /// A reported state is kept until the session says it is over, and the
    /// events that change *which sessions exist* ask for a rescan while the
    /// ones that only change a state do not.
    #[test]
    fn a_reported_state_is_kept_until_the_session_ends() {
        let event = |id: &str, signal: crate::hook::Signal| crate::hook::Event {
            session_id: id.into(),
            reported: crate::hook::Reported {
                signal,
                cwd: "/w/proj".into(),
                permission: None,
            },
            // This test is about the session's own state; subagent events are
            // covered where subagents are.
            finished_agent: None,
        };
        let mut app = test_app();

        // Nothing arriving is not "nothing is happening": an absent entry means
        // fall back to the transcript, so it must stay absent.
        assert_eq!(app.apply_hooks(Vec::new()), (false, false));
        assert!(app.hooked_signal("a").is_none());

        // A start is a row to go and find now.
        assert_eq!(
            app.apply_hooks(vec![event("a", crate::hook::Signal::Started)]),
            (true, true)
        );
        // Ordinary state changes are not worth a rescan of the disk.
        assert_eq!(
            app.apply_hooks(vec![
                event("a", crate::hook::Signal::Busy),
                event("a", crate::hook::Signal::Idle),
            ]),
            (true, false)
        );
        assert_eq!(app.hooked_signal("a"), Some(crate::hook::Signal::Idle));
        assert_eq!(app.reporting(), vec![("proj".to_string(), "idle")]);

        // And an ended session is forgotten rather than left claiming its last
        // state forever — which is also a rescan, since the row is going.
        assert_eq!(
            app.apply_hooks(vec![event("a", crate::hook::Signal::Ended)]),
            (true, true)
        );
        assert!(app.hooked_signal("a").is_none());
        assert!(app.reporting().is_empty());
    }

    /// Gemini CLI is the one harness whose rows are not named after the id it
    /// reports: a chat file is named after the first eight characters of the
    /// session id, and that filename is the row's identity because resuming
    /// reuses the id across disjoint files. Without the loose match every Gemini
    /// event would land on no row at all.
    #[test]
    fn a_gemini_event_finds_the_chat_file_it_belongs_to() {
        let mut app = test_app();
        app.apply_hooks(vec![crate::hook::Event {
            session_id: "79709c93-1111-4111-8111-111111111111".into(),
            reported: crate::hook::Reported {
                signal: crate::hook::Signal::Idle,
                cwd: "/w/proj".into(),
                permission: None,
            },
            finished_agent: None,
        }]);

        assert_eq!(
            app.hooked_signal("session-2026-05-14T17-34-79709c93"),
            Some(crate::hook::Signal::Idle)
        );
        // And only that one: a stem whose tail belongs to another session, or an
        // id that is not shaped like Gemini's at all, must not borrow it.
        assert!(
            app.hooked_signal("session-2026-05-14T17-34-deadbeef")
                .is_none()
        );
        assert!(app.hooked_signal("79709c93").is_none());
        assert_eq!(
            gemini_id_tail("session-2026-05-14T17-34-79709c93"),
            Some("79709c93")
        );
        assert_eq!(gemini_id_tail("019fda22-5315-7580-84de-033e4f6835b5"), None);
    }

    /// Answering a prompt in a pane stops the tab asking about it, without
    /// waiting for a hook that only fires once the unblocked tool has finished.
    #[test]
    fn typing_into_a_pane_settles_the_question_it_answers() {
        let mut app = test_app();
        let mut session = session("a", true, "proj");
        session.process.as_mut().unwrap().process_list = vec![crate::proc::ProcEntry {
            pid: 7,
            is_root: true,
            ghost: false,
            cpu: 0.0,
            memory: 0,
            args: String::new(),
        }];
        app.sessions = vec![session];

        // An agent with no hooks has only its transcript to speak for it, and
        // fabricating a report here would shadow it for the rest of the session.
        app.mark_answered(7);
        assert!(app.hooked_signal("a").is_none());

        app.apply_hooks(vec![crate::hook::Event {
            session_id: "a".into(),
            reported: crate::hook::Reported {
                signal: crate::hook::Signal::NeedsInput,
                cwd: "/w/proj".into(),
                permission: None,
            },
            finished_agent: None,
        }]);
        assert_eq!(
            app.hooked_signal("a"),
            Some(crate::hook::Signal::NeedsInput)
        );

        // The keystroke is the answer, so the agent is working again.
        app.mark_answered(7);
        assert_eq!(app.hooked_signal("a"), Some(crate::hook::Signal::Busy));

        // A different agent's keys settle nothing here.
        app.apply_hooks(vec![crate::hook::Event {
            session_id: "a".into(),
            reported: crate::hook::Reported {
                signal: crate::hook::Signal::NeedsInput,
                cwd: "/w/proj".into(),
                permission: None,
            },
            finished_agent: None,
        }]);
        app.mark_answered(8);
        assert_eq!(
            app.hooked_signal("a"),
            Some(crate::hook::Signal::NeedsInput)
        );
    }

    fn session(id: &str, running: bool, label: &str) -> Session {
        let mut s = Session::new(Provider::Claude, id.into());
        s.label_source = label.into();
        s.last_active = chrono::Utc::now().to_rfc3339();
        s.started_at = s.last_active.clone();
        if running {
            s.process = Some(crate::proc::ProcInfo::default());
        }
        s
    }

    /// Two live agents in one checkout, both having written the same file —
    /// the arrangement the whole warning exists for.
    #[test]
    fn a_contested_file_reaches_the_footer_and_the_info_panel() {
        let repo = std::env::temp_dir().join(format!("cctop-ui-clash-{}", std::process::id()));
        std::fs::create_dir_all(repo.join(".git")).expect("checkout");
        let dir = repo.to_string_lossy().into_owned();
        let contested = crate::collide::normalise("src/ui/mod.rs", &dir);

        let mut app = test_app();
        app.sessions = vec![session("a", true, &dir), session("b", true, &dir)];
        for s in app.sessions.iter_mut() {
            s.recent_writes = vec![contested.clone()];
        }
        app.collisions = crate::collide::apply(&mut app.sessions);

        // On the rows, so the column can colour and sort by it…
        for s in &app.sessions {
            assert_eq!(s.conflict, Some(crate::collide::Overlap::File));
        }
        // …and in the footer, which names the file rather than a count.
        let footer = app.conflict_footer().expect("a warning");
        assert!(footer.contains("ui/mod.rs"), "{footer}");
        assert!(footer.contains("2 agents"), "{footer}");

        // The panel names the peer, which is the part that says what to do.
        let clash = app.clash_of(&app.sessions[0]).expect("a clash");
        assert_eq!(clash.peers, vec![app.sessions[1].display_label()]);
        assert_eq!(clash.files, vec![contested]);

        // A repository shared without a shared file is the quieter finding, and
        // deliberately does not reach the footer.
        app.sessions[1].recent_writes = vec![crate::collide::normalise("other.rs", &dir)];
        app.collisions = crate::collide::apply(&mut app.sessions);
        assert_eq!(
            app.sessions[0].conflict,
            Some(crate::collide::Overlap::Directory)
        );
        assert!(app.conflict_footer().is_none());

        std::fs::remove_dir_all(&repo).ok();
    }

    /// A remote row survives the walk that replaces the table, counts towards
    /// the totals, and refuses every key that would reach into this machine.
    #[test]
    fn remote_rows_outlive_a_walk_and_stay_read_only() {
        let mut app = test_app();
        app.sessions = vec![session("local", true, "/here")];

        let mut away = session("away", true, "/srv/work");
        away.remote = Some(crate::session::Remote {
            host: "box".into(),
            branch: Some("main".into()),
        });
        away.total_cost = Some(3.0);
        app.remotes.insert("box".into(), vec![away]);
        app.merge_remotes();
        assert_eq!(app.sessions.len(), 2);
        assert!(
            (app.stats.spend_claude - 3.0).abs() < 1e-9,
            "totals span hosts"
        );

        // A full walk replaces the table with this machine's rows only. The
        // remote ones have to come back, or a host would blink out every
        // refresh.
        app.sessions = vec![session("local", true, "/here")];
        app.merge_remotes();
        assert_eq!(app.sessions.len(), 2);
        assert_eq!(
            app.sessions.iter().filter(|s| s.remote.is_some()).count(),
            1
        );

        // And nothing here may act on it.
        let remote = app
            .sessions
            .iter()
            .find(|s| s.remote.is_some())
            .expect("the remote row");
        let why = App::remote_refusal(remote).expect("a refusal");
        assert!(why.contains("box"), "the refusal has to name the machine");
        assert!(App::remote_refusal(&app.sessions[0]).is_none());

        // The branch comes from the far side rather than from this filesystem,
        // where the same path may well exist and mean something else.
        assert_eq!(
            crate::ui::columns::branch_of(remote).as_deref(),
            Some("main")
        );

        // A host that stops answering keeps its rows and says so.
        app.remote_errors
            .insert("box".into(), "Permission denied".into());
        let footer = app.remote_footer().expect("a warning");
        assert!(footer.contains("box"), "{footer}");
        assert!(footer.contains("Permission denied"), "{footer}");
    }

    /// With no host configured the column is one repeated word down every row,
    /// so it is hidden — through the user's own mechanism, so the two cannot
    /// disagree about what is on screen.
    #[test]
    fn the_host_column_stays_off_a_single_machine() {
        let ids = |hidden: &[ColumnId]| -> Vec<ColumnId> {
            columns::visible_columns(300, hidden)
                .iter()
                .map(|c| c.id)
                .collect()
        };
        assert!(ids(&[]).contains(&ColumnId::Host));
        assert!(!ids(&[ColumnId::Host]).contains(&ColumnId::Host));
    }

    fn with_subagents(id: &str, names: &[&str]) -> Session {
        let mut s = session(id, true, id);
        s.subagents = names
            .iter()
            .map(|n| crate::session::Subagent {
                agent_id: format!("agent-{n}"),
                agent_type: "general-purpose".into(),
                description: (*n).into(),
                model: "claude-opus-5".into(),
                started_at: None,
                last_active: None,
                duration_ms: 0,
                status: crate::session::SubagentStatus::Running,
                cost: 0.0,
                tool_count: 0,
                tool_use_id: None,
                context: None,
                ghost: false,
            })
            .collect();
        s
    }

    /// Children belong under the parent they ran for. Sorting them as peers
    /// would scatter one session's subagents down a table ordered by cost or
    /// age, which is the one arrangement that makes the tree meaningless.
    #[test]
    fn expanded_subagents_sit_directly_under_their_parent() {
        let mut app = test_app();
        app.sessions = vec![
            with_subagents("a", &["one", "two"]),
            session("b", true, "b"),
        ];
        app.refilter();
        assert_eq!(app.visible.len(), 2, "collapsed: one row per session");

        app.expanded.insert(app.sessions[0].key());
        app.refilter();

        // Asserted as a position relative to the parent rather than as a fixed
        // list: where the parent lands is the sort's business, and these two
        // sessions are equally recent.
        let at = app
            .visible
            .iter()
            .position(|&r| r == Row::Session(0))
            .expect("parent row");
        assert_eq!(app.visible.len(), 4);
        assert_eq!(
            &app.visible[at..at + 3],
            &[
                Row::Session(0),
                Row::Subagent {
                    parent: 0,
                    index: 0
                },
                Row::Subagent {
                    parent: 0,
                    index: 1
                },
            ]
        );
    }

    /// The cursor is anchored on what it was pointing at, and a child is only
    /// identified by its parent *and* its own id — anchoring on the session key
    /// alone would snap the cursor back to the parent on every refresh, two
    /// times a second, while the user was reading a child row.
    #[test]
    fn the_cursor_stays_on_a_child_row_across_a_refresh() {
        let mut app = test_app();
        app.sessions = vec![with_subagents("a", &["one", "two"])];
        app.expanded.insert(app.sessions[0].key());
        app.refilter();
        app.selected = 2;

        app.refilter();

        assert_eq!(
            app.visible[app.selected],
            Row::Subagent {
                parent: 0,
                index: 1
            }
        );
        assert_eq!(
            app.selected_subagent().map(|s| s.description.clone()),
            Some("two".into())
        );
    }

    /// A child row resolves to its parent for anything addressed to a session,
    /// so every existing action keeps working — but the destructive ones have to
    /// know the difference, because the cursor is on a subagent and the session
    /// they would signal is not what the user pointed at.
    #[test]
    fn a_child_row_owns_its_parent_but_is_not_it() {
        let mut app = test_app();
        app.sessions = vec![with_subagents("a", &["one"])];
        app.expanded.insert(app.sessions[0].key());
        app.refilter();

        app.selected = 0;
        assert!(!app.on_subagent());
        assert!(app.selected_subagent().is_none());

        app.selected = 1;
        assert!(app.on_subagent());
        assert_eq!(
            app.selected_session().map(|s| s.session_id.clone()),
            Some("a".into()),
            "a child still resolves to the session that owns it"
        );
        assert!(app.selected_subagent().is_some());
    }

    /// Collapsing from a child row must leave the cursor somewhere that still
    /// exists; the row it was on is about to be removed.
    #[test]
    fn collapsing_from_a_child_lands_the_cursor_on_its_parent() {
        let mut app = test_app();
        app.sessions = vec![with_subagents("a", &["one", "two"])];
        app.expanded.insert(app.sessions[0].key());
        app.refilter();
        app.selected = 1;

        app.toggle_expanded();

        assert_eq!(app.visible.len(), 1);
        assert_eq!(app.visible[app.selected], Row::Session(0));
        assert!(app.expanded.is_empty());
    }

    /// A background subagent is acknowledged by its parent the moment it
    /// starts, so the transcript says "finished" while it is still working. The
    /// hook is the agent reporting for itself, and it has to win — this is the
    /// difference between a child row that tracks a live agent and one that
    /// reads `done` for the whole run.
    #[test]
    fn a_hooks_word_retires_a_subagent_the_transcript_still_calls_running() {
        let mut app = test_app();
        app.sessions = vec![with_subagents("a", &["one", "two"])];
        assert!(
            app.sessions[0]
                .subagents
                .iter()
                .all(|s| s.status == crate::session::SubagentStatus::Running)
        );

        // The hook names the bare id; the transcript is stored as `agent-<id>`.
        app.finished_agents.insert("one".into());
        app.apply_finished_agents();

        let status = |i: usize| app.sessions[0].subagents[i].status;
        assert_eq!(status(0), crate::session::SubagentStatus::Done);
        assert_eq!(
            status(1),
            crate::session::SubagentStatus::Running,
            "only the subagent named may be retired"
        );
    }

    /// A session with nothing to show must not swallow the key and leave the
    /// user pressing it at a row that never opens.
    #[test]
    fn expanding_a_session_without_subagents_says_so() {
        let mut app = test_app();
        app.sessions = vec![session("a", true, "a")];
        app.refilter();

        app.toggle_expanded();

        assert!(app.expanded.is_empty());
        assert!(app.status.is_some(), "the refusal has to be visible");
    }

    #[test]
    fn live_filter_hides_stopped_sessions() {
        let mut app = test_app();
        app.sessions = vec![session("a", true, "x"), session("b", false, "y")];
        app.live_only = true;
        app.refilter();
        assert_eq!(app.visible.len(), 1);
        assert_eq!(app.sessions[app.visible[0].session()].session_id, "a");
    }

    #[test]
    fn live_filter_includes_transcript_inferred_cursor_session() {
        let mut app = test_app();
        let mut cursor = Session::new(Provider::Cursor, "cursor".into());
        cursor.started_at = chrono::Utc::now().to_rfc3339();
        cursor.last_active = cursor.started_at.clone();
        cursor.inferred_running = true;
        app.sessions = vec![cursor];
        app.live_only = true;
        app.refilter();
        assert_eq!(app.visible.len(), 1);
        assert!(app.sessions[app.visible[0].session()].is_running());
        assert!(app.sessions[app.visible[0].session()].process.is_none());
    }

    /// The launcher's directory is a field, not a caption. A `claude` opened on
    /// the wrong project reads its way into the wrong repository before anyone
    /// notices, and until now the only way to change it was to restart cctop
    /// somewhere else.
    #[test]
    fn the_launchers_directory_can_be_typed_and_is_checked_before_it_is_taken() {
        let dir = tempfile::tempdir().expect("tempdir");
        let mut app = App::new(Plan::Retail, channel().0);
        app.launch_cwd = Some(dir.path().to_path_buf());

        // Opens prefilled with what it would have used, so nothing looks lost.
        app.edit_launch_cwd();
        assert_eq!(app.mode, Mode::LaunchCwd);
        assert_eq!(
            app.launch_cwd_input,
            crate::util::tildify(&dir.path().to_string_lossy())
        );

        // A directory that is not one is refused where it was typed, and the
        // field stays open. Failing at launch instead would report it from
        // inside the shim, after the launcher had gone.
        app.launch_cwd_input = dir.path().join("nope").to_string_lossy().into_owned();
        app.accept_launch_cwd();
        assert!(app.launch_cwd_bad);
        assert_eq!(app.mode, Mode::LaunchCwd, "the field stays open");
        assert_eq!(app.launch_cwd.as_deref(), Some(dir.path()), "unchanged");

        // A real one is taken.
        let sub = dir.path().join("work");
        std::fs::create_dir(&sub).expect("mkdir");
        app.launch_cwd_input = sub.to_string_lossy().into_owned();
        app.accept_launch_cwd();
        assert!(!app.launch_cwd_bad);
        assert_eq!(app.mode, Mode::Launch);
        assert_eq!(app.launch_cwd.as_deref(), Some(sub.as_path()));

        // Empty means where cctop was started, which is what the footer calls
        // "this directory" — not an error, and not the previous value.
        app.edit_launch_cwd();
        app.launch_cwd_input = "   ".into();
        app.accept_launch_cwd();
        assert_eq!(app.launch_cwd, None);
        assert_eq!(app.mode, Mode::Launch);
    }

    /// Esc has to leave the launch as it was found, or it becomes a way to lose
    /// the setting you opened the field to change.
    #[test]
    fn cancelling_the_directory_field_keeps_the_old_one() {
        let dir = tempfile::tempdir().expect("tempdir");
        let mut app = App::new(Plan::Retail, channel().0);
        app.launch_cwd = Some(dir.path().to_path_buf());
        app.edit_launch_cwd();
        app.launch_cwd_input = "/somewhere/else".into();
        app.on_key(key(KeyCode::Esc));
        assert_eq!(app.mode, Mode::Launch);
        assert_eq!(app.launch_cwd.as_deref(), Some(dir.path()));
    }

    /// The menu and the keyboard must never disagree about what is possible.
    /// Both ask the same predicates; this pins that they still do.
    #[test]
    fn the_menu_refuses_a_remote_row_the_way_the_keys_do() {
        let mut app = App::new(Plan::Retail, channel().0);
        let mut s = session("a", true, "/repo");
        s.remote = Some(crate::session::Remote {
            host: "devbox".into(),
            branch: None,
        });
        app.sessions = vec![s];
        app.refilter();
        app.selected = 0;

        let items = menu::items(&app);
        assert!(!items.is_empty(), "a selected row has a menu");

        // Everything that reaches into this filesystem is refused, and every
        // refusal names the host — the same answer pressing the key gives.
        for item in &items {
            match item.action {
                menu::Action::Expand | menu::Action::Mark => {
                    assert!(item.enabled(), "{} works on a remote row", item.label);
                }
                _ => {
                    let why = item.blocked.as_deref().unwrap_or("");
                    assert!(
                        why.contains("devbox"),
                        "{} must name the host, said {why:?}",
                        item.label
                    );
                }
            }
        }
        // And the cursor never rests on one of the refusals.
        assert!(items[menu::first_enabled(&items)].enabled());
    }

    #[test]
    fn opening_the_menu_needs_a_row_and_lands_on_something_runnable() {
        let mut app = App::new(Plan::Retail, channel().0);
        // No rows: Enter must not open an empty box.
        app.open_row_menu();
        assert_eq!(app.mode, Mode::List);

        app.sessions = vec![session("a", false, "/repo")];
        app.refilter();
        app.selected = 0;
        app.open_row_menu();
        assert_eq!(app.mode, Mode::RowMenu);
        let items = menu::items(&app);
        assert!(items[app.menu_cursor].enabled());
    }

    #[test]
    fn session_root_pid_excludes_ghost_and_child_processes() {
        let mut session = session("a", true, "x");
        session.process.as_mut().unwrap().process_list = vec![
            crate::proc::ProcEntry {
                pid: 1,
                is_root: true,
                ghost: true,
                cpu: 0.0,
                memory: 0,
                args: String::new(),
            },
            crate::proc::ProcEntry {
                pid: 2,
                is_root: false,
                ghost: false,
                cpu: 0.0,
                memory: 0,
                args: String::new(),
            },
            crate::proc::ProcEntry {
                pid: 3,
                is_root: true,
                ghost: false,
                cpu: 0.0,
                memory: 0,
                args: String::new(),
            },
        ];

        assert_eq!(session_root_pid(&session), Some(3));
    }

    #[test]
    fn runtime_tabs_are_unavailable_for_stopped_sessions() {
        let mut app = test_app();
        app.sessions = vec![session("stopped", false, "x")];
        app.refilter();
        assert!(!app.tab_available(1));
        assert!(!app.tab_available(2));

        app.bottom_tab = 0;
        app.cycle_tab(1);
        assert_eq!(app.bottom_tab, 3);
    }

    #[test]
    fn selecting_stopped_session_leaves_runtime_tab() {
        let mut app = test_app();
        app.sessions = vec![
            session("running", true, "x"),
            session("stopped", false, "y"),
        ];
        app.visible = vec![Row::Session(0), Row::Session(1)];
        app.bottom_tab = 1;
        app.move_selection(1);
        assert_eq!(app.bottom_tab, 0);
    }

    #[test]
    fn search_matches_label_and_id_case_insensitively() {
        let mut app = test_app();
        app.sessions = vec![
            session("aaa", false, "/home/x/alpha"),
            session("bbb", false, "/home/x/beta"),
        ];
        app.search = "alpha".into();
        app.refilter();
        assert_eq!(app.visible.len(), 1);

        app.search = "BBB".into();
        app.refilter();
        assert_eq!(app.visible.len(), 1);
        assert_eq!(app.sessions[app.visible[0].session()].session_id, "bbb");
    }

    /// The table abbreviates the working directory to fit its column, so the
    /// filter has to match the full path — otherwise the directory someone
    /// types is one the row is not admitting to.
    #[test]
    fn search_matches_the_full_working_directory() {
        let mut app = test_app();
        let mut deep = session("aaa", false, "/home/x/work/api/services/billing");
        // What the table actually shows for that row.
        deep.abbrev_label = "…/billing".into();
        app.sessions = vec![deep, session("bbb", false, "/home/x/other")];

        app.search = "work/api".into();
        app.refilter();
        assert_eq!(app.visible.len(), 1);
        assert_eq!(app.sessions[app.visible[0].session()].session_id, "aaa");
    }

    /// Content hits widen the filter, and only for the query they were found
    /// for: a scan that lands after the user has typed another character must
    /// not put its rows back on screen.
    #[test]
    fn transcript_hits_widen_the_filter_for_their_own_query_only() {
        let mut app = test_app();
        app.sessions = vec![
            session("aaa", false, "/home/x/alpha"),
            session("bbb", false, "/home/x/beta"),
        ];
        let hit = |key: &str| HashMap::from([(key.to_string(), "…flywheel…".to_string())]);

        // No content search: a word only the transcript knows finds nothing.
        app.search = "flywheel".into();
        app.refilter();
        assert!(app.visible.is_empty());

        // With one, the session whose transcript matched joins the metadata
        // matches rather than replacing them.
        app.search_content = true;
        app.scanned("flywheel".into(), hit("claude:bbb"));
        assert_eq!(app.visible.len(), 1);
        assert_eq!(app.sessions[app.visible[0].session()].session_id, "bbb");

        app.search = "alpha".into();
        app.scanned("alpha".into(), hit("claude:bbb"));
        assert_eq!(
            app.visible.len(),
            2,
            "metadata and content matches, not one"
        );

        // Hits belonging to a query that has since been extended are ignored.
        app.search = "alphabet".into();
        app.refilter();
        assert!(app.visible.is_empty());
        assert!(app.selected_snippet().is_none());
    }

    /// Turning content search off has to take its results with it, or the rows
    /// it found stay on screen with nothing matching them.
    #[test]
    fn leaving_content_search_drops_its_rows() {
        let mut app = test_app();
        app.sessions = vec![session("aaa", false, "/home/x/alpha")];
        app.search = "flywheel".into();
        app.search_content = true;
        app.scanned(
            "flywheel".into(),
            HashMap::from([("claude:aaa".into(), "…flywheel…".into())]),
        );
        assert_eq!(app.visible.len(), 1);
        assert_eq!(app.selected_snippet(), Some("…flywheel…"));

        app.toggle_content_search();
        assert!(app.visible.is_empty());
        assert!(app.selected_snippet().is_none());
    }

    /// A scan is worth its cost only once there is a word to look for, and only
    /// for a query that isn't already answered.
    #[test]
    fn a_scan_waits_for_a_word_and_for_the_typing_to_settle() {
        let mut app = test_app();
        app.sessions = vec![session("aaa", false, "/home/x/alpha")];
        app.search_content = true;

        // Too short to be worth reading every transcript for.
        app.search = "fl".into();
        app.search_edited();
        app.scan_typed_at = None;
        app.tick_scan();
        assert!(!app.scanning);

        // Long enough, but the user is still typing.
        app.search = "flywheel".into();
        app.search_edited();
        app.tick_scan();
        assert!(!app.scanning, "fired before the debounce elapsed");

        // Settled.
        app.scan_typed_at = Some(Instant::now() - SCAN_DEBOUNCE);
        app.tick_scan();
        assert!(app.scanning);

        // And the answer to a query already scanned for is not scanned again.
        app.scanned("flywheel".into(), HashMap::new());
        app.tick_scan();
        assert!(!app.scanning);
    }

    /// ↑ walks back through past queries and ↓ returns, ending on whatever was
    /// half-typed when the walk began.
    #[test]
    fn the_query_history_walks_both_ways() {
        let mut app = test_app();
        app.search_history = vec!["newest".into(), "older".into()];

        app.search = "half-typ".into();
        app.history_step(1);
        assert_eq!(app.search, "newest");
        app.history_step(1);
        assert_eq!(app.search, "older");
        // The end of the history is a floor, not a wrap.
        app.history_step(1);
        assert_eq!(app.search, "older");

        app.history_step(-1);
        assert_eq!(app.search, "newest");
        app.history_step(-1);
        assert_eq!(app.search, "half-typ");
        // Nothing older to come back from any more.
        app.history_step(-1);
        assert_eq!(app.search, "half-typ");
    }

    /// Re-running a query moves it to the front rather than filling the history
    /// with copies of the search someone runs most.
    #[test]
    fn a_repeated_query_is_remembered_once() {
        let mut app = test_app();
        app.search = "alpha".into();
        app.remember_query();
        app.search = "beta".into();
        app.remember_query();
        app.search = "alpha".into();
        app.remember_query();
        assert_eq!(app.search_history, vec!["alpha", "beta"]);

        // An abandoned modal leaves nothing behind.
        app.search = "   ".into();
        app.remember_query();
        assert_eq!(app.search_history, vec!["alpha", "beta"]);
    }

    #[test]
    fn selection_follows_the_session_across_a_resort() {
        let mut app = test_app();
        app.sessions = vec![session("a", false, "/x/a"), session("b", false, "/x/b")];
        app.sort_col = ColumnId::Project;
        app.sort_asc = true;
        app.refilter();
        app.selected = 1;
        let before = app.selected_session().unwrap().key();

        app.sort_asc = false;
        app.refilter();
        assert_eq!(app.selected_session().unwrap().key(), before);
        assert_eq!(app.selected, 0);
    }

    #[test]
    fn selection_stays_in_bounds_when_sessions_disappear() {
        let mut app = test_app();
        app.sessions = (0..5)
            .map(|i| session(&i.to_string(), false, "/x"))
            .collect();
        app.refilter();
        app.selected = 4;
        app.sessions.truncate(2);
        app.refilter();
        assert!(app.selected < app.visible.len());
    }

    #[test]
    fn empty_list_does_not_panic_on_navigation() {
        let mut app = test_app();
        app.refilter();
        app.move_selection(1);
        app.move_selection(-1);
        assert_eq!(app.selected, 0);
        assert!(app.selected_session().is_none());
    }

    #[test]
    fn sort_toggles_on_repeat_and_resets_on_change() {
        let mut app = test_app();
        app.sort_col = ColumnId::Cost;
        app.sort_asc = true;
        app.set_sort(ColumnId::Cost);
        assert!(!app.sort_asc, "same column must flip direction");
        app.set_sort(ColumnId::Cpu);
        assert!(app.sort_asc, "new column starts ascending");
        assert_eq!(app.sort_col, ColumnId::Cpu);
    }

    #[test]
    fn age_filter_roundtrips_through_prefs_keys() {
        for f in [AgeFilter::Day, AgeFilter::Week, AgeFilter::Month] {
            assert_eq!(AgeFilter::parse(f.key()), Some(f));
        }
        assert_eq!(AgeFilter::parse("nope"), None);
    }

    #[test]
    fn age_filter_excludes_old_sessions() {
        let mut app = test_app();
        let mut old = session("old", false, "/x");
        old.last_active = (chrono::Utc::now() - chrono::Duration::days(10)).to_rfc3339();
        app.sessions = vec![session("new", false, "/x"), old];
        app.age_filter = Some(AgeFilter::Day);
        app.refilter();
        assert_eq!(app.visible.len(), 1);
        assert_eq!(app.sessions[app.visible[0].session()].session_id, "new");
    }

    #[test]
    fn cost_floor_filters_by_total_cost() {
        let mut app = test_app();
        let mut cheap = session("cheap", false, "/x");
        cheap.total_cost = Some(0.50);
        let mut pricey = session("pricey", false, "/x");
        pricey.total_cost = Some(5.00);
        app.sessions = vec![cheap, pricey];
        app.cost_floor = 1.0;
        app.refilter();
        assert_eq!(app.visible.len(), 1);
        assert_eq!(app.sessions[app.visible[0].session()].session_id, "pricey");
    }

    #[test]
    fn cost_floor_zero_shows_everything() {
        let mut app = test_app();
        app.sessions = vec![session("a", false, "/x"), session("b", false, "/x")];
        app.cost_floor = 0.0;
        app.refilter();
        assert_eq!(app.visible.len(), 2);
    }

    #[test]
    fn cycle_matches_wraps_around_search_matches() {
        let mut app = test_app();
        let now = chrono::Utc::now().to_rfc3339();
        let mk = |id: &str, label: &str| {
            let mut s = session(id, false, label);
            s.last_active = now.clone();
            s.started_at = now.clone();
            s
        };
        app.sessions = vec![mk("a", "/x/match"), mk("b", "/y"), mk("c", "/z/match")];
        app.search = "match".into();
        app.refilter();
        assert_eq!(app.visible.len(), 2);
        app.selected = 0;
        app.cycle_matches(1);
        assert_eq!(app.selected_session().unwrap().session_id, "c");
        app.cycle_matches(1);
        assert_eq!(app.selected_session().unwrap().session_id, "a");
        app.cycle_matches(-1);
        assert_eq!(app.selected_session().unwrap().session_id, "c");
    }

    #[test]
    fn batch_delete_keeps_marked_sessions_visible_until_worker_confirms() {
        let mut app = test_app();
        app.sessions = vec![
            session("a", false, "/x"),
            session("b", false, "/x"),
            session("c", false, "/x"),
        ];
        app.refilter();
        // Mark a and c by identity, not by row: the three fixtures are created in
        // the same instant, so which row each lands on depends on how the clock
        // happened to tick. Selecting by index made this assert the sort order,
        // and it failed on hosts where those timestamps came out equal or out of
        // creation order.
        let row = |app: &App, id: &str| {
            app.visible
                .iter()
                .position(|&r| app.sessions[r.session()].session_id == id)
                .expect("fixture is visible")
        };
        app.selected = row(&app, "a");
        app.toggle_mark();
        app.selected = row(&app, "c");
        app.toggle_mark();
        assert_eq!(app.marked.len(), 2);
        assert_eq!(app.marked_sessions().len(), 2);

        app.batch(BatchKind::Delete);
        assert_eq!(app.mode, Mode::BatchConfirm);
        app.batch_execute();
        assert_eq!(app.sessions.len(), 3);
        assert_eq!(app.deleting.len(), 2);
        assert!(app.marked.is_empty());
    }

    #[test]
    fn batch_delete_refuses_when_marked_session_is_running() {
        let mut app = test_app();
        app.sessions = vec![session("a", false, "/x"), session("b", true, "/x")];
        app.refilter();
        app.selected = 0;
        app.toggle_mark();
        app.selected = 1;
        app.toggle_mark();
        app.batch(BatchKind::Delete);
        assert_eq!(app.mode, Mode::BatchDeleteBlocked);
    }

    /// The other half of the bell: hearing it is useless if the row it came
    /// from is somewhere in a list of a dozen.
    #[test]
    fn b_jumps_the_selection_to_the_session_that_rang() {
        let mut app = test_app();
        app.sessions = vec![session("a", true, "/x/a"), session("b", true, "/x/b")];
        app.refilter();
        let target = app.sessions[1].key();
        app.notify.last = Some(crate::notify::Rang {
            key: target.clone(),
            label: "b".into(),
            reason: crate::notify::Reason::NeedsInput,
            at: Instant::now(),
        });

        app.selected = 0;
        app.jump_to_bell();
        assert_eq!(app.selected_session().map(Session::key), Some(target));

        // Filtered out of the table, the bell has nowhere to land — and says so
        // rather than moving the cursor to an unrelated row.
        app.search = "x/a".into();
        app.refilter();
        app.selected = 0;
        app.jump_to_bell();
        assert_eq!(app.selected, 0);
        assert!(app.status.is_some());
    }

    #[test]
    fn refresh_interval_adjusts_and_clamps() {
        let mut app = test_app();
        app.refresh_secs = 2.0;
        app.adjust_refresh(0.5);
        assert_eq!(app.refresh_secs, 2.5);
        app.adjust_refresh(-10.0);
        assert_eq!(app.refresh_secs, 0.5);
        app.adjust_refresh(100.0);
        assert_eq!(app.refresh_secs, 60.0);
    }

    fn key(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::NONE)
    }

    /// The whole point of the rebinding: a vim reflex moves the cursor and
    /// cannot reach a live agent.
    #[test]
    fn k_moves_up_and_never_terminates() {
        let mut app = test_app();
        app.sessions = vec![session("a", true, "/x"), session("b", true, "/y")];
        app.refilter();
        app.selected = 1;

        app.on_key(key(KeyCode::Char('k')));
        assert_eq!(app.selected, 0, "k must move up like every modal here");
        assert_eq!(app.mode, Mode::List, "k must not open a kill dialog");

        app.on_key(key(KeyCode::Char('j')));
        assert_eq!(app.selected, 1);

        // Terminate still exists, behind a modifier. The fixture's process has
        // no root PID, so it stops at the explanation rather than the confirm —
        // either way, Ctrl+K is what reaches the terminate path at all.
        app.on_key(KeyEvent::new(KeyCode::Char('k'), KeyModifiers::CONTROL));
        assert_eq!(app.mode, Mode::KillBlocked);
    }

    #[test]
    fn f10_quits_from_an_agent_tab_instead_of_reaching_the_agent() {
        let mut app = test_app();
        app.tab = 1;

        app.on_key(key(KeyCode::F(10)));

        assert!(app.should_quit);
    }

    /// Every filter that paints a badge must be reachable from Esc, one press
    /// at a time.
    #[test]
    fn esc_clears_one_filter_layer_per_press() {
        let mut app = test_app();
        app.sessions = vec![session("a", true, "/x")];
        app.search = "x".into();
        app.cost_floor = 1.0;
        app.live_only = true;
        app.age_filter = Some(AgeFilter::Day);
        app.tool_tab = 2;
        app.refilter();

        for expected in 1..=5 {
            app.on_key(key(KeyCode::Esc));
            let left = [
                !app.search.is_empty(),
                app.cost_floor > 0.0,
                app.live_only,
                app.age_filter.is_some(),
                app.tool_tab != 0,
            ]
            .iter()
            .filter(|on| **on)
            .count();
            assert_eq!(
                left,
                5 - expected,
                "press {expected} cleared the wrong count"
            );
        }
        // A sixth press is harmless.
        app.on_key(key(KeyCode::Esc));
        assert_eq!(app.mode, Mode::List);
    }

    /// Panel keys are bounded by the tab list, not by a literal that drifts.
    #[test]
    fn number_keys_cover_every_panel_and_nothing_more() {
        let mut app = test_app();
        app.sessions = vec![session("a", true, "/x")];
        app.refilter();
        for (i, _) in panels::TABS.iter().enumerate() {
            let digit = char::from_digit(i as u32 + 1, 10).unwrap();
            app.on_key(key(KeyCode::Char(digit)));
            assert_eq!(app.bottom_tab, i, "key {digit} must select panel {i}");
        }
        // One past the end changes nothing rather than selecting a phantom tab.
        let past = char::from_digit(panels::TABS.len() as u32 + 1, 10).unwrap();
        let before = app.bottom_tab;
        app.on_key(key(KeyCode::Char(past)));
        assert_eq!(app.bottom_tab, before);
    }

    /// The live filter and the n/N jump must agree, because they are now the
    /// same predicate.
    #[test]
    fn refilter_and_matches_search_agree() {
        let mut app = test_app();
        app.sessions = vec![
            session("aaa", false, "/home/x/Alpha"),
            session("bbb", false, "/home/x/beta"),
        ];
        for query in ["alpha", "ALPHA", "x/", "", "nomatch"] {
            app.search = query.into();
            app.refilter();
            let by_predicate: Vec<usize> = (0..app.sessions.len())
                .filter(|&i| app.matches_search(&app.sessions[i]))
                .collect();
            assert_eq!(app.visible.len(), by_predicate.len(), "query {query:?}");
        }
    }

    #[test]
    fn case_insensitive_contains_matches_std() {
        for (h, n) in [
            ("Alpha/Beta", "beta"),
            ("Alpha", "alpha"),
            ("Alpha", ""),
            ("a", "aa"),
            ("héllo-World", "world"),
            ("nope", "zz"),
        ] {
            assert_eq!(
                contains_ascii_ci(h, n),
                h.to_ascii_lowercase().contains(n),
                "{h:?} / {n:?}"
            );
        }
    }

    /// An empty table before the first load means "still looking", and the
    /// table draws a different thing for each.
    #[test]
    fn sessions_are_not_reported_empty_before_the_first_load() {
        let app = test_app();
        assert!(!app.loaded);
        assert!(app.sessions.is_empty());
    }
}