cctop 0.25.2

An htop-like terminal monitor for AI coding agent sessions on Linux (Claude Code, Codex, Cursor, Devin, Gemini CLI, OpenCode, Pi, Windsurf)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
//! Workspace tabs: the dashboard, plus a terminal for every agent you open.
//!
//! Nothing here is new machinery. [`shim::host`](crate::shim::host) already puts
//! an agent on a pty cctop owns, and [`attach`](crate::attach) already turns that
//! pty into a screen that can be drawn into any rectangle and resized to it. A
//! tab is a list of those screens; a split is that list drawn side by side
//! instead of one at a time.
//!
//! The dashboard is not in this list — it is tab zero and always there, so
//! [`App::tab`](super::App::tab) is `0` for the session table and `1..=len` for
//! these.

use std::path::Path;
use std::time::{Duration, Instant};

use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

use super::theme::Hue;

/// How long a pane's screen has to sit still before the agent counts as idle.
///
/// An agent that is working repaints constantly — Claude Code's "✻ Baked for
/// 5s" alone ticks every second — so silence is the signal, and it needs no
/// per-harness parsing. Two seconds clears the gap between a spinner's frames
/// without waiting so long that a finished turn goes unnoticed. A blinking
/// cursor does not count: the terminal draws that, not the agent.
///
// ponytail: an agent that redraws nothing while thinking would read as idle.
// None of the four do; if one appears, its transcript's activity state is the
// tiebreak.
const QUIET_IS_IDLE: Duration = Duration::from_secs(2);

/// How often a rmux-backed pane re-asks rmux which process the agent is, until
/// it gets an answer.
///
/// Bounded because the question is asked from the draw loop. It is only asked at
/// all while unanswered, which in practice is the first moment of a pane's life.
const FIND_AGENT_EVERY: Duration = Duration::from_millis(500);

/// Why a tab is asking to be looked at.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Attention {
    /// The agent has stopped drawing: its turn is over and the prompt is yours.
    Idle,
    /// [`Attention::Idle`], on a turn this cctop watched end while you were
    /// not looking at it — news, where plain idle is only context. See
    /// [`seen`](super::seen).
    Done,
    /// The agent has explicitly asked something and is blocked on the answer.
    NeedsInput,
}

/// One terminal on screen.
pub struct Pane {
    /// What this pane started. Dropping it kills that process, which is why a
    /// pane merely *looking at* someone else's session leaves this `None`: `a`
    /// on a session row must not make cctop responsible for its life.
    ///
    /// For a rmux-backed pane the process here is the rmux *client*, not the
    /// agent — see [`rmux`](crate::rmux).
    hosted: Option<crate::shim::Hosted>,
    /// The rmux session the agent is really in, when there is one.
    ///
    /// Its presence is what separates closing a pane from ending an agent: with
    /// it, the two are different acts and only the second needs asking about.
    pub rmux: Option<String>,
    /// The session this pane was opened to resume, named as
    /// [`rmux::name_for_session`](crate::rmux::name_for_session) names it.
    ///
    /// Recorded whether or not rmux is what carries the agent, because it is the
    /// only durable answer to "is this session already open?" — `rmux` alone is
    /// `None` on every pane when rmux is not installed, and resuming one
    /// transcript into two agents is precisely what that question guards.
    pub resumed: Option<String>,
    /// The Claude profile this pane's agent was started under, when it is not
    /// the default one.
    ///
    /// Kept on the pane because that is the only thing that still knows: the
    /// profile reaches the agent as an environment variable, which is invisible
    /// from the outside, and the border needs it to show the right account's
    /// limits rather than whichever account cctop itself would have used.
    ///
    /// Filled in by the caller that chose it, like `resumed` below.
    pub profile: Option<String>,
    /// The pid cctop hosts. A second request to view the same agent finds this
    /// pane rather than opening a duplicate onto one terminal.
    pub pid: u32,
    /// The agent's own pid, once known, for a pane that is not hosting it
    /// directly. See [`Pane::agent`] for why this is worth chasing.
    agent: Option<u32>,
    /// When rmux was last asked who the agent is, so an unanswered question is
    /// retried without being retried every frame.
    asked_at: Option<Instant>,
    pub label: String,
    /// Whether an agent is what this pane started.
    ///
    /// [`harnesses`] offers the login shell alongside the agents, and half of
    /// what a second tab is for is `git diff` — so a pane is not necessarily an
    /// agent, and everything `attention` infers from a still screen assumes it
    /// is one. A shell sitting at its prompt has not *finished a turn*; it has
    /// no turns. Without this it goes green two seconds after you stop typing,
    /// which reads as an agent waiting for you in a tab where there is none.
    is_agent: bool,
    pub view: crate::attach::Attach,
    /// When this pane's screen last changed, which is how idleness is told
    /// without asking the agent or its transcript anything.
    drew_at: Instant,
}

impl Pane {
    /// A pane labelled `label` with no process behind it, for tests elsewhere
    /// that draw one: the fields that own a process are private to this module.
    #[cfg(test)]
    pub(crate) fn for_test(label: &str) -> Pane {
        Pane {
            hosted: None,
            rmux: None,
            resumed: None,
            profile: None,
            pid: 4321,
            agent: None,
            asked_at: None,
            label: label.into(),
            is_agent: true,
            view: crate::attach::Attach::for_test(),
            drew_at: Instant::now(),
        }
    }

    /// What this pane's agent says it is doing, read off its screen.
    ///
    /// Only for a harness with a row in [`FOOTERS`]: that row is what makes a
    /// pane an agent worth reading, where `is_agent` only knows the harnesses
    /// cctop aliases, and `Esc to cancel` in a shell is nobody's question.
    ///
    /// A screen none of its rules match is idle once it has gone still — the
    /// same inference the tab bar makes from silence, and sound for the same
    /// reason: every one of these harnesses ticks a timer or a spinner while it
    /// works, so a still screen with no working hint on it is a turn that ended.
    /// Still, and not merely unmatched: see [`FOOTERS`] for the frame mid-turn
    /// that has neither.
    pub fn read_screen(&self) -> Option<crate::peek::Screened> {
        if !screenable(self.harness()) {
            return None;
        }
        let screen = self.view.parser.screen();
        let (_, cols) = screen.size();
        let rows: Vec<String> = screen.rows(0, cols).collect();
        let signal = screen_state(self.harness(), &rows)
            .or_else(|| self.idle().then_some(crate::hook::Signal::Idle))?;
        let ask = (signal == crate::hook::Signal::NeedsInput)
            .then(|| screen_ask(self.harness(), &rows))
            .flatten();
        Some(crate::peek::Screened { signal, ask })
    }

    /// Whether the agent has gone quiet long enough to count as waiting for you.
    fn idle(&self) -> bool {
        self.drew_at.elapsed() >= QUIET_IS_IDLE
    }

    /// Whether the agent in this pane has rung and not yet been looked at.
    ///
    /// The one signal in `attention` that the agent sends deliberately. Every
    /// other input there is inference — a hook event, or a screen that stopped
    /// moving — and this is the agent saying it outright, in the language every
    /// terminal has understood for fifty years.
    fn rang(&self) -> bool {
        self.view.rang().is_some()
    }

    /// Answer the bell, because this pane is the one being looked at, and give
    /// back what the agent said when it rang.
    pub fn answer_bell(&mut self) -> Option<String> {
        self.view.answer()
    }

    /// The pid of the agent this pane shows.
    ///
    /// The same thing as [`Pane::pid`] everywhere except under rmux, where that
    /// is the client and this is the agent behind it. Everything asking what the
    /// agent *is doing* — its hooks, its transcript, its row in the table —
    /// wants this one, because that is the process all of it is keyed by.
    ///
    /// Falls back to the hosted pid while the answer is still unknown. That
    /// finds nothing, which is right: nothing is better than the wrong agent,
    /// and the caller already has a fallback for a pane it knows nothing about.
    pub fn agent(&self) -> u32 {
        self.agent.unwrap_or(self.pid)
    }

    /// Learn which process the agent is, if that is not known yet.
    ///
    /// It cannot be settled at launch. cctop spawns a rmux *client* and returns;
    /// the server creating the session and spawning the agent inside it happens
    /// on its own time, so for the first moments of a pane's life there is no
    /// pane to ask about. Once found it is kept — a rmux pane's command outlives
    /// every client that ever looks at it, so the answer cannot go stale while
    /// this pane is alive to hold it.
    fn find_agent(&mut self) {
        let Some(name) = self.rmux.as_deref() else {
            return;
        };
        if self.agent.is_some()
            || self
                .asked_at
                .is_some_and(|at| at.elapsed() < FIND_AGENT_EVERY)
        {
            return;
        }
        self.asked_at = Some(Instant::now());
        self.agent = crate::rmux::agent_pid(name);
        // The first moment the session is known to be there is the first moment
        // its options can be set, and settling it here means it is done once per
        // pane rather than on a timer. Every attach passes through, so a session
        // left by an older cctop is quieted when it is picked up again.
        if self.agent.is_some() {
            crate::rmux::quiet(name);
            crate::rmux::mouse(name);
            // The one moment the session exists and this pane's label is settled
            // — the callers that rename a pane do it before it is ever pumped.
            // Every other cctop reads the tab's name back off the session, so
            // without this a resumed agent would be one thing here and a uuid
            // next door.
            crate::rmux::set_label(name, &self.label);
            // Only when there is one to record: an unset option reads back as
            // "the default account", which is exactly what `None` means here.
            if let Some(profile) = &self.profile {
                crate::rmux::set_profile(name, profile);
            }
        }
    }

    /// Whether the agent survives this pane going away.
    pub fn outlives_cctop(&self) -> bool {
        self.rmux.is_some()
    }

    /// Whether ending this pane's agent is cctop's to do.
    ///
    /// False for a pane opened with `a`, which is a window onto an agent started
    /// somewhere else: there is no pty to drop and no rmux session to kill, so
    /// the pane can be closed but the agent cannot be reached. Asking first is
    /// the difference between a key that declines and a key that appears to work
    /// and does nothing.
    pub fn owns_agent(&self) -> bool {
        self.hosted.is_some() || self.rmux.is_some()
    }

    /// The harness running in this pane, as one word — `"claude"`, `"zsh"`.
    ///
    /// Read off the rmux session name where there is one: it is spelled
    /// `cctop-<harness>-…` at creation and never rewritten, so it still says
    /// "claude" after the tab has been renamed to anything at all. A pane with
    /// no session — one cctop hosts itself, or a window opened with `a` —
    /// falls back to the first word of its label, which a rename does clobber.
    ///
    /// ponytail: a renamed pane on cctop's own pty answers with its new name.
    pub fn harness(&self) -> &str {
        harness_of(self.rmux.as_deref().unwrap_or(self.label.as_str()))
    }

    /// Whether an agent is what this pane started, rather than a shell or an
    /// editor — see the field of the same name.
    pub fn is_agent(&self) -> bool {
        self.is_agent
    }

    /// The key to actually send this pane's agent, once pane-specific
    /// translation is done.
    ///
    /// There is exactly one translation: Claude Code puts the top and bottom
    /// of the chat on Ctrl+Home and Ctrl+End — the right action, a chord too
    /// many for keys already named after where they go. In one of its panes
    /// the bare keys are promoted to the shifted forms on the way in; anywhere
    /// else they keep their line-editing meaning, which a shell reaches for
    /// constantly.
    pub fn translate_key(&self, key: KeyEvent) -> KeyEvent {
        match key.code {
            KeyCode::Home | KeyCode::End
                if key.modifiers.is_empty() && self.harness() == "claude" =>
            {
                KeyEvent::new(key.code, KeyModifiers::CONTROL)
            }
            _ => key,
        }
    }
}

/// Who owns the agent a pane is opened onto.
#[derive(Debug, Clone)]
pub enum Own {
    /// A rmux session of this name, so the agent outlives cctop. An existing
    /// session of that name is attached to rather than replaced.
    Tmux(String),
    /// A rmux session that is already running: attach, never create. Picking one
    /// from the launcher that has since ended must fail and say so, not quietly
    /// start something new under its name.
    TmuxExisting(String),
    /// A pty cctop owns, which ends when cctop does.
    Cctop,
}

impl Pane {
    /// Start `argv` and open a pane onto it.
    pub fn launch(argv: &[String], cwd: Option<&Path>, own: Own) -> anyhow::Result<Pane> {
        let rmux = match &own {
            Own::Tmux(name) | Own::TmuxExisting(name) => Some(name.clone()),
            Own::Cctop => None,
        };
        let spawn = match &own {
            Own::Tmux(name) => {
                // Before the client, not after: the pane's scrollback is fixed
                // the moment it is made. See [`rmux::prepare`].
                crate::rmux::prepare(argv, name, cwd);
                crate::rmux::attach_or_create(argv, name, cwd)
            }
            Own::TmuxExisting(name) => crate::rmux::attach(name),
            Own::Cctop => argv.to_vec(),
        };
        let hosted = crate::shim::host(&spawn, cwd, super::render::pane_size())?;
        // The shim binds and serves the socket before returning, so there is
        // something to connect to even though the agent has drawn nothing yet.
        let mut view = crate::attach::attach(hosted.pid).ok_or_else(|| {
            anyhow::anyhow!(
                "{} started but its terminal could not be opened",
                label_of(argv)
            )
        })?;
        // With rmux in the middle the agent's keyboard-protocol request never
        // reaches this end; see [`attach::Attach::assume_extended_keys`].
        if rmux.is_some() {
            view.assume_extended_keys();
        }
        Ok(Pane {
            pid: hosted.pid,
            // The agent's name, not the wrapper's: a tab reading `rmux
            // new-session -A -s cctop-claude-32cca860` names the plumbing.
            label: label_of(argv),
            is_agent: starts_an_agent(argv),
            view,
            rmux,
            // Filled in by the caller that knows: launching is not resuming, and
            // most launches are not any session in particular.
            resumed: None,
            profile: None,
            agent: None,
            asked_at: None,
            hosted: Some(hosted),
            drew_at: Instant::now(),
        })
    }

    /// Open a pane onto an agent something else is responsible for.
    pub fn view_of(pid: u32, label: String) -> Option<Pane> {
        Some(Pane {
            hosted: None,
            rmux: None,
            resumed: None,
            // Nothing was launched here, so there is no choice to record.
            profile: None,
            pid,
            // Nothing stands between this pane and the agent: the pid asked for
            // is the agent's, which is what makes this the answer already.
            agent: Some(pid),
            asked_at: None,
            label,
            // `a` on a session row is the only way here, and a session row is
            // an agent.
            is_agent: true,
            view: crate::attach::attach(pid)?,
            drew_at: Instant::now(),
        })
    }

    /// End the agent behind this pane for good.
    ///
    /// Only rmux-backed panes need this. Everywhere else, dropping the pane
    /// already is the kill — which is the whole reason the two have to be told
    /// apart once rmux is in the picture.
    pub fn kill_agent(&self) -> Result<(), String> {
        match &self.rmux {
            Some(name) => crate::rmux::kill(name),
            None => Ok(()),
        }
    }

    /// Whether the agent behind this pane has gone.
    fn finished(&mut self) -> bool {
        match self.hosted.as_mut() {
            Some(hosted) => hosted.finished().is_some(),
            // Nothing here owns the process, so the connection is the only
            // evidence there is: a shim that exited closes it.
            None => self.view.closed(),
        }
    }
}

/// A rmux session a tab stands for while this cctop holds no client on it.
///
/// Every cctop on this machine shows a tab for every cctop-owned rmux session,
/// including the ones another cctop started. Holding a client on all of them
/// would be the wrong way to do it: rmux would have several clients on one
/// window, and the size they argue their way to is nobody's. So an unwatched tab
/// keeps only this — enough to name it, to say when its agent wants you, and to
/// attach the moment you switch to it.
#[derive(Debug, Clone)]
pub struct Shared {
    /// The rmux session, which is the tab's identity across every cctop.
    pub name: String,
    /// What the cctop that started it called the tab. See
    /// [`rmux::set_label`](crate::rmux::set_label).
    pub label: String,
    /// The agent's own pid, so a tab nobody is attached to can still say that it
    /// is waiting on you — the hooks report under this and need no pane.
    pub pid: Option<u32>,
    /// When the session last drew anything, in unix seconds, as of the last
    /// sync. Stands in for [`Pane::drew_at`] on a tab that has no pane to watch.
    pub activity: Option<u64>,
    /// The account the agent was started under, carried across the trade so the
    /// pane this becomes again reports the same limits it did before. See
    /// [`Pane::profile`].
    pub profile: Option<String>,
    /// What the agent last reported about itself, as recorded on the rmux
    /// session — see [`rmux::State`](crate::rmux::State).
    ///
    /// This is the agent's own word, and it outranks [`Shared::idle`] below,
    /// which is only ever an inference from a clock. It is also the only thing
    /// either of them can say about a session this cctop was not running for:
    /// the live report went to whoever was listening at the time, and that was
    /// nobody.
    pub state: Option<crate::rmux::State>,
}

impl Shared {
    /// What a [`crate::rmux::Running`] becomes when no client of ours is on it.
    pub fn of(agent: &crate::rmux::Running) -> Shared {
        Shared {
            label: agent.label.clone().unwrap_or_else(|| {
                // No label recorded: an agent from a cctop older than this,
                // or one whose `set-option` did not land. The session name is
                // the fallback, minus the prefix every one of them carries.
                agent
                    .name
                    .strip_prefix("cctop-")
                    .unwrap_or(&agent.name)
                    .to_string()
            }),
            name: agent.name.clone(),
            pid: agent.pid,
            activity: agent.activity,
            profile: agent.profile.clone(),
            state: agent.state,
        }
    }

    /// Whether the session holds an agent rather than a shell.
    ///
    /// Read off the session name, the one thing about it that is never
    /// rewritten — the same place [`Pane::harness`] looks — because a tab with
    /// no pane has no argv left to ask [`starts_an_agent`] about.
    pub fn is_agent(&self) -> bool {
        let harness = harness_of(&self.name);
        crate::alias::AGENTS
            .split_whitespace()
            .any(|agent| agent == harness)
    }

    /// What the rmux session records about its agent, if it is still true.
    ///
    /// Aged out by the same asymmetric rule a live report is — see
    /// [`Signal::is_current_after`](crate::hook::Signal::is_current_after) — so
    /// a session killed mid-turn stops claiming to be working, while one that
    /// has been asking since yesterday still is.
    fn recorded(&self) -> Option<crate::hook::Signal> {
        let state = self.state?;
        state
            .is_current(crate::rmux::now_secs())
            .then_some(state.signal)
    }

    /// Whether the agent has gone quiet long enough to count as waiting for you.
    ///
    /// The same judgement [`Pane::idle`] makes, from rmux's record of the
    /// session rather than from a screen — an unwatched tab has no screen. A
    /// second of slack on top of [`QUIET_IS_IDLE`], because rmux reports this to
    /// the second and the sweep that read it is already up to
    /// [`SHARE_EVERY`](super::panes::SHARE_EVERY) old: without it a busy agent flickers
    /// idle between sweeps.
    fn idle(&self) -> bool {
        let Some(activity) = self.activity else {
            return false;
        };
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);
        now.saturating_sub(activity) > QUIET_IS_IDLE.as_secs()
    }
}

/// One workspace tab: the panes shown together, and which of them has the
/// keyboard.
pub struct Tab {
    pub panes: Vec<Pane>,
    pub focus: usize,
    /// Panes stacked top to bottom rather than laid out left to right.
    ///
    /// One direction for the whole tab. A split *tree* would let every pane
    /// divide differently, and nothing has needed that yet — this covers the
    /// side-by-side and the stacked case with a bool.
    pub stacked: bool,
    /// Set only while `panes` is empty: the session this tab is a placeholder
    /// for. [`Tab::attach`] trades it for a pane and [`Tab::detach`] trades it
    /// back, so the two are never both true and an empty tab with no `shared` is
    /// still an agent that has exited.
    pub shared: Option<Shared>,
    /// The *rest* of a split's sessions, for a tab holding no client on any of
    /// them.
    ///
    /// `shared` is the leading pane and stays that way; this is the other panes,
    /// in order. Both are set only while `panes` is empty, and both are traded
    /// for panes together by [`Tab::attach`].
    ///
    /// A split used to have no form here at all: [`Tab::detach`] declined one, so
    /// a tab of two sessions could not be put down and picked up, and came back
    /// from a restart as two tabs that had never met. Carrying the rest is what
    /// lets one tab hold them, and it is why a tab's identity is now recorded on
    /// rmux rather than implied by what happens to be attached.
    pub extra: Vec<Shared>,
    /// The colour the tab was painted, if any.
    ///
    /// Kept on the tab rather than on a pane or a `Shared`, because it is the
    /// one place that survives the trade between them: a pane is swapped for a
    /// `Shared` on every switch away, and a property either side held would
    /// have to be handed across both ways.
    pub color: Option<Hue>,
    /// When this tab's agent was last restarted, for the sweep across its
    /// label that says so. On the tab for the reason `color` is: a restart
    /// swaps the pane or the `Shared` underneath, and the one thing still
    /// standing afterwards is the tab.
    pub restarted: Option<Instant>,
    /// Whether the focused pane is drawn over the whole tab — `Alt+z`.
    ///
    /// A mode of the tab rather than a mark on one pane, so it follows the
    /// keyboard: `Alt+o` while zoomed shows the next pane zoomed, the way
    /// flipping through full-screen terminals should feel, and `Alt+b`'s walk
    /// through a split lands on the pane that asked with it on screen. See
    /// [`Tab::zoomed`] for why it is read through a method.
    zoom: bool,
}

impl Tab {
    pub fn new(pane: Pane) -> Tab {
        Tab {
            panes: vec![pane],
            focus: 0,
            stacked: false,
            shared: None,
            extra: Vec::new(),
            color: None,
            restarted: None,
            zoom: false,
        }
    }

    /// A tab for a rmux session this cctop has not attached to — one another
    /// cctop started, or one this cctop left when you switched away.
    ///
    /// A tab of one, which is every session nobody has split. It takes its axis
    /// off the session rather than assuming side by side, so a session carrying
    /// `@cctop_axis` from a split it has since been pulled out of comes back the
    /// way it was left.
    /// A tab for a rmux session this cctop has not attached to — one another
    /// cctop started, or one this cctop left when you switched away.
    ///
    /// A tab of one, which is every session nobody has split. Its axis is read
    /// off the session rather than assumed, so a session still carrying
    /// `@cctop_axis` from a split it has since been pulled out of comes back the
    /// way it was left.
    #[cfg(test)]
    pub fn for_agent(agent: &crate::rmux::Running) -> Tab {
        Tab::split_of(agent, &[], agent.axis())
    }

    /// A tab standing for one leading session and however many more belong to
    /// the same tab beside it.
    ///
    /// `others` is the rest of the split in pane order, and is empty for every
    /// session that has never been split — which is the shape the whole codebase
    /// assumed before this existed, so nothing has to ask which case it is in.
    ///
    /// The axis is read off the sessions themselves rather than passed in, so
    /// that a tab comes back laid out the way it was left and no caller has to
    /// remember to ask. A word this cctop does not know reads as side by side,
    /// which is the default and not a claim.
    pub fn split_of(
        leader: &crate::rmux::Running,
        others: &[&crate::rmux::Running],
        axis: crate::rmux::Axis,
    ) -> Tab {
        Tab {
            panes: Vec::new(),
            focus: 0,
            stacked: axis == crate::rmux::Axis::Stacked,
            shared: Some(Shared::of(leader)),
            extra: others.iter().map(|agent| Shared::of(agent)).collect(),
            color: leader.color.as_deref().and_then(Hue::from_name),
            restarted: None,
            zoom: false,
        }
    }

    /// Whether this tab is a session with no client of ours on it.
    pub fn detached(&self) -> bool {
        self.panes.is_empty() && self.shared.is_some()
    }

    /// The rmux sessions this tab stands for, whether attached or not.
    pub fn sessions(&self) -> impl Iterator<Item = &str> {
        self.panes
            .iter()
            .filter_map(|pane| pane.rmux.as_deref())
            .chain(self.shared.iter().map(|s| s.name.as_str()))
            .chain(self.extra.iter().map(|s| s.name.as_str()))
    }

    /// Put a client of this cctop back on the session this tab stands for.
    ///
    /// Only ever called on the way to looking at the tab, which is what makes
    /// the trade sound: at most one cctop is being *used* on a session at a time,
    /// so at most one of them holds the client whose size rmux fits the window
    /// to.
    ///
    /// A split attaches every pane at once, which is what it already does when
    /// the tab was never put down — the panes are peers and all of them are
    /// being looked at.
    pub fn attach(&mut self) -> anyhow::Result<()> {
        let Some(shared) = self.shared.clone() else {
            return Ok(());
        };
        // Leading pane first, so the tab keeps the shape it was left in whatever
        // order the sessions were listed back in.
        let mut panes = vec![Self::attach_one(&shared)?];
        for extra in &self.extra {
            panes.push(Self::attach_one(extra)?);
        }
        self.panes = panes;
        self.focus = 0;
        self.shared = None;
        self.extra.clear();
        Ok(())
    }

    /// One `Shared` as the pane it becomes when this cctop takes a client on it.
    fn attach_one(shared: &Shared) -> anyhow::Result<Pane> {
        // `TmuxExisting` never creates: a session that ended between the sync
        // that found it and this must fail and say so, not silently start a new
        // agent under a dead agent's name.
        let argv = [shared.label.clone()];
        let mut pane = Pane::launch(&argv, None, Own::TmuxExisting(shared.name.clone()))?;
        // The label the other cctop chose, not one reconstructed from the argv
        // above — which is the label already, but only by coincidence.
        pane.label = shared.label.clone();
        // Reattaching is not relaunching, so nothing here chose an account —
        // this is the one the session was started under, read back off rmux by
        // the sweep that found it or kept from the pane this tab last had.
        pane.profile = shared.profile.clone();
        Ok(pane)
    }

    /// Give up this cctop's client on the session, keeping the tab.
    ///
    /// Dropping the pane kills the rmux client and nothing else — the session,
    /// and the agent in it, carry on for whichever cctop looks next. Declines for
    /// anything that could not be rebuilt from a session name: a pty cctop owns
    /// and would therefore *end* here, or a pane merely looking at somebody
    /// else's agent.
    ///
    /// A split is now rebuildable, so it detaches like anything else — each pane
    /// keeps its own [`Shared`] and the whole thing comes back together on the
    /// way in. It used to decline, which is why a split could not survive a
    /// restart at all: the tab held clients it had no way of giving up, and the
    /// only record of the arrangement was the process about to exit.
    pub fn detach(&mut self) -> bool {
        // Nothing to give up. Without this a tab that was *already* detached —
        // empty `panes`, holding its `Shared`s — would read as a successful
        // detach and be cleared into a tab with no session behind it at all,
        // which `drop_empty_tabs` then throws away.
        if self.panes.is_empty() {
            return false;
        }
        // A recording is fed by this client, so giving it up would end the
        // recording — and switching tabs is not asking for that. The tab keeps
        // its client until the recording is stopped, at the cost of rmux
        // sizing the window for it meanwhile.
        if self.panes.iter().any(|pane| pane.view.recording()) {
            return false;
        }
        // Every pane has to be one that can come back. A tab with a pty cctop
        // owns anywhere in it keeps its clients rather than losing the pane.
        if self.panes.iter().any(|pane| pane.rmux.is_none()) {
            return false;
        }
        let panes = std::mem::take(&mut self.panes);
        let mut shared = Vec::with_capacity(panes.len());
        for pane in &panes {
            shared.push(Shared {
                name: pane.rmux.clone().expect("checked above"),
                label: pane.label.clone(),
                pid: Some(pane.agent()),
                // Nothing has been read off rmux for this tab yet, and the pane
                // it is replacing was on screen a moment ago. The next sweep
                // fills it.
                activity: None,
                profile: pane.profile.clone(),
                state: None,
            });
        }
        // The leading pane is the tab; the rest follow it in order.
        self.shared = shared.first().cloned();
        self.extra = shared.into_iter().skip(1).collect();
        self.focus = 0;
        true
    }

    /// Call the tab something other than the command that started it.
    ///
    /// Written onto the rmux session as well as the pane, because the label is
    /// how every *other* cctop names this tab — and how this one names it again
    /// after a detach. A rename only the pane remembered would come back as the
    /// old name the moment either happened.
    ///
    /// The first pane, not the focused one: a split tab is titled after its
    /// first pane with a count of the rest, so that is the label the bar shows.
    pub fn rename(&mut self, name: String) {
        if let Some(pane) = self.panes.first_mut() {
            if let Some(session) = pane.rmux.as_deref() {
                crate::rmux::set_label(session, &name);
            }
            pane.label = name;
        } else if let Some(shared) = self.shared.as_mut() {
            crate::rmux::set_label(&shared.name, &name);
            shared.label = name;
        }
    }

    /// Paint the tab, the way [`Tab::rename`] names it.
    ///
    /// Written onto every rmux session the tab stands for — both halves of a
    /// split included, which is why `sessions` rather than the first pane —
    /// so every cctop that lists them paints it the same way, and so the
    /// colour is still there after a detach. A pane with no session behind it
    /// keeps the colour in memory only, as far as its label gets either.
    ///
    /// `None` hands the tab back to the default ink.
    pub fn recolor(&mut self, color: Option<Hue>) {
        for session in self.sessions() {
            crate::rmux::set_color(session, color.map(Hue::name).unwrap_or(""));
        }
        self.color = color;
    }

    /// What the tab bar calls this tab.
    pub fn title(&self) -> String {
        match self.panes.len() {
            0 | 1 => self
                .panes
                .first()
                .map(|p| p.label.clone())
                .or_else(|| self.shared.as_ref().map(|s| s.label.clone()))
                .unwrap_or_default(),
            n => format!("{} +{}", self.panes[0].label, n - 1),
        }
    }

    /// Whether any pane of this tab is being recorded, for the bar to say so.
    pub fn recording(&self) -> bool {
        self.panes.iter().any(|pane| pane.view.recording())
    }

    pub fn focused_mut(&mut self) -> Option<&mut Pane> {
        self.panes.get_mut(self.focus)
    }

    /// Whether one pane is filling the tab.
    ///
    /// Only while there is more than one: zooming a lone pane changes nothing
    /// on screen, and a marker in the bar that says otherwise would be a lie
    /// — nor should closing a split down to one leave the flag set for the
    /// next split to inherit as a surprise.
    pub fn zoomed(&self) -> bool {
        self.zoom && self.panes.len() > 1
    }

    /// Zoom the focused pane, or put the split back. Returns whether it is
    /// zoomed now; `None` when there is nothing to zoom it over.
    pub fn toggle_zoom(&mut self) -> Option<bool> {
        if self.panes.len() < 2 {
            self.zoom = false;
            return None;
        }
        self.zoom = !self.zoom;
        Some(self.zoom)
    }

    /// Add a pane to the split and give it the keyboard.
    ///
    /// Unzooms: asking for a split is asking to see both halves of it, and a
    /// new pane born hidden behind a zoom would be an agent started out of
    /// sight.
    ///
    /// Records the tab's shape onto rmux as it goes, so this arrangement is
    /// still here after a restart: which tab each session belongs to, which pane
    /// of it each is, and which way the tab divides. Written on every pane
    /// rather than the new one alone, because the two sessions were not a tab
    /// before this call and both have to be able to say so afterwards.
    pub fn split(&mut self, pane: Pane, stacked: bool) {
        self.stacked = stacked;
        self.panes.push(pane);
        self.focus = self.panes.len() - 1;
        self.zoom = false;
        self.record_shape();
    }

    /// Write the tab's membership and layout onto every session it stands for.
    ///
    /// The leading pane's name is the tab's name — it is unique already, it is
    /// stable for as long as the session is, and it costs nothing to mint. It is
    /// written onto every pane including the leader, so that closing the leader
    /// leaves the rest still able to say which tab they are.
    ///
    /// Best effort and silent, like every other `@cctop_*` write: a shape that
    /// failed to save is a split that comes back as two tabs, which is where a
    /// split was before any of this.
    pub fn record_shape(&self) {
        let names: Vec<&str> = self.sessions().collect();
        let Some(leader) = names.first().copied() else {
            return;
        };
        let axis = match self.stacked {
            true => crate::rmux::Axis::Stacked,
            false => crate::rmux::Axis::Side,
        };
        for (index, name) in names.iter().enumerate() {
            // A tab of one records nothing: it is the shape every session had
            // before this option existed, and writing it would mean a later split
            // has to take it back off.
            if names.len() < 2 {
                crate::rmux::set_tab(name, "");
            } else {
                crate::rmux::set_tab(name, leader);
                crate::rmux::set_pane(name, index);
            }
        }
        if names.len() > 1 {
            crate::rmux::set_axis(&names, axis);
        }
    }

    /// Move the keyboard to the next pane, wrapping.
    pub fn cycle_focus(&mut self) {
        if !self.panes.is_empty() {
            self.focus = (self.focus + 1) % self.panes.len();
        }
    }

    /// Fold in whatever the agents have drawn. True when anything changed.
    ///
    /// Every pane is pumped, not just the focused one: the shim's output has to
    /// be read whether or not it is on screen, and a background pane whose
    /// buffer filled up would stall the agent behind it.
    pub fn pump(&mut self) -> bool {
        self.panes.iter_mut().fold(false, |changed, pane| {
            // Not `||`: that short-circuits, and every pane must be drained.
            let drew = pane.view.pump();
            if drew {
                pane.drew_at = Instant::now();
            }
            // Here because it is the one thing every pane does every tick, and
            // the answer has to be chased rather than waited for — see
            // [`Pane::find_agent`].
            pane.find_agent();
            drew | changed
        })
    }

    /// What this tab wants, if anything — the most urgent of its panes.
    ///
    /// `known` is what has actually been *reported* about a pane's agent, from
    /// its hooks or its transcript. When it answers, it wins: an agent saying
    /// its turn is over beats any inference drawn from the pixels. When it does
    /// not — the agent has no hooks and has written nothing yet — the pane's own
    /// screen is the fallback, and the only thing that can be read off a screen
    /// is that it stopped moving.
    ///
    /// The focused pane never asks: you are looking straight at it.
    ///
    /// `known` is asked about [`Pane::agent`] and not the pid cctop hosts, which
    /// is the difference between a rmux-backed tab that knows what its agent is
    /// doing and one reduced to guessing from its screen.
    pub fn attention(
        &self,
        focused: bool,
        known: &dyn Fn(u32) -> Option<crate::hook::Signal>,
    ) -> Option<Attention> {
        // A tab nobody is attached to has no screen to read, so `known` is not
        // the tiebreak here — it is the whole answer. Which is enough for the
        // case that matters: an agent another cctop started, blocked on a
        // question, still blinks at you here.
        if let Some(shared) = &self.shared {
            // Three answers, in order of how directly they know. A live report
            // is this cctop hearing the agent itself; the session's record is
            // some *other* cctop having heard it, which is the only answer that
            // survives this one restarting or having been closed at the time;
            // and `idle()` below is nobody having heard anything, reading a
            // clock instead.
            let reported = shared.pid.and_then(known).or_else(|| shared.recorded());
            return match reported {
                Some(crate::hook::Signal::NeedsInput) => Some(Attention::NeedsInput),
                // The held-prompt shape, read off rmux's record of the session
                // instead of a screen. See the pane arm below for why a tool in
                // flight over a still terminal is a question.
                Some(crate::hook::Signal::Acting) => shared.idle().then_some(Attention::NeedsInput),
                Some(signal) if signal.is_working() => None,
                Some(_) => Some(Attention::Idle),
                // No hooks, so the fallback is the same one a pane uses — that
                // the thing has stopped drawing — asked of rmux instead of a
                // screen this cctop does not have.
                None => shared.idle().then_some(Attention::Idle),
            };
        }
        self.panes
            .iter()
            .enumerate()
            .filter(|(i, _)| !(focused && *i == self.focus))
            .filter_map(|(_, pane)| match known(pane.agent()) {
                // A bell over a turn the agent has already reported as finished
                // is the nudge, not a question: Claude Code rings its
                // `idle_prompt` notification a minute after `Stop` down the
                // same bell it rings a permission prompt with, and reading that
                // as a held question is how a tab that is merely done goes
                // amber and stays amber. The agent's own word for its state is
                // the one thing that can tell the two apart.
                Some(crate::hook::Signal::Idle) if pane.rang() => Some(Attention::Idle),
                // Otherwise, before anything inferred: the agent rang. A harness
                // rings when it is blocked on you — see [`Pane::rang`].
                _ if pane.rang() => Some(Attention::NeedsInput),
                // Everything below infers a turn from a screen or a hook, and a
                // pane that is not an agent has no turns to infer. A shell left
                // at its prompt is still by definition, so the quiet-means-idle
                // fallback fires on every one of them: the tab goes green two
                // seconds after you stop typing and reads as an agent waiting
                // for you, in a tab holding no agent at all.
                //
                // Above rather than below the bell on purpose — a bell is the
                // thing in the pane asking for you outright, and a long build
                // that finishes with a `\a` means it as much as an agent does.
                _ if !pane.is_agent => None,
                Some(crate::hook::Signal::NeedsInput) => Some(Attention::NeedsInput),
                // A tool call that started, has not come back, and has stopped
                // repainting is a permission prompt waiting on you. Claude Code
                // says so outright — `PermissionRequest` arrives as
                // `NeedsInput`, matched above — but it is the only harness that
                // does: the rest raise a `Notification` on a six-second timer or
                // nothing at all, and a permission prompt leaves no trace in a
                // transcript either. So without this a tab blocked on one is
                // drawn as merely idle, the same green as a tab whose turn is
                // simply over.
                //
                // The two halves are both needed. A tool in flight alone is the
                // ordinary case; a still screen alone is the finished turn the
                // green already covers. Together they are the one thing that
                // holds an agent mid-tool without it drawing anything.
                //
                // ponytail: a tool that runs long *and* silently reads the same
                // way. Claude Code, Gemini and Cursor all tick an elapsed timer
                // while a tool runs, so in practice the screen is only still
                // when the agent is blocked.
                Some(crate::hook::Signal::Acting) => pane.idle().then_some(Attention::NeedsInput),
                // Reported as working — compacting and just-started included:
                // the screen is irrelevant, and this is the case the heuristic
                // gets wrong for an agent that thinks quietly.
                Some(signal) if signal.is_working() => None,
                // Its turn is over, or the session is.
                Some(_) => Some(Attention::Idle),
                None => pane.idle().then_some(Attention::Idle),
            })
            // A held question outranks a finished turn: one of them is blocking
            // an agent, the other is only waiting on you when you get to it.
            .max_by_key(|a| matches!(a, Attention::NeedsInput))
    }

    /// The agents this tab speaks for in the bar: every pane's but the one you
    /// are looking straight at, which is the same exclusion
    /// [`Tab::attention`] makes. A detached tab speaks for the agent its
    /// session carries.
    pub fn unwatched_agents(&self, focused: bool) -> Vec<u32> {
        if let Some(shared) = &self.shared {
            return shared.pid.into_iter().collect();
        }
        self.panes
            .iter()
            .enumerate()
            .filter(|(i, pane)| pane.is_agent && !(focused && *i == self.focus))
            .map(|(_, pane)| pane.agent())
            .collect()
    }

    /// Drop the panes whose agents have exited. True once nothing is left.
    ///
    /// A detached tab is never nothing left: it holds no pane by design, and
    /// what becomes of it is the sync's to decide — the session it stands for
    /// outlives every client, this cctop's included.
    ///
    /// A pane that goes while it is being recorded has its recording stopped
    /// here, and where the file went is added to `saved` for the caller to say:
    /// the agent exiting is the commonest way a recording ends, and the one
    /// nobody pressed a key for.
    pub fn reap(&mut self, saved: &mut Vec<(std::path::PathBuf, std::io::Result<()>)>) -> bool {
        self.panes.retain_mut(|pane| {
            if !pane.finished() {
                return true;
            }
            saved.extend(pane.view.stop_recording());
            false
        });
        self.focus = self.focus.min(self.panes.len().saturating_sub(1));
        self.panes.is_empty() && self.shared.is_none()
    }
}

/// The agents a new pane can be started with: the ones cctop already knows how
/// to alias, filtered to what is actually installed, plus the login shell.
///
/// The shell earns its place — half of what a tab is wanted for next to an agent
/// is `git diff`, and a tab that can only hold an agent would send you back out
/// to another window for it.
pub fn harnesses() -> Vec<Vec<String>> {
    let mut found: Vec<Vec<String>> = crate::alias::AGENTS
        .split_whitespace()
        .filter(|agent| crate::shim::is_command(agent))
        .map(|agent| vec![agent.to_string()])
        .collect();
    if let Some(shell) = std::env::var("SHELL").ok().filter(|s| !s.is_empty()) {
        found.push(vec![shell]);
    }
    found
}

/// One line of the launcher.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Choice {
    /// An agent cctop left running in rmux, from this run or an earlier one.
    ///
    /// Boxed because a launcher row only needs four of a session's dozen fields
    /// — its name, where it works, what account it runs under, and whether
    /// somebody is already looking at it — and `Running` grew past the size
    /// where holding one of these inline doubles the enum. The box is per row,
    /// there are as many rows as there are live agents, and each is a handful of
    /// strings.
    Waiting(Box<crate::rmux::Running>),
    /// A command to start fresh.
    Start(Vec<String>),
}

impl Choice {
    pub fn label(&self) -> String {
        match self {
            // The rmux name is `cctop-<what>`; the prefix is true of every one
            // of them and so tells the reader nothing.
            Choice::Waiting(agent) => agent
                .name
                .strip_prefix("cctop-")
                .unwrap_or(&agent.name)
                .to_string(),
            Choice::Start(argv) => label_of(argv),
        }
    }

    /// Where picking this lands, when that is known and worth saying.
    ///
    /// A still-running agent brings its own: it has been working somewhere since
    /// before this launcher was opened, and `-c` cannot move it. Saying so is the
    /// only way to tell two `claude`s apart when both are just called claude.
    pub fn cwd(&self) -> Option<&Path> {
        match self {
            Choice::Waiting(agent) => agent.cwd.as_deref(),
            Choice::Start(_) => None,
        }
    }
}

/// What the launcher offers: the agents still running in rmux first, then the
/// commands that start a new one.
///
/// Agents outliving cctop is only half of the bargain — the other half is being
/// able to get back to them. Without this they survive somewhere unnameable,
/// reachable only by knowing to run `rmux attach` yourself, which is a worse
/// deal than the panes that simply died.
///
/// `open` is the rmux sessions already on screen in this cctop; they are left
/// out, since a second client onto one agent only makes the two panes argue
/// about the window size.
///
/// A session attached from *elsewhere* — a `rmux attach` in another terminal —
/// is still offered. It has the same problem, but hiding a running agent is the
/// worse of the two failures, so it is shown and labelled instead.
pub fn choices(open: &[String]) -> Vec<Choice> {
    crate::rmux::running()
        .into_iter()
        .filter(|agent| !open.contains(&agent.name))
        .map(|agent| Choice::Waiting(Box::new(agent)))
        .chain(harnesses().into_iter().map(Choice::Start))
        .collect()
}

/// How a command picked from the launcher is named on screen: the command as
/// typed, minus any path, which matches what [`shim::host`](crate::shim::host)
/// calls it once it is running.
pub fn label_of(argv: &[String]) -> String {
    // `env VAR=value claude` is a `claude` tab. The prefix is how the agent was
    // started, which is plumbing, and naming a tab after its plumbing is the
    // same mistake as calling one `rmux new-session -A -s cctop-claude`.
    crate::config::without_launch_prefix(argv)
        .iter()
        .map(|arg| arg.rsplit('/').next().unwrap_or(arg))
        .collect::<Vec<_>>()
        .join(" ")
}

/// How one agent's screen says what it is doing.
///
/// Each harness ends its screen with a line of key hints, and the hints change
/// with the state: a dialog holding the turn offers a way to cancel it, a turn
/// in flight offers a way to interrupt it. The same words do not mean the same
/// thing across harnesses — `esc to cancel` is a permission prompt in Claude
/// Code and a turn in flight in Gemini — which is why this is a table per
/// harness rather than one list of phrases.
///
/// A rule is a set of phrases that must *all* appear in the last `lines`
/// non-empty lines, compared without case. Asking is tried before working, so
/// a prompt raised mid-turn is the prompt.
///
/// There are no idle phrases, on purpose. Codex keeps `? for shortcuts` on its
/// bottom line while it works, and between two steps of one turn draws a frame
/// with no working line at all — so a footer that *looks* idle is a flicker
/// away from a false bell. Idle is instead the absence of both, held still;
/// see [`Pane::read_screen`].
///
/// Only the bottom of the screen is read because the conversation is on the
/// same screen, and a reply that quotes one of these phrases — this comment,
/// read aloud — must not answer for the footer. The narrower the footer, the
/// fewer lines: Claude Code's is the last two.
///
/// Claude Code's phrases were captured from 2.1.283 and Codex's from 0.157.1,
/// both off real screens. The rest are distilled from herdr's detection
/// manifests (Apache-2.0,
/// github.com/herdrdev/herdr, `src/detect/manifests/`, 2026-09), keeping the
/// rules that are plain phrases and leaving out the ones that need a regex or
/// the terminal title.
///
/// ponytail: phrases, not herdr's rule engine; a harness that rewords its
/// footer reads as "nothing recognised" until its row here is updated, and the
/// quiet-screen fallback in [`Pane::read_screen`] carries it meanwhile.
struct Footer {
    harness: &'static str,
    lines: usize,
    asking: &'static [&'static [&'static str]],
    working: &'static [&'static [&'static str]],
}

const FOOTERS: &[Footer] = &[
    Footer {
        harness: "claude",
        lines: 2,
        // A permission prompt, an AskUserQuestion, the trust-this-folder question.
        asking: &[&["esc to cancel"]],
        working: &[&["esc to interrupt"]],
    },
    Footer {
        harness: "codex",
        lines: 10,
        asking: &[
            // An approval: `Would you like to run the following command?` over
            // `Press enter to confirm or esc to cancel`.
            &["press enter to confirm or esc to cancel"],
            &["would you like to run the following command?"],
            // Its startup questions: trust the hooks, update now.
            &["enter confirm · esc skip"],
            &["press enter to confirm or esc to go back"],
            &["update now", "skip until next version"],
            &["enter to submit answer"],
            &["enter to submit all"],
            &["allow command?"],
            &["do you trust the contents of this directory?"],
            &["[y/n]"],
            &["yes (y)"],
        ],
        // `• Working (12s • esc to interrupt)`, above the prompt box.
        working: &[&[" to interrupt)"]],
    },
    Footer {
        harness: "gemini",
        lines: 10,
        asking: &[
            &["apply this change"],
            &["allow execution"],
            &["waiting for user confirmation"],
            &["do you want to proceed"],
        ],
        working: &[&["esc to cancel"]],
    },
    Footer {
        harness: "opencode",
        lines: 10,
        asking: &[
            &["△ permission required"],
            &["esc dismiss", "enter confirm"],
            &["esc dismiss", "enter submit"],
        ],
        working: &[
            &["esc to interrupt"],
            &["ctrl+c to interrupt"],
            &["esc interrupt"],
            &["esc again to interrupt"],
        ],
    },
    Footer {
        harness: "cursor",
        lines: 8,
        asking: &[
            &["write to this file?", "proceed (y)"],
            &["run this command?"],
            &["skip (esc or n)"],
            &["(y) (enter)"],
            &["keep (n)"],
        ],
        working: &[&["ctrl+c to stop"]],
    },
    Footer {
        harness: "devin",
        lines: 8,
        asking: &[
            &["do you trust the authors of this directory?"],
            &["approve once", "esc cancel"],
        ],
        working: &[&["esc to interrupt"], &["guide devin while it works"]],
    },
    Footer {
        harness: "droid",
        lines: 8,
        asking: &[
            &["enter to select", "esc to cancel"],
            &["enter select", "esc cancel"],
        ],
        working: &[&["esc to stop"]],
    },
    Footer {
        harness: "pi",
        lines: 12,
        asking: &[],
        working: &[&["working..."]],
    },
];

/// Whether `harness` has a row in [`FOOTERS`] — the cheap half of the check a
/// reader makes before paying for the screen itself.
pub(crate) fn screenable(harness: &str) -> bool {
    FOOTERS.iter().any(|f| f.harness == harness)
}

/// What `harness`'s own footer says it is doing, when it says so plainly.
///
/// `None` both for a harness with no row in [`FOOTERS`] and for a screen none
/// of its rules match; [`Pane::read_screen`] tells the two apart.
pub(crate) fn screen_state(harness: &str, rows: &[String]) -> Option<crate::hook::Signal> {
    use crate::hook::Signal;
    let footer = FOOTERS.iter().find(|f| f.harness == harness)?;
    let bottom: Vec<String> = rows
        .iter()
        .map(|row| row.trim())
        .filter(|row| !row.is_empty())
        .rev()
        .take(footer.lines)
        .map(str::to_lowercase)
        .collect();
    let text = bottom.join("\n");
    let any = |rules: &[&[&str]]| rules.iter().any(|all| all.iter().all(|p| text.contains(p)));
    if any(footer.asking) {
        Some(Signal::NeedsInput)
    } else if any(footer.working) {
        Some(Signal::Busy)
    } else {
        None
    }
}

/// What a prompt on `harness`'s screen is asking for, when the prompt draws
/// the answer on it.
///
/// Read only once the screen has said it is asking — a `$ …` command line is a
/// normal thing to have on screen at a shell, and this is only called on the
/// screen that just matched a prompt. Codex puts the command it wants under
/// "Would you like to run…"; Claude Code's menu is numbered, so the question
/// and the tool's own detail are the rows above the highlighted option.
/// Whatever is found is verbatim screen text, one line and bounded: a summary
/// invented here would be shown next to an Allow button.
///
/// ponytail: claude and codex only. The other harnesses' prompts were seen,
/// not read for this — a guessed extraction beside a real answer is worse
/// than none.
pub(crate) fn screen_ask(harness: &str, rows: &[String]) -> Option<String> {
    // Wider than the footer: Claude's question box and Codex's `$` line sit a
    // few rows above the hint row the recognizer matches on.
    const ASK_ROWS: usize = 15;
    let bottom: Vec<String> = rows
        .iter()
        .map(|row| row.trim().to_string())
        .filter(|row| !row.is_empty())
        .rev()
        .take(ASK_ROWS)
        .collect();
    let found = match harness {
        "codex" => bottom.iter().find_map(|row| {
            row.strip_prefix('$')
                .map(str::trim)
                .filter(|s| !s.is_empty())
                .map(String::from)
        })?,
        "claude" => {
            // The highlighted option (`❯ 1. Yes`) is the menu's top edge; the
            // question and the tool's box are the rows above it. The first one
            // met from the bottom is the prompt's — a `❯` in the conversation
            // above is never the nearer one.
            let top = bottom
                .iter()
                .position(|row| row.starts_with('❯') || row.starts_with('›'))?;
            let mut detail: Vec<String> = bottom[top + 1..]
                .iter()
                .map(|row| unbox(row))
                .filter(|row| !row.is_empty())
                // Further up than this is the conversation, not the prompt.
                .take(3)
                .collect();
            detail.reverse();
            match detail.is_empty() {
                true => return None,
                false => detail.join(" — "),
            }
        }
        _ => return None,
    };
    Some(crate::util::truncate(&found, crate::hook::MAX_ASK))
}

/// A row's box-drawing edges removed, for what the box says rather than draws.
fn unbox(row: &str) -> String {
    row.trim_matches(|c: char| "╭╮╰╯─│ ".contains(c))
        .trim()
        .to_string()
}

/// The harness a rmux session name or a pane label starts with, as one word.
///
/// `cctop-<harness>-…` is how every session is named at creation, whether it
/// was launched fresh or resumed; a label is the command, so its first word.
pub(crate) fn harness_of(name: &str) -> &str {
    name.strip_prefix("cctop-")
        .unwrap_or(name)
        .split(['-', ' ', '·'])
        .next()
        .unwrap_or_default()
}

/// Whether `argv` starts one of the agents cctop knows about.
///
/// Asked of the same list the aliases are built from, so a harness cctop can
/// shim is one it will read a turn off — and anything else, the login shell
/// included, is a terminal cctop is merely holding.
fn starts_an_agent(argv: &[String]) -> bool {
    // Through `label_of` so that `env FOO=1 claude` is still claude, which is
    // exactly how the profile-carrying launches spell themselves.
    let label = label_of(argv);
    let Some(command) = label.split_whitespace().next() else {
        return false;
    };
    crate::alias::AGENTS
        .split_whitespace()
        .any(|agent| agent == command)
}

#[cfg(test)]
mod tests {
    /// The screens below are Claude Code 2.1.283's own, captured from a real
    /// session: at its prompt, mid-turn, on a permission prompt and on an
    /// AskUserQuestion — plus a reply quoting the phrases, which must not count.
    /// One footer per state for every other harness, spelled the way herdr's
    /// manifests say they are drawn — so a row edited into the table is checked
    /// against the words it was meant to catch, and the harnesses whose words
    /// overlap stay apart.
    #[test]
    fn each_harness_is_read_by_its_own_words() {
        use crate::hook::Signal::{Busy, NeedsInput};
        let read = |harness: &str, text: &str| {
            let rows: Vec<String> = text.lines().map(String::from).collect();
            super::screen_state(harness, &rows)
        };
        let cases = [
            (
                "codex",
                "Allow command?\n  Yes (y)   No (n)",
                Some(NeedsInput),
            ),
            ("gemini", "⠏ Reading files (esc to cancel, 3s)", Some(Busy)),
            (
                "gemini",
                "│ Allow execution of: 'touch x'?\n│ ● 1. Yes",
                Some(NeedsInput),
            ),
            ("opencode", "■■■■⬝⬝⬝⬝  esc interrupt", Some(Busy)),
            (
                "opencode",
                "△ Permission required\n  bash touch x",
                Some(NeedsInput),
            ),
            ("cursor", "⬢ Generating  ctrl+c to stop", Some(Busy)),
            (
                "cursor",
                "Run this command?\n → Run (once) (y)\n   Skip (esc or n)",
                Some(NeedsInput),
            ),
            ("devin", "Running tools · esc to interrupt", Some(Busy)),
            (
                "devin",
                "Approve once\nSelect · Confirm · Esc cancel",
                Some(NeedsInput),
            ),
            ("devin", "❭ \n  Context: 12% used", None),
            ("droid", "⠋ Thinking…  (esc to stop)", Some(Busy)),
            (
                "droid",
                "> Yes, allow\n  No, cancel\nEnter to select · ↑↓ to navigate · Esc to cancel",
                Some(NeedsInput),
            ),
            ("pi", "── ⠋ Working... ──", Some(Busy)),
            ("pi", "> hello", None),
            ("aider", "esc to interrupt", None),
        ];
        for (harness, text, want) in cases {
            assert_eq!(read(harness, text), want, "{harness}: {text:?}");
        }
    }

    /// Codex 0.157.1's own screens: `? for shortcuts` on the bottom line
    /// throughout, which is why it is not taken for idle; the working line
    /// above the prompt box; and an approval.
    #[test]
    fn codex_says_what_it_is_doing_above_its_prompt() {
        use crate::hook::Signal;
        let screen = |text: &str| {
            let rows: Vec<String> = text.lines().map(String::from).collect();
            super::screen_state("codex", &rows)
        };
        let busy = "\
› Run the shell command: touch hello.txt
• I’ll create hello.txt in the current workspace.
◦ Working (5s • esc to interrupt)

› Ask Codex to do anything

  GPT-5.6-Terra high · ~/play · No changes
  ← for agents · ? for shortcuts";
        assert_eq!(screen(busy), Some(Signal::Busy));
        let between = "\
› Run the shell command: touch hello.txt
• I’ll create hello.txt in the current workspace.

› Ask Codex to do anything

  GPT-5.6-Terra high · ~/play · No changes
  ← for agents · ? for shortcuts";
        assert_eq!(screen(between), None, "mid-turn, and no phrase says so");
        let approval = "\
• Running touch ../outside.txt
  Would you like to run the following command?
  $ touch ../outside.txt
› 1. Yes, proceed (y)
  2. Yes, and don't ask again for commands that start with `touch ../outside.txt` (p)
  3. No, and tell Codex what to do differently (esc)
  Press enter to confirm or esc to cancel";
        assert_eq!(screen(approval), Some(Signal::NeedsInput));
        let hooks = "\
  Hooks need review
› 1. Review hooks
  2. Trust all and continue
  3. Continue without trusting (hooks won't run)
  enter confirm · esc skip";
        assert_eq!(screen(hooks), Some(Signal::NeedsInput));
    }

    #[test]
    fn claude_says_what_it_is_doing_in_its_footer() {
        use crate::hook::Signal;
        let screen = |text: &str| {
            let rows: Vec<String> = text.lines().map(String::from).collect();
            super::screen_state("claude", &rows)
        };
        let idle = "\
────────────────────────────
❯ Try \"create a util logging.py that...\"
────────────────────────────
  ⚠ Transcript saving is off
  ⏸ manual mode on · ? for shortcuts

";
        assert_eq!(screen(idle), None, "idle is stillness, not a phrase");
        let busy = "\
✢ Quantumizing… (2s · thinking)
────────────────────────────
❯
────────────────────────────
  ⚠ Transcript saving is off
  ⏸ manual mode on · esc to interrupt";
        assert_eq!(screen(busy), Some(Signal::Busy));
        let permission = "\
 Do you want to proceed?
 ❯ 1. Yes
   2. Yes, and always allow access to this folder
   3. No

 Esc to cancel · Tab to amend
";
        assert_eq!(screen(permission), Some(Signal::NeedsInput));
        let question = "\
❯ 1. Tea
  2. Coffee
────────────────────────────
  4. Chat about this
Enter to select · ↑/↓ to navigate · Esc to cancel";
        assert_eq!(screen(question), Some(Signal::NeedsInput));
        let quoted = "\
⏺ The footer reads `Esc to cancel` on a prompt and `esc to interrupt` mid-turn.
  That is how the state is told.
❯ fix the parser
  ⏸ manual mode on";
        assert_eq!(screen(quoted), None, "a reply is not the footer");
        assert_eq!(screen(""), None);
    }

    /// A resumed tab is named after its session, not its command.
    ///
    /// `claude --resume 4ebf1ab4-2ef8-4fb2-a7d5-d445b5026dc9` is 45 characters
    /// of tab bar whose only variable part is a uuid nobody reads. The label
    /// the resume path builds is what the bar should show instead.
    #[test]
    fn a_resume_command_is_not_a_tab_name() {
        let argv: Vec<String> = ["claude", "--resume", "4ebf1ab4-2ef8-4fb2-a7d5-d445b5026dc9"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        // What the command alone would give: the uuid, in full.
        let from_argv = super::label_of(&argv);
        assert!(from_argv.contains("4ebf1ab4"), "{from_argv}");
        assert!(from_argv.chars().count() > 40, "{from_argv}");

        // What the resume path builds instead: the agent, then the session.
        let label = format!(
            "{} · {}",
            argv[0],
            crate::util::truncate("Improve super cctop", super::super::launch::TAB_LABEL_CHARS)
        );
        assert_eq!(label, "claude · Improve super cctop");
        assert!(!label.contains("4ebf1ab4"));
    }

    /// A tab launched under a profile is still a `claude` tab. The `env` prefix
    /// is how it was started, and naming a tab after its plumbing is the same
    /// mistake as calling one `rmux new-session -A -s cctop-claude`.
    #[test]
    fn a_profile_prefix_does_not_become_the_tab_name() {
        let argv: Vec<String> = ["env", "CLAUDE_CONFIG_DIR=/home/x/.claude-work", "claude"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        assert_eq!(label_of(&argv), "claude");

        // Several, and a flag the agent owns, which must survive.
        let argv: Vec<String> = ["env", "A=1", "B=2", "claude", "--resume"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        assert_eq!(label_of(&argv), "claude --resume");

        // Codex is selected by a different variable and must strip the same.
        let argv: Vec<String> = ["env", "CODEX_HOME=/home/x/.codex-work", "codex"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        assert_eq!(label_of(&argv), "codex");

        // A command that merely happens to be called `env` keeps its name.
        assert_eq!(label_of(&["env".to_string()]), "env");
        assert_eq!(label_of(&["claude".to_string()]), "claude");
    }
    use super::*;

    /// The launcher must never offer something that isn't there — picking it
    /// would open a tab onto an immediate "command not found".
    #[test]
    fn the_launcher_only_offers_commands_that_exist() {
        for argv in harnesses() {
            assert!(
                crate::shim::is_command(&argv[0]),
                "offered a command that is not installed: {argv:?}"
            );
        }
    }

    /// The launcher puts still-running agents above the commands that start a
    /// new one, and never offers a second pane onto an agent already on screen.
    #[test]
    fn the_launcher_offers_what_is_running_before_what_is_new() {
        let starts = harnesses().len();
        let plain = choices(&[]);
        // Whatever rmux happens to be holding, the "start new" block is intact
        // and comes last.
        assert_eq!(
            plain
                .iter()
                .filter(|c| matches!(c, Choice::Start(_)))
                .count(),
            starts
        );
        let first_start = plain
            .iter()
            .position(|c| matches!(c, Choice::Start(_)))
            .unwrap_or(0);
        assert!(
            plain[first_start..]
                .iter()
                .all(|c| matches!(c, Choice::Start(_))),
            "a running agent appeared below the new-launch commands"
        );

        // An agent already on screen is not offered again.
        if let Some(Choice::Waiting(agent)) = plain.iter().find(|c| matches!(c, Choice::Waiting(_)))
        {
            let hidden = choices(std::slice::from_ref(&agent.name));
            assert!(!hidden.contains(&Choice::Waiting(agent.clone())));
        }
    }

    /// A session as rmux would describe it, with `ago` seconds since it last
    /// drew anything.
    fn session(name: &str, label: Option<&str>, ago: u64) -> crate::rmux::Running {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);
        crate::rmux::Running {
            name: name.to_string(),
            pid: Some(4321),
            cwd: None,
            attached: false,
            activity: Some(now.saturating_sub(ago)),
            label: label.map(str::to_string),
            profile: None,
            order: None,
            state: None,
            color: None,
            tab: None,
            pane: None,
            axis: None,
        }
    }

    /// The point of writing the state onto the session: a cctop that was not
    /// running when the agent asked still finds the question waiting for it.
    ///
    /// `known` answers `None` throughout, which is what a fresh cctop knows —
    /// the live event went over a socket to whoever was listening at the time,
    /// and that was somebody else. Before the session carried it, the only
    /// thing left to go on was the activity clock, and a held prompt over a
    /// still screen reads there as merely idle.
    #[test]
    fn a_tab_finds_a_question_that_was_asked_before_this_cctop_started() {
        let recorded = |signal, ago: u64| {
            let mut agent = session("cctop-x", Some("claude"), 0);
            agent.state = Some(crate::rmux::State {
                signal,
                at: crate::rmux::now_secs().saturating_sub(ago),
            });
            Tab::for_agent(&agent)
        };
        let unheard = &|_| None;

        assert_eq!(
            recorded(crate::hook::Signal::NeedsInput, 300).attention(false, unheard),
            Some(Attention::NeedsInput),
            "the session remembered what this cctop never heard"
        );
        assert_eq!(
            recorded(crate::hook::Signal::Idle, 300).attention(false, unheard),
            Some(Attention::Idle),
            "and a finished turn is still the quieter of the two"
        );
        assert_eq!(
            recorded(crate::hook::Signal::Busy, 5).attention(false, unheard),
            None,
            "an agent recorded as working is left alone"
        );

        // A working claim nobody has confirmed for hours is the shape a session
        // killed mid-turn leaves behind. It lapses back to the screen-reading
        // fallback rather than asserting itself forever — and this tab's clock
        // says it last drew a moment ago, so that fallback is "not idle".
        assert_eq!(
            recorded(crate::hook::Signal::Busy, 3 * 3_600).attention(false, unheard),
            None,
        );

        // A live report is fresher than anything written down, and wins.
        let stale = recorded(crate::hook::Signal::NeedsInput, 300);
        assert_eq!(
            stale.attention(false, &|_| Some(crate::hook::Signal::Busy)),
            None,
            "this cctop heard the agent go back to work"
        );
    }

    /// A pane holding `label`, drawn `ago` seconds back.
    fn pane(label: &str, is_agent: bool, ago: u64) -> Pane {
        Pane {
            hosted: None,
            rmux: None,
            resumed: None,
            profile: None,
            pid: 4321,
            agent: None,
            asked_at: None,
            label: label.into(),
            is_agent,
            view: crate::attach::Attach::for_test(),
            drew_at: Instant::now() - Duration::from_secs(ago),
        }
    }

    /// A pane whose agent rang, with everything else saying it is busy.
    fn ringing_tab(bell: &[u8]) -> Tab {
        let mut pane = pane("claude", true, 0);
        pane.view.parser.process(bell);
        Tab::new(pane)
    }

    /// The launcher offers the login shell, and a shell has no turns to finish.
    ///
    /// Every inference in `attention` reads a still screen as an agent waiting
    /// for you. A shell at its prompt is still by definition, so a tab opened
    /// for `git diff` — or to run cctop in — went green two seconds after the
    /// last keystroke and sat there claiming an agent wanted something.
    #[test]
    fn a_tab_that_is_not_an_agent_reports_no_turn() {
        let unreported = &|_: u32| None;
        assert_eq!(
            Tab::new(pane("zsh", false, 5)).attention(false, unreported),
            None,
            "a quiet shell is a shell, not a finished turn"
        );
        assert_eq!(
            Tab::new(pane("claude", true, 5)).attention(false, unreported),
            Some(Attention::Idle),
            "and the same silence from an agent still means what it did"
        );

        // Nor does the permission-prompt shape apply: a tool in flight over a
        // still terminal is a question only where a terminal holds an agent.
        assert_eq!(
            Tab::new(pane("zsh", false, 5))
                .attention(false, &|_| Some(crate::hook::Signal::Acting)),
            None
        );

        // The bell survives, because that is the thing in the pane asking
        // outright rather than cctop reading its pixels.
        let mut rang = pane("zsh", false, 5);
        rang.view.parser.process(b"\x07");
        assert_eq!(
            Tab::new(rang).attention(false, unreported),
            Some(Attention::NeedsInput)
        );
    }

    /// What counts as an agent is the list the aliases are built from, so a
    /// harness cctop can shim is one it will read a turn off.
    #[test]
    fn an_agent_is_recognised_through_the_way_it_was_launched() {
        let argv = |s: &str| -> Vec<String> { s.split(' ').map(str::to_string).collect() };
        assert!(starts_an_agent(&argv("claude")));
        assert!(starts_an_agent(&argv("claude --resume 4ebf1ab4")));
        assert!(starts_an_agent(&argv("/usr/local/bin/codex")));
        // How a launch under a named account spells itself.
        assert!(starts_an_agent(&argv(
            "env CLAUDE_CONFIG_DIR=/tmp/x claude"
        )));
        assert!(!starts_an_agent(&argv("/bin/zsh")));
        assert!(!starts_an_agent(&argv("")));
    }

    /// The bell outranks every inference. A harness rings when it is blocked on
    /// you, and it keeps drawing its spinner and reporting itself as working
    /// while it waits — which is exactly the state the rest of `attention` reads
    /// as "leave it alone". Before the bell was kept, a tab blocked on a
    /// permission prompt was drawn as busy for as long as it sat there.
    ///
    /// What it does not outrank is the agent saying its turn is over. Claude
    /// Code rings the idle nudge a minute after `Stop`, down the same bell, and
    /// a finished turn drawn as a held question is the false alarm that teaches
    /// people to ignore the amber.
    #[test]
    fn an_agent_that_rang_outranks_looking_busy() {
        let ringing = ringing_tab(b"\x07");
        assert_eq!(
            ringing.attention(false, &|_| Some(crate::hook::Signal::Busy)),
            Some(Attention::NeedsInput),
        );
        assert_eq!(
            ringing.attention(false, &|_| Some(crate::hook::Signal::Idle)),
            Some(Attention::Idle),
            "the idle nudge was read as a question"
        );
        // A tool call held over a rung bell is the permission prompt itself.
        assert_eq!(
            ringing.attention(false, &|_| Some(crate::hook::Signal::Acting)),
            Some(Attention::NeedsInput),
        );

        // The control: the same freshly drawn pane, silent, is left alone.
        let quiet = ringing_tab(b"thinking");
        assert_eq!(
            quiet.attention(false, &|_| Some(crate::hook::Signal::Busy)),
            None,
        );

        // And the pane you are looking at is never the one blinking at you.
        assert_eq!(
            ringing.attention(true, &|_| Some(crate::hook::Signal::Busy)),
            None,
        );
    }

    /// The point of writing the label onto the session: two cctops showing the
    /// same agent must call it the same thing. The one that started it knows the
    /// conversation's title; every other one has only the session name, which
    /// for a resume is a sanitised uuid.
    #[test]
    fn a_shared_tab_is_called_what_the_cctop_that_started_it_called_it() {
        let tab = Tab::for_agent(&session(
            "cctop-claude-4ebf1ab4-2ef8-4fb2-a7d5-d445b5026dc9",
            Some("claude · Improve super cctop"),
            0,
        ));
        assert!(tab.detached());
        assert_eq!(tab.title(), "claude · Improve super cctop");

        // Nothing recorded — an agent left by a cctop older than this. The
        // session name stands in, minus the prefix every one of them carries.
        let tab = Tab::for_agent(&session("cctop-claude-32cca860", None, 0));
        assert_eq!(tab.title(), "claude-32cca860");
    }

    /// Switching tabs must not silently move an agent to another account.
    ///
    /// `go_to_tab` trades the pane you leave for a `Shared` and trades it back
    /// when you return, and a tab this cctop never launched is built from the
    /// session alone. The account used to survive neither, and a lost account is
    /// not "unknown" on the border — it reads as the default one, so a pane
    /// running as a second login was shown the first login's remaining budget,
    /// which is the figure you decide by.
    #[test]
    fn the_account_a_pane_runs_as_survives_a_tab_switch() {
        let mut running = session("cctop-claude-32cca860", Some("claude"), 0);
        running.profile = Some("work".into());
        let adopted = Tab::for_agent(&running);
        assert_eq!(
            adopted.shared.as_ref().and_then(|s| s.profile.as_deref()),
            Some("work"),
        );

        // And nothing invented for the ordinary account, which writes no option
        // and so reads back as none.
        let plain = Tab::for_agent(&session("cctop-claude-4e2b1c90", Some("claude"), 0));
        assert_eq!(plain.shared.as_ref().and_then(|s| s.profile.clone()), None);
    }

    /// A tab this cctop holds no client on still has to blink: that is the whole
    /// point of showing another cctop's agents. It has no screen to read, so the
    /// hooks answer, and rmux's own record of the session answers when they
    /// cannot.
    #[test]
    fn an_unwatched_tab_still_says_when_its_agent_wants_you() {
        let quiet = Tab::for_agent(&session("cctop-claude-a", None, 30));
        let busy = Tab::for_agent(&session("cctop-claude-b", None, 0));
        let pid = quiet.shared.as_ref().and_then(|s| s.pid).expect("pid");

        // A held question outranks everything, and being reported as working
        // outranks a session that merely looks quiet.
        assert_eq!(
            quiet.attention(false, &|_| Some(crate::hook::Signal::NeedsInput)),
            Some(Attention::NeedsInput)
        );
        assert_eq!(
            quiet.attention(false, &|_| Some(crate::hook::Signal::Busy)),
            None
        );
        // Asked about the agent's pid, which is the only one its hooks mention.
        assert_eq!(
            quiet.attention(false, &|asked| (asked == pid)
                .then_some(crate::hook::Signal::NeedsInput)),
            Some(Attention::NeedsInput)
        );

        // A tool call in flight is working *and* a question, depending on
        // whether the terminal is still: that is the shape of a permission
        // prompt, which nothing else reports in time to blink about.
        assert_eq!(
            quiet.attention(false, &|_| Some(crate::hook::Signal::Acting)),
            Some(Attention::NeedsInput)
        );
        assert_eq!(
            busy.attention(false, &|_| Some(crate::hook::Signal::Acting)),
            None,
            "an agent still repainting mid-tool is working, not asking"
        );

        // No hooks: rmux's last-output time is the fallback the missing screen
        // would have provided.
        let unreported = |_: u32| None;
        assert_eq!(quiet.attention(false, &unreported), Some(Attention::Idle));
        assert_eq!(busy.attention(false, &unreported), None);
    }

    /// A detached tab is not an empty one. `reap` reporting it as finished would
    /// have every cctop drop the tabs it is not looking at, one tick after it
    /// stopped looking.
    #[test]
    fn a_detached_tab_is_not_reaped() {
        let mut tab = Tab::for_agent(&session("cctop-claude-a", None, 0));
        assert!(
            !tab.reap(&mut Vec::new()),
            "a shared tab was reaped for having no pane"
        );
        // Once it stands for nothing, it is nothing.
        tab.shared = None;
        assert!(tab.reap(&mut Vec::new()));
    }

    /// A still-running agent in the launcher, as rmux would have described it.
    fn waiting(name: &str) -> Choice {
        Choice::Waiting(Box::new(crate::rmux::Running {
            pid: Some(4321),
            cwd: Some(std::path::PathBuf::from("/home/x/proj")),
            ..crate::rmux::Running::unrecorded(name)
        }))
    }

    /// The tab is named after the agent, not the plumbing that carries it.
    #[test]
    fn a_choice_is_named_for_the_agent_not_the_wrapper() {
        assert_eq!(waiting("cctop-claude-32cca860").label(), "claude-32cca860");
        assert_eq!(
            Choice::Start(vec!["/usr/bin/claude".into()]).label(),
            "claude"
        );
    }

    /// A running agent brings the directory it has been working in; a fresh one
    /// has none of its own, and takes whatever the launcher was opened on.
    #[test]
    fn only_a_running_agent_names_its_own_directory() {
        assert_eq!(
            waiting("cctop-claude-abc").cwd(),
            Some(Path::new("/home/x/proj"))
        );
        assert_eq!(Choice::Start(vec!["claude".into()]).cwd(), None);
    }

    /// The thing rmux breaks if nobody accounts for it: the pid cctop hosts is
    /// the rmux client, so everything the agent reports about itself is filed
    /// under a pid nothing on this side would ever ask about. A tab that asked
    /// the wrong one would fall back to reading the screen for exactly the panes
    /// where the agent is talking.
    #[test]
    fn a_rmux_backed_tab_asks_about_the_agent_and_not_the_client() {
        // A pane standing in for a rmux client: what cctop hosts is one pid, and
        // the agent behind it is another.
        let (_child, client_pid) = crate::shim::test_session(&["sh", "-c", "sleep 30"], (80, 24));
        let mut pane = Pane::view_of(client_pid, "claude".into()).expect("attach");
        pane.rmux = Some("cctop-claude-abc".into());
        let agent_pid = client_pid + 1_000;
        pane.agent = Some(agent_pid);
        assert_eq!(pane.agent(), agent_pid);
        assert!(pane.outlives_cctop());

        let mut tab = Tab::new(pane);
        // Focus is elsewhere, so the pane is allowed to ask for attention.
        tab.focus = 1;

        // The agent says it is blocked on a question. It arrives under the
        // agent's pid, which is the only pid its hooks ever mention.
        assert_eq!(
            tab.attention(true, &|pid| (pid == agent_pid)
                .then_some(crate::hook::Signal::NeedsInput)),
            Some(Attention::NeedsInput)
        );
        // The client's pid says nothing about the agent, and must not be taken
        // for it — this is the assertion the fix exists for.
        assert_ne!(
            tab.attention(true, &|pid| (pid == client_pid)
                .then_some(crate::hook::Signal::NeedsInput)),
            Some(Attention::NeedsInput)
        );

        // Reported as working: the screen is irrelevant, however long the client
        // has sat still.
        assert_eq!(
            tab.attention(true, &|pid| (pid == agent_pid)
                .then_some(crate::hook::Signal::Busy)),
            None
        );
    }

    /// A pane whose agent is still drawing must not claim to be idle, a held
    /// question must outrank a finished turn, and the tab you are looking at
    /// must stay quiet — blinking the title of the pane in front of you is
    /// noise, and it is the case that fires most often.
    #[test]
    fn a_tab_asks_for_attention_only_when_it_has_something_you_cannot_see() {
        let mut kids = Vec::new();
        let mut pane = |script: &str| {
            let (child, pid) = crate::shim::test_session(&["sh", "-c", script], (80, 24));
            kids.push(child);
            (pid, Pane::view_of(pid, "agent".into()).expect("attach"))
        };
        // One agent that keeps painting, one that drew once and went quiet.
        let (busy_pid, busy) = pane("while :; do printf '.'; sleep 0.2; done");
        let (quiet_pid, quiet) = pane("printf 'done'; sleep 30");

        let mut tab = Tab::new(busy);
        tab.panes.push(quiet);
        let unreported = |_: u32| None;

        // Both panes have just been created, so neither has been quiet yet.
        assert_eq!(tab.attention(false, &unreported), None);

        // Past the threshold, only the one that stopped drawing is idle.
        let deadline = Instant::now() + QUIET_IS_IDLE + Duration::from_secs(2);
        while Instant::now() < deadline {
            tab.pump();
            std::thread::sleep(Duration::from_millis(50));
        }
        assert_eq!(tab.attention(false, &unreported), Some(Attention::Idle));

        // The busy pane holding a question outranks the quiet one being idle.
        assert_eq!(
            tab.attention(false, &|pid| (pid == busy_pid)
                .then_some(crate::hook::Signal::NeedsInput)),
            Some(Attention::NeedsInput)
        );
        // Focused tab: the focused pane is excluded, so the quiet one is left.
        tab.focus = 0;
        assert_eq!(
            tab.attention(true, &|pid| (pid == busy_pid)
                .then_some(crate::hook::Signal::NeedsInput)),
            Some(Attention::Idle)
        );
        // Focus the quiet one instead: it is the only pane with anything to
        // report, and you are looking straight at it, so the tab stays quiet.
        tab.focus = 1;
        assert_eq!(tab.attention(true, &unreported), None);

        drop(tab);
        for child in &mut kids {
            let _ = child.kill();
            let _ = child.wait();
        }
        for pid in [busy_pid, quiet_pid] {
            let _ = crate::shim::socket_path(pid).map(std::fs::remove_file);
        }
    }

    /// The trade that keeps several cctops off one rmux window: the tab you
    /// leave gives up its client and keeps everything needed to take one back.
    /// Only rmux-backed panes may do it — a pty cctop owns would be *ended* by
    /// this — and a split of them detaches whole, keeping each session's place.
    #[test]
    fn leaving_a_rmux_tab_gives_up_its_client_and_nothing_else() {
        let (mut child, pid) = crate::shim::test_session(&["sh", "-c", "sleep 30"], (80, 24));
        let mut pane = Pane::view_of(pid, "claude · Improve super cctop".into()).expect("attach");
        pane.rmux = Some("cctop-claude-abc".into());
        let agent_pid = pid + 1_000;
        pane.agent = Some(agent_pid);

        let mut tab = Tab::new(pane);
        assert!(tab.detach());
        assert!(tab.detached());
        let shared = tab.shared.clone().expect("nothing was kept");
        assert_eq!(shared.name, "cctop-claude-abc");
        // The label survives, so the tab does not rename itself on the way out —
        // and the agent's pid does, so it can still blink.
        assert_eq!(shared.label, "claude · Improve super cctop");
        assert_eq!(shared.pid, Some(agent_pid));
        assert_eq!(tab.title(), "claude · Improve super cctop");

        // A pane with no rmux behind it: dropping it is the kill, so it stays.
        let mut owned = Tab::new(Pane::view_of(pid, "claude".into()).expect("attach"));
        assert!(!owned.detach());
        assert!(owned.shared.is_none());

        // A split detaches too, and keeps both of its sessions: the whole point
        // of the second `Shared` is that a tab of two can be put down and taken
        // up again, in order, rather than coming back as two tabs that never met.
        let mut split = Tab::new(Pane::view_of(pid, "claude".into()).expect("attach"));
        split.panes[0].rmux = Some("cctop-claude-abc".into());
        split
            .panes
            .push(Pane::view_of(pid, "shell".into()).expect("attach"));
        split.panes[1].rmux = Some("cctop-zsh".into());
        assert!(split.detach());
        assert_eq!(split.panes.len(), 0);
        assert_eq!(
            split.shared.as_ref().map(|s| s.name.as_str()),
            Some("cctop-claude-abc")
        );
        assert_eq!(split.extra.len(), 1);
        assert_eq!(
            split.extra[0].name, "cctop-zsh",
            "the second pane kept its place"
        );
        // Both halves still answer, which is what a tab bar reads.
        assert_eq!(
            split.sessions().collect::<Vec<_>>(),
            ["cctop-claude-abc", "cctop-zsh"]
        );

        // One pane with no rmux behind it anywhere in the tab is still the kill,
        // so a split containing one keeps its clients rather than losing it.
        let mut mixed = Tab::new(Pane::view_of(pid, "claude".into()).expect("attach"));
        mixed.panes[0].rmux = Some("cctop-claude-abc".into());
        mixed
            .panes
            .push(Pane::view_of(pid, "local shell".into()).expect("attach"));
        assert!(!mixed.detach());
        assert_eq!(mixed.panes.len(), 2, "nothing was given up");

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

    /// The whole reason a tab has an identity recorded on rmux rather than
    /// implied by what happens to be attached: a split put down must come back
    /// up as the one tab it was, in the order it was, divided the same way.
    ///
    /// The bug: a tab was "whatever session is attached here", so a split had
    /// no form to be stored in — it could not be detached, and came back from a
    /// restart as two tabs that had never met, with the arrangement lost.
    #[test]
    fn a_split_survives_being_put_down_and_picked_up() {
        let (mut child, pid) = crate::shim::test_session(&["sh", "-c", "sleep 30"], (80, 24));
        let mut tab = Tab::new(Pane::view_of(pid, "claude".into()).expect("attach"));
        tab.panes[0].rmux = Some("cctop-claude-abc".into());
        let mut second = Pane::view_of(pid, "shell".into()).expect("attach");
        second.rmux = Some("cctop-zsh".into());
        tab.split(second, true);

        assert!(tab.detach(), "a split of rmux panes is now detachable");
        assert_eq!(
            tab.sessions().collect::<Vec<_>>(),
            ["cctop-claude-abc", "cctop-zsh"]
        );
        assert!(tab.stacked, "and it comes back divided the same way");

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

    /// `Tab::split` writes the tab's membership onto rmux, so the tab has an
    /// answer to "which sessions are mine" that does not live in this process.
    #[test]
    fn a_split_records_itself_onto_its_sessions() {
        if !crate::rmux::available() {
            eprintln!("skipping: rmux not installed");
            return;
        }
        // The daemon is machine-wide, so this serialises against the other
        // tests that talk to it.
        let _turn = crate::rmux::test_lock();
        let leader = format!("cctop-leader-{}", std::process::id());
        let other = format!("cctop-other-{}", std::process::id());
        for name in [&leader, &other] {
            let _ = crate::rmux::start_detached(&["sleep".into(), "30".into()], name, None);
        }
        let (mut child, pid) = crate::shim::test_session(&["sh", "-c", "sleep 30"], (80, 24));
        let mut tab = Tab::new(Pane::view_of(pid, "claude".into()).expect("attach"));
        tab.panes[0].rmux = Some(leader.clone());
        let mut second = Pane::view_of(pid, "shell".into()).expect("attach");
        second.rmux = Some(other.clone());
        tab.split(second, false);
        let read = |name: &str| crate::rmux::running().into_iter().find(|s| s.name == name);
        assert_eq!(
            read(&leader).as_ref().and_then(|s| s.tab.as_deref()),
            Some(&leader[..])
        );
        assert_eq!(
            read(&other).as_ref().and_then(|s| s.tab.as_deref()),
            Some(&leader[..])
        );
        // Ordered, so the listing can put them back the right way round.
        assert_eq!(read(&leader).as_ref().and_then(|s| s.pane), Some(0));
        assert_eq!(read(&other).as_ref().and_then(|s| s.pane), Some(1));
        assert_eq!(
            read(&other).map(|s| s.axis()),
            Some(crate::rmux::Axis::Side)
        );

        // A pane pulled back out of the tab stops claiming membership, rather
        // than pointing at a tab it is no longer part of.
        let mut alone = Tab::new(Pane::view_of(pid, "shell".into()).expect("attach"));
        alone.panes[0].rmux = Some(other.clone());
        alone.record_shape();
        assert_eq!(read(&other).and_then(|s| s.tab), None);

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

    #[test]
    fn a_command_is_labelled_by_its_name_not_its_path() {
        assert_eq!(label_of(&["/usr/bin/claude".into()]), "claude");
        assert_eq!(
            label_of(&["codex".into(), "--full-auto".into()]),
            "codex --full-auto"
        );
    }

    /// The colour a session records becomes the tab's, and a word this cctop
    /// does not know is no colour rather than a wrong one.
    #[test]
    fn a_sessions_colour_paints_its_tab() {
        let mut agent = session("cctop-claude-x", Some("claude"), 0);
        agent.color = Some("violet".to_string());
        assert_eq!(Tab::for_agent(&agent).color, Some(Hue::Violet));
        agent.color = Some("chartreuse".to_string());
        assert_eq!(
            Tab::for_agent(&agent).color,
            None,
            "a newer cctop's hue was guessed at"
        );
    }

    /// A tab keeps the colour it was painted even where there is no session to
    /// hold it: a pane on cctop's own pty is painted in memory only, which is
    /// as far as its name travels too.
    #[test]
    fn a_tab_with_no_session_still_keeps_its_colour() {
        let mut tab = Tab::new(pane("claude", true, 0));
        tab.recolor(Some(Hue::Cyan));
        assert_eq!(tab.color, Some(Hue::Cyan));
        tab.recolor(None);
        assert_eq!(tab.color, None);
    }

    /// The harness is read off the session name when there is one — it
    /// survives a rename, which is the whole point — and off the label's first
    /// word when there is not.
    #[test]
    fn a_panes_harness_comes_from_its_session_before_its_label() {
        let mut pane = pane("renamed work", true, 0);
        assert_eq!(pane.harness(), "renamed");
        pane.rmux = Some("cctop-claude-32cca860-b503".into());
        assert_eq!(pane.harness(), "claude", "a rename hid the harness");
        pane.rmux = Some("cctop-zsh".into());
        assert_eq!(pane.harness(), "zsh");
    }

    /// In a claude pane Home and End go in as the Ctrl- forms the agent binds
    /// to the top and bottom of the chat; anywhere else they are the
    /// line-editing keys they say, and a modified Home keeps its own meaning
    /// even there.
    #[test]
    fn home_and_end_are_promoted_only_in_a_claude_pane() {
        let claude = pane("claude", true, 0);
        for code in [KeyCode::Home, KeyCode::End] {
            let sent = claude.translate_key(KeyEvent::new(code, KeyModifiers::NONE));
            assert_eq!(sent.code, code);
            assert_eq!(sent.modifiers, KeyModifiers::CONTROL);
        }
        // Shift+Home is still "select to the start of the line", not a jump.
        let shifted = claude.translate_key(KeyEvent::new(KeyCode::Home, KeyModifiers::SHIFT));
        assert_eq!(shifted.modifiers, KeyModifiers::SHIFT);
        // And a shell's Home is the shell's own.
        let shell = pane("zsh", false, 0);
        let sent = shell.translate_key(KeyEvent::new(KeyCode::End, KeyModifiers::NONE));
        assert_eq!(sent.modifiers, KeyModifiers::NONE);
    }
}