taimux-cli 0.26.0

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

use std::collections::HashMap;

use taimux_core::{conv, state, tmux};

/// Is this transcript quiet enough to interrupt?
///
/// Two refusals: an unanswered `tool_use` as the very last record (a tool call is
/// still in flight), and any activity in the last 45 seconds. The second is
/// insurance for the first, because the screen reading is the most fragile thing
/// in this tool and a recently-touched transcript is worth leaving alone whatever
/// the screen said.
///
/// The `tool_use` test is a text match on the final line rather than a parse of
/// `.message.content[]`, which is the one approximation: an assistant turn whose
/// own prose quotes that key reads as busy. It fails toward "leave it alone", and
/// the recency guard covers the same ground, so the cost is a pane skipped rather
/// than a turn lost.
pub fn transcript_is_settled(text: &str, now: i64) -> Result<(), String> {
    let Some(last) = text.lines().rfind(|l| !l.trim().is_empty()) else {
        return Ok(()); // unknown shape: do not block on a guess
    };
    if taimux_core::json::field(last, "type") == "assistant"
        && (last.contains("\"type\":\"tool_use\"") || last.contains("\"type\": \"tool_use\""))
    {
        return Err("a tool call is still running".into());
    }
    let ts = taimux_core::json::field(last, "timestamp");
    if ts.is_empty() {
        return Ok(());
    }
    let Some(then) = parse_iso8601(&ts) else {
        return Ok(()); // unparseable: not evidence of anything
    };
    if now - then < 45 {
        return Err("active in the last 45s".into());
    }
    Ok(())
}

/// An ISO 8601 UTC timestamp to epoch seconds, which is all claude writes:
/// `2026-09-02T01:23:45.678Z`. The parse is `turn::epoch_ms`, which the state
/// reading needs to the millisecond; this only wants the second.
fn parse_iso8601(s: &str) -> Option<i64> {
    taimux_core::turn::epoch_ms(s).map(|ms| ms.div_euclid(1000))
}

/// Is the screen free of anything a Ctrl-C would mean something else to?
///
/// Applied even with `--include-busy`, because this is the one state where the
/// keystroke that starts a restart is also an answer to a question.
pub fn screen_has_no_dialog(screen: &str) -> Result<(), String> {
    if state::awaits_input(screen) {
        return Err("a dialog is waiting for an answer".into());
    }
    let tail: Vec<&str> = screen
        .lines()
        .filter(|l| !l.trim().is_empty())
        .rev()
        .take(4)
        .collect();
    if tail
        .iter()
        .any(|l| l.contains("Press Ctrl-C again to exit"))
    {
        return Err("a Ctrl-C is already half-pressed".into());
    }
    Ok(())
}

/// Is the prompt box empty?
///
/// Unsent text in it is work nobody has committed yet, and a restart would throw
/// it away. The non-breaking space claude pads the box with is stripped before
/// the check, or every box would look occupied.
pub fn screen_has_no_draft(screen: &str) -> Result<(), String> {
    let txt: Vec<&str> = screen.lines().filter(|l| !l.trim().is_empty()).collect();
    if txt.is_empty() {
        return Ok(());
    }
    let Some(box_line) = txt.iter().rev().find(|l| l.contains('❯')) else {
        return Err("no prompt box on screen".into());
    };
    let after = box_line.split_once('❯').map(|(_, r)| r).unwrap_or("");
    let rest: String = after
        .chars()
        .filter(|c| !c.is_whitespace() && *c != '\u{a0}')
        .collect();
    if rest.is_empty() {
        Ok(())
    } else {
        Err("unsent text in the prompt box".into())
    }
}

/// The rows claude needs before it draws its prompt box at all.
///
/// Measured against 2.1.278 in a tmux server of its own, a row at a time: at six
/// the `❯` is on screen and whatever has been typed into it with it, at five the
/// last row is the box's own top rule and neither the glyph nor the draft is
/// anywhere on the pane, and by three nothing of the box survives. Width does not
/// move it, 46, 54, 63, 80 and 213 columns all break in the same place.
///
/// A pane under it is not a pane in a strange state, it is a pane that cannot be
/// READ: the box, an unsent draft inside it and a dialog over it go off the
/// bottom together, so `screen_has_no_draft` refuses it and would go on refusing
/// it for as long as the pane stays that size. Nine of the fourteen outdated
/// panes on this machine were exactly that, which is how a sweep meant to clear
/// the outdated list offered to clear four of them.
const BOX_ROWS: usize = 6;

/// One tmux command line, as the arguments it is made of.
type Cmd = Vec<String>;

/// Getting a pane to a readable size, and putting the window back after.
type ZoomSteps = (Vec<Cmd>, Vec<Cmd>);

/// What it takes to read a pane at a size claude will draw on, and what it takes
/// to put the window back afterwards.
///
/// Split out from the running of it so the ORDER can be tested without a tmux to
/// run it against, the order being the whole of the difficulty. `None` when there
/// is nothing to gain: a pane already tall enough, or a window no taller than the
/// pane it holds, where zooming would hand it the rows it already has.
///
/// **Zoom rather than `resize-pane -y`**, and only a crowded window shows why:
/// seven panes in seventeen rows share eleven rows of content, six of which are
/// already spoken for by the others, so the tallest any one of them can be made
/// is five, one short of what the box needs. Zoom is the only growth that does
/// not have to come out of a sibling. It also leaves the LAYOUT untouched, so
/// putting the window back is a matter of the zoom flag and the active pane
/// rather than of replaying a layout string and hoping it lands.
fn zoom_steps(
    pane: &str,
    zoomed: bool,
    pane_rows: usize,
    window_rows: usize,
    active: &str,
    last: &str,
) -> Option<ZoomSteps> {
    if pane_rows >= BOX_ROWS || window_rows < BOX_ROWS || window_rows <= pane_rows {
        return None;
    }
    let cmd = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::<Cmd>();

    let mut go = Vec::new();
    // `-Z` toggles the WINDOW's zoom whatever pane it is pointed at, so on a
    // window that arrives zoomed the first one only ever switches the OTHER pane
    // off, and a second is what zooms this one. Two identical command lines in a
    // row is not a duplicated push.
    if zoomed {
        go.push(cmd(&["resize-pane", "-Z", "-t", pane]));
    }
    go.push(cmd(&["resize-pane", "-Z", "-t", pane]));

    let mut back = vec![cmd(&["resize-pane", "-Z", "-t", pane])];
    // Zooming made this pane the active one and pushed whatever was active into
    // the window's "last pane", so both have to go back, and in that order:
    // selecting the old last pane first leaves the old active one current with
    // the right pane behind it. `prefix + ;` is the user's binding, not taimux's
    // to spend. A pane that was active already has neither to restore.
    if active != pane {
        if !last.is_empty() && last != pane {
            back.push(cmd(&["select-pane", "-t", last]));
        }
        if !active.is_empty() {
            back.push(cmd(&["select-pane", "-t", active]));
        }
    }
    // A window that arrives zoomed is zoomed on its active pane by definition,
    // which is why that pane is never this one: it would have the window's full
    // height and be refused above.
    if zoomed && !active.is_empty() {
        back.push(cmd(&["resize-pane", "-Z", "-t", active]));
    }
    Some((go, back))
}

/// The commands that put the window back, run when this goes out of scope.
///
/// A guard rather than a line at the end of the function because the read
/// between the two can panic, and a window left zoomed on a pane nobody chose is
/// a worse outcome than a pane left unread.
struct Restoring(Vec<Cmd>);

impl Drop for Restoring {
    fn drop(&mut self) {
        for c in &self.0 {
            tmux::run(&c.iter().map(String::as_str).collect::<Vec<_>>());
        }
    }
}

/// One pane's screen, read at a size claude will draw its prompt box on.
///
/// `None` when the pane did not need it or the window cannot give it, in which
/// case nothing was touched and the screen already in hand is the best there is.
///
/// The wait is not padding. claude redraws on the SIGWINCH and does it fast,
/// measured at 13 to 16ms across six runs with the draft already in the first
/// readable frame, but a capture taken with no wait at all comes back with no box
/// at all: tmux does not reflow an old frame into the new rows, it hands over
/// what is there and claude fills it a moment later. So the poll is what makes
/// the read real, and its ceiling is thirty times the measurement rather than a
/// guess at it.
pub fn capture_zoomed(pane: &str) -> Option<String> {
    if !taimux_core::env::on("TAIMUX_ZOOM_TO_READ") {
        return None;
    }
    let geom = tmux::ask(&[
        "display-message",
        "-p",
        "-t",
        pane,
        "-F",
        "#{window_zoomed_flag}\t#{pane_height}\t#{window_height}\t#{window_id}",
    ])?;
    let g: Vec<&str> = geom.trim_end().split('\t').collect();
    if g.len() < 4 {
        return None;
    }
    let (zoomed, win) = (g[0] == "1", g[3]);
    let pane_rows: usize = g[1].parse().ok()?;
    let window_rows: usize = g[2].parse().ok()?;

    let mut active = String::new();
    let mut last = String::new();
    for l in tmux::ask(&[
        "list-panes",
        "-t",
        win,
        "-F",
        "#{pane_id}\t#{pane_active}\t#{pane_last}",
    ])?
    .lines()
    {
        let c: Vec<&str> = l.split('\t').collect();
        if c.len() < 3 {
            continue;
        }
        if c[1] == "1" {
            active = c[0].to_string();
        }
        if c[2] == "1" {
            last = c[0].to_string();
        }
    }

    let (go, back) = zoom_steps(pane, zoomed, pane_rows, window_rows, &active, &last)?;
    for c in &go {
        tmux::run(&c.iter().map(String::as_str).collect::<Vec<_>>());
    }
    let _restore = Restoring(back);

    let deadline = std::time::Instant::now() + std::time::Duration::from_millis(500);
    loop {
        let screen = tmux::capture(pane).unwrap_or_default();
        if screen.contains('❯') || std::time::Instant::now() >= deadline {
            return Some(screen);
        }
        std::thread::sleep(std::time::Duration::from_millis(10));
    }
}

/// The version a running process is executing, read from its own `/proc/exe`
/// rather than from the binary on `$PATH`: a long-lived session goes on running
/// the release it started under.
pub fn version_of_pid(pid: i32, versions_dir: &str) -> Option<String> {
    let exe = std::fs::read_link(format!("/proc/{}/exe", pid)).ok()?;
    let exe = exe.to_string_lossy();
    let exe = exe.trim_end_matches(" (deleted)"); // replaced by an update
    let prefix = format!("{}/", versions_dir);
    exe.strip_prefix(&prefix)
        .filter(|rest| !rest.is_empty())
        .map(|rest| rest.split('/').next().unwrap_or(rest).to_string())
}

/// One pane the plan will act on.
pub struct Planned {
    pub pane: String,
    pub target: String,
    /// The pane's own process: the session itself, or for a background session
    /// only agent view's client of it.
    pub pid: i32,
    /// What gets typed into the pane once that process has gone.
    pub cmd: String,
    pub title: String,
    pub via: String,
    /// The background session to respawn before `cmd` attaches the pane to it
    /// again, for a pane that only shows one. Two panes showing the same one
    /// both carry it, and it is respawned once.
    pub respawn: Option<String>,
}

/// A background session no pane shows, which the plan will respawn.
pub struct PlannedBg {
    /// The id `claude respawn` takes.
    pub id: String,
    /// Its worker now.
    pub pid: i32,
    pub name: String,
    pub via: String,
}

pub struct Plan {
    pub newver: String,
    pub launcher: String,
    pub go: Vec<Planned>,
    /// Background sessions no pane shows: see `plan`.
    pub go_bg: Vec<PlannedBg>,
    pub skipped: Vec<String>,
    /// Set when at least one pane was skipped for being unresolvable, which gets
    /// its own paragraph: it is the one skip the reader can act on.
    pub unresolved: bool,
}

pub struct Opts {
    pub include_busy: bool,
    pub only_panes: Vec<String>,
    pub force_transcript: Option<String>,
    pub self_pane: String,
}

/// Everything the plan needs from the outside, so it can be built against
/// fixtures as well as against a live machine.
pub trait Env {
    fn capture(&self, pane: &str) -> String;
    /// The same pane read at a size claude will draw its prompt box on, for the
    /// one that is too short to show one at the size it is.
    ///
    /// `None` by default, and for every fixture: a screen handed over by a test
    /// is already the screen that test means, and only the live implementation
    /// has a window to zoom.
    fn capture_zoomed(&self, _pane: &str) -> Option<String> {
        None
    }
    fn hook_state(&self, pane: &str, pid: i32) -> Option<String>;
    /// The permission mode on the session's hook line, the one its last turn
    /// ran in. `None` by default, and for every fixture that predates it.
    fn hook_mode(&self, _pane: &str, _pid: i32) -> Option<String> {
        None
    }
    /// What the session says it is doing, Claude Code's own status
    /// (`status::of`), which outranks the hook line wherever there is one.
    /// `None` by default, and for every fixture that predates it.
    fn own_state(&self, _pid: i32, _screen: &str) -> Option<state::State> {
        None
    }
    /// The background session this pane shows when another process runs it:
    /// an attach, or a pane whose conversation was moved into the background.
    fn elsewhere(&self, _pane: &str, _pid: i32) -> Option<Elsewhere> {
        None
    }
    /// Every background session running now, whether a pane shows it or not.
    /// None by default, and for every fixture that predates it.
    fn background(&self) -> Vec<BgSession> {
        Vec::new()
    }
    fn version_of_pid(&self, pid: i32) -> Option<String>;
    fn cwd_of(&self, pid: i32) -> Option<String>;
    fn argv_of(&self, pid: i32) -> Vec<String>;
    fn resolve(&self, pane: &str, cwd: &str, title: &str, pid: i32) -> Result<String, String>;
    fn read_transcript(&self, path: &str) -> Option<String>;
    fn now(&self) -> i64;
}

/// A session a pane shows while agent view's supervisor runs it, under
/// another pid: see `status::Via::elsewhere`.
pub struct Elsewhere {
    /// The id `claude attach` takes.
    pub id: String,
    /// The process running it.
    pub pid: i32,
    /// The version that process runs, which is the one the row shows.
    pub version: Option<String>,
    /// The transcript that session writes, for the settled check, or `None`
    /// where it is not where Claude Code puts it.
    pub transcript: Option<String>,
}

/// A background session as Claude Code's own files describe it, for the ones
/// no pane shows: there is no screen to read, so this is all there is.
#[derive(Clone)]
pub struct BgSession {
    /// The id `claude respawn` takes.
    pub id: String,
    /// The worker running it.
    pub pid: i32,
    /// The version that worker runs.
    pub version: Option<String>,
    pub name: String,
    /// What the session says it is doing.
    pub state: Option<state::State>,
    pub transcript: Option<String>,
    /// What the job's own record says it left going, or `None` where that
    /// record says nothing.
    pub in_flight: Option<taimux_core::status::InFlight>,
}

/// An id that can be typed into a shell as it stands. A job id is eight hex
/// digits and a session id a UUID, both read out of Claude Code's own files, so
/// anything else means those files say something this does not understand.
fn typable_id(id: &str) -> bool {
    !id.is_empty() && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
}

/// What a pane shows, and the transcript behind it, judged quiet enough to put
/// back: a dialog refuses even with `--include-busy`, an unsent draft and a
/// transcript still being written to only without it.
fn settled(screen: &str, transcript: Option<&str>, o: &Opts, e: &dyn Env) -> Result<(), String> {
    screen_has_no_dialog(screen)?;
    if o.include_busy {
        return Ok(());
    }
    screen_has_no_draft(screen)?;
    match transcript.and_then(|t| e.read_transcript(t)) {
        Some(text) => transcript_is_settled(&text, e.now()),
        None => Ok(()),
    }
}

/// Decide what to restart, and say why for everything else.
///
/// `agents` is `claude agents --json`, fetched by the caller and only when a
/// stale non-pane process actually needs naming: the CLI costs about three
/// seconds to start.
pub fn plan(
    rows: &str,
    newver: &str,
    launcher: &str,
    o: &Opts,
    e: &dyn Env,
    versions_dir: &str,
    agents: &dyn Fn() -> String,
) -> Plan {
    let mut p = Plan {
        newver: newver.to_string(),
        launcher: launcher.to_string(),
        go: Vec::new(),
        go_bg: Vec::new(),
        skipped: Vec::new(),
        unresolved: false,
    };
    let mut claimed: HashMap<String, String> = HashMap::new();
    // Every pane's agent pid, so the non-pane sweep below can tell a session
    // that has a pane from one that has not.
    let mut matched: Vec<i32> = Vec::new();

    for line in rows.lines() {
        let f: Vec<&str> = line.split('\t').collect();
        if f.len() < 7 || f[3] != "claude" {
            continue;
        }
        let (id, tgt, cwd, title) = (f[0], f[1], f[2], f[6]);
        let pid: i32 = f[4].parse().unwrap_or(0);

        let Some(ver) = (pid != 0).then(|| e.version_of_pid(pid)).flatten() else {
            p.skipped.push(format!(
                "{} {}  looks like claude but no session process was found under the pane",
                id, tgt
            ));
            continue;
        };
        matched.push(pid);
        if !o.only_panes.is_empty() && !o.only_panes.iter().any(|w| w == id) {
            continue;
        }

        // A pane showing a session that agent view's supervisor runs, where the
        // version that counts is its worker's, as the row shows it. Retyping the
        // pane cannot reach that worker: it would resume the transcript the pane
        // started on, branching a conversation that carries on elsewhere. The
        // supervisor restarts a worker that has fallen behind only when nothing
        // is attached to it (`respawnIfIdleStale`, 2.1.299), so this asks it to,
        // with `claude respawn`, and attaches the pane again afterwards. Every
        // guard below applies as it does to any pane: the screen is the
        // session's own, and so is the state `own_state` reads.
        let away = e.elsewhere(id, pid);
        if let Some(a) = &away {
            matched.push(a.pid);
        }
        let ver = match &away {
            Some(a) => a.version.clone().unwrap_or_else(|| "?".into()),
            None => ver,
        };

        if ver == newver {
            continue; // nothing to gain from interrupting it
        }
        if id == o.self_pane {
            p.skipped.push(format!(
                "{} {}  {}, this pane: restart it by hand (killing it would kill taimux)",
                id, tgt, ver
            ));
            continue;
        }

        let mut screen = e.capture(id);
        // A screen with no prompt box on it is either a session doing something
        // unusual or a pane too short to draw one, and those want opposite
        // answers: the first is a refusal, the second is a measurement that has
        // not been taken yet. Taking it costs the window a zoom for the
        // milliseconds claude needs to redraw, and buys a reading of the box, of
        // anything typed into it and of any dialog over it, none of which is on
        // the pane at the size it sits at. It happens here rather than after the
        // state check on purpose: `merge` is reading the same blank screen.
        if !screen.contains('❯') {
            if let Some(bigger) = e.capture_zoomed(id) {
                screen = bigger;
            }
        }
        let hook = e.hook_state(id, pid);
        let st = state::reading(&screen, e.own_state(pid, &screen), hook.as_deref());
        if st.as_str() != "idle" && !o.include_busy {
            p.skipped.push(format!(
                "{} {}  {}, {}: rerun when idle, or --include-busy",
                id,
                tgt,
                ver,
                st.as_str()
            ));
            continue;
        }
        // Idle is not the same as nothing to lose. A turn that left a shell or a
        // subagent running is over and its prompt is free, which is why the list
        // shows it idle, but that work runs as the session's children and dies
        // with it. This used to be one question, answered "working" for both, on
        // a pane whose two watchers were due to report hours later.
        if state::background(&screen, hook.as_deref()) && !o.include_busy {
            p.skipped.push(format!(
                "{} {}  {}, work still in flight: rerun once it reports back, or --include-busy",
                id, tgt, ver
            ));
            continue;
        }

        // A background session needs no ladder: its job id is what `claude
        // attach` and `claude respawn` both take, and the worker resumes its own
        // conversation.
        if let Some(a) = &away {
            if o.force_transcript.is_some() {
                p.skipped.push(format!(
                    "{} {}  {}, shows background session {}: --transcript does not apply, its worker is respawned instead",
                    id, tgt, ver, a.id
                ));
                continue;
            }
            if !typable_id(&a.id) {
                p.skipped.push(format!(
                    "{} {}  {}, shows background session {:?}, an id not safe to type",
                    id, tgt, ver, a.id
                ));
                continue;
            }
            if let Err(why) = settled(&screen, a.transcript.as_deref(), o, e) {
                p.skipped
                    .push(format!("{} {}  {}, not settled: {}", id, tgt, ver, why));
                continue;
            }
            p.go.push(Planned {
                pane: id.to_string(),
                target: tgt.to_string(),
                pid,
                cmd: format!("command claude attach {}", a.id),
                title: title.to_string(),
                via: format!(
                    "{} -> {}, background session {}, {}",
                    ver,
                    newver,
                    a.id,
                    st.as_str()
                ),
                respawn: Some(a.id.clone()),
            });
            continue;
        }

        let ccwd = e.cwd_of(pid).unwrap_or_else(|| cwd.to_string());
        let (transcript, via) = match &o.force_transcript {
            Some(t) => (t.clone(), "--transcript, given".to_string()),
            None => match e.resolve(id, &ccwd, title, pid) {
                Ok(t) => {
                    // resolve() hands back "<path>\t<why>"
                    let (path, why) = t.split_once('\t').unwrap_or((t.as_str(), ""));
                    (path.to_string(), why.to_string())
                }
                Err(why) => {
                    p.skipped
                        .push(format!("{} {}  {}, unresolved: {}", id, tgt, ver, why));
                    p.unresolved = true;
                    continue;
                }
            },
        };

        if let Err(why) = settled(&screen, Some(&transcript), o, e) {
            p.skipped
                .push(format!("{} {}  {}, not settled: {}", id, tgt, ver, why));
            continue;
        }

        if let Some(first) = claimed.get(&transcript) {
            p.skipped.push(format!(
                "{} {}  {}, resolves to the same transcript as {}",
                id, tgt, ver, first
            ));
            continue;
        }
        claimed.insert(transcript.clone(), id.to_string());

        // The mode it is in now, which a plain resume would not bring back: the
        // footer of the screen read above, else the mode of its last turn.
        let mode = conv::current_mode(&screen, e.hook_mode(id, pid).as_deref());
        let Some(cmd) = conv::build_cmd(&e.argv_of(pid), &transcript, &ccwd, cwd, mode.as_deref())
        else {
            p.skipped
                .push(format!("{} {}  {}, could not read its argv", id, tgt, ver));
            continue;
        };
        p.go.push(Planned {
            pane: id.to_string(),
            target: tgt.to_string(),
            pid,
            cmd,
            title: title.to_string(),
            via: format!("{} -> {}, {}, {}", ver, newver, via, st.as_str()),
            respawn: None,
        });
    }

    // Background sessions no pane shows, which only a whole plan looks for:
    // `--pane` names panes. Nothing to type into and no screen to read, so
    // `claude respawn` is the whole of the restart, and what stands in for the
    // screen is what Claude Code keeps itself: the session's own status, its
    // transcript, and the job's record of work it left running and of replies
    // saved for its next start. A worker some pane shows was dealt with above.
    if o.only_panes.is_empty() {
        for b in e.background() {
            if matched.contains(&b.pid) {
                continue;
            }
            matched.push(b.pid);
            let ver = b.version.clone().unwrap_or_else(|| "?".into());
            if ver == newver {
                continue;
            }
            match plan_bg(&b, o, e) {
                Ok(st) => p.go_bg.push(PlannedBg {
                    id: b.id.clone(),
                    pid: b.pid,
                    name: b.name.clone(),
                    via: format!("{} -> {}, no pane, {}", ver, newver, st.as_str()),
                }),
                Err(why) => p
                    .skipped
                    .push(format!("{} background  {}, {}", b.id, ver, why)),
            }
        }
    }

    // Stale claude processes that are not a pane's foreground job. Reported,
    // never touched: a restart types into a PANE, and these have none, so the
    // only useful thing to do about a stale one is name it. The naming costs a
    // `claude agents --json`, so it is fetched lazily and once.
    let mut agents_json: Option<String> = None;
    for np in nonpane_pids(&matched, versions_dir) {
        let Some(ver) = e.version_of_pid(np) else {
            continue;
        };
        if ver == newver {
            continue;
        }
        let j = agents_json.get_or_insert_with(agents);
        p.skipped.push(format!(
            "pid {}  {}, not a tmux pane: {}",
            np,
            ver,
            describe_nonpane(&e.argv_of(np), j)
        ));
    }
    p
}

/// Whether a background session no pane shows can be respawned, with the
/// state it is in when it can.
///
/// The guards a pane gets, from what there is to read in place of a screen. A
/// session waiting on an answer is refused whatever `--include-busy` says, as a
/// dialog on screen is, and so is one holding a reply saved for its next start:
/// a respawn sends that reply, which starts a turn nobody asked for now. A
/// record that says nothing of work in flight is not taken to mean none.
fn plan_bg(b: &BgSession, o: &Opts, e: &dyn Env) -> Result<state::State, String> {
    if !typable_id(&b.id) {
        return Err(format!("an id not safe to pass on: {:?}", b.id));
    }
    let st = match b.state {
        Some(st @ state::State::Idle) => st,
        Some(state::State::Input) => {
            return Err(format!(
                "waiting for an answer: claude attach {} to give it",
                b.id
            ))
        }
        Some(st @ state::State::Run) if o.include_busy => st,
        Some(st) => {
            return Err(format!(
                "{}: rerun when idle, or --include-busy",
                st.as_str()
            ))
        }
        None => return Err("says nothing of what it is doing".into()),
    };
    match b.in_flight {
        Some(f) if f.queued > 0 => {
            return Err(format!(
                "a reply is saved for its next start, which a respawn would send: claude attach {} to see it",
                b.id
            ))
        }
        _ if o.include_busy => {}
        Some(f) if f.tasks > 0 => {
            return Err(
                "work still in flight: rerun once it reports back, or --include-busy".into(),
            )
        }
        Some(_) => {}
        None => {
            return Err(
                "its job record says nothing of work in flight: --include-busy to respawn it anyway"
                    .into(),
            )
        }
    }
    if !o.include_busy {
        if let Some(text) = b.transcript.as_deref().and_then(|t| e.read_transcript(t)) {
            transcript_is_settled(&text, e.now()).map_err(|why| format!("not settled: {}", why))?;
        }
    }
    Ok(st)
}

/// The plan, as the reader sees it. Byte-for-byte what bash printed, because the
/// only way to know a port of this is right is to compare it.
pub fn render(p: &Plan) -> String {
    let mut s = format!("claude: {} installed at {}\n\n", p.newver, p.launcher);
    if p.go.is_empty() && p.go_bg.is_empty() {
        s.push_str("nothing to restart.\n");
    } else {
        s.push_str(&format!("to restart ({}):\n", p.go.len() + p.go_bg.len()));
        for g in &p.go {
            s.push_str(&format!("  {:<5} {:<14} {}\n", g.pane, g.target, g.title));
            s.push_str(&format!("        {}\n", g.via));
            match &g.respawn {
                Some(job) => {
                    s.push_str(&format!("        claude respawn {}, then {}\n", job, g.cmd))
                }
                None => s.push_str(&format!("        {}\n", g.cmd)),
            }
        }
        for b in &p.go_bg {
            s.push_str(&format!("  {:<5} {:<14} {}\n", b.id, "background", b.name));
            s.push_str(&format!("        {}\n", b.via));
            s.push_str(&format!("        claude respawn {}\n", b.id));
        }
    }
    if !p.skipped.is_empty() {
        s.push_str(&format!("\nskipped ({}):\n", p.skipped.len()));
        for k in &p.skipped {
            s.push_str(&format!("  {}\n", k));
        }
    }
    if p.unresolved {
        s.push_str(
            "\nAn unresolved pane means guessing, so it was left alone: restart it by hand\n\
             with `claude -c` in that pane, or from its /resume picker. Each session records\n\
             its pane at the next SessionStart, so a pane resolves cleanly once restarted.\n",
        );
    }
    s
}

/// Interrupt a session, wait for it to go, and type its replacement.
///
/// Two Ctrl-Cs, because the first one arms claude's "press again to exit" and the
/// second takes it. `/exit` after six waits is for a session that ignores both,
/// and thirty waits (twelve seconds) is where it gives up rather than typing a
/// command into a pane that still has a session in it.
pub fn restart_pane(pane: &str, pid: i32, cmd: &str) -> bool {
    use std::thread::sleep;
    use std::time::Duration;

    tmux::run(&["send-keys", "-t", pane, "C-c"]);
    sleep(Duration::from_millis(300));
    tmux::run(&["send-keys", "-t", pane, "C-c"]);

    let mut waited = 0;
    let mut sent_exit = false;
    while alive(pid) {
        sleep(Duration::from_millis(400));
        waited += 1;
        if waited >= 6 && !sent_exit {
            tmux::run(&["send-keys", "-t", pane, "/exit", "Enter"]);
            sent_exit = true;
        }
        if waited >= 30 {
            return false;
        }
    }
    sleep(Duration::from_millis(500));
    tmux::run(&["send-keys", "-t", pane, "C-c"]);
    sleep(Duration::from_millis(200));
    tmux::run(&["send-keys", "-t", pane, cmd, "Enter"])
}

/// Ask agent view's supervisor to put a background session on the version it
/// runs now, by the route Claude Code documents.
///
/// `claude respawn <id>` (2.1.333) stops the worker and resumes the same
/// conversation, under the same id and in the same permission mode, in a new
/// one, in about half a second. Measured with a client attached, which the
/// supervisor's own sweep of stale workers refuses. The new worker runs the
/// supervisor's version, which is the installed one once the supervisor has
/// taken an update. Run by path rather than by name, so no alias or function in
/// anybody's shell gets between `claude` and its subcommand.
pub fn respawn(launcher: &str, job: &str) -> Result<(), String> {
    let o = std::process::Command::new(launcher)
        .args(["respawn", job])
        .stdin(std::process::Stdio::null())
        .output()
        .map_err(|e| format!("could not run {}: {}", launcher, e))?;
    if o.status.success() {
        return Ok(());
    }
    let said = format!(
        "{}\n{}",
        String::from_utf8_lossy(&o.stderr),
        String::from_utf8_lossy(&o.stdout)
    );
    Err(said
        .lines()
        .map(str::trim)
        .find(|l| !l.is_empty())
        .map(str::to_string)
        .unwrap_or_else(|| format!("claude respawn {}: {}", job, o.status)))
}

/// Take a pane's client off the background session just respawned, and attach
/// the pane to it again.
///
/// A `claude attach` client exits by itself when its session restarts
/// ("Session <id> has exited"). Agent view's client, which is what a pane whose
/// conversation was moved into the background runs, goes back to its list
/// ("That session was stopped") and stays. That one is ended with SIGTERM
/// rather than with keys: a key reaches whichever session the client shows, and
/// a client showing some other session would hand two Ctrl-Cs to THAT one's
/// worker. A signal reaches the client alone, which holds no conversation of
/// its own. Measured on 2.1.333: gone in about 600ms.
pub fn reattach(pane: &str, client: i32, cmd: &str) -> bool {
    use std::thread::sleep;
    use std::time::Duration;

    let gone = |polls: u32| {
        for _ in 0..polls {
            if !alive(client) {
                return true;
            }
            sleep(Duration::from_millis(200));
        }
        !alive(client)
    };
    // Only a process still running a claude binary is signalled: a pid that has
    // gone and been handed out again is somebody else's.
    if !gone(10) && version_of_pid(client, &versions_dir()).is_some() {
        let _ = std::process::Command::new("kill")
            .args(["-TERM", &client.to_string()])
            .stdin(std::process::Stdio::null())
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status();
    }
    if !gone(25) {
        return false;
    }
    sleep(Duration::from_millis(300));
    tmux::run(&["send-keys", "-t", pane, "C-c"]);
    sleep(Duration::from_millis(200));
    tmux::run(&["send-keys", "-t", pane, cmd, "Enter"])
}

/// Is a pid still there? `/proc` rather than `kill -0`, since nothing is being
/// signalled and a directory read cannot be mistaken for one.
fn alive(pid: i32) -> bool {
    std::path::Path::new(&format!("/proc/{}", pid)).exists()
}

/// The default answer is yes, so a bare Enter restarts. The plan has already been
/// printed by then, which is what makes that safe.
pub fn confirm_yes(answer: &str) -> bool {
    matches!(answer.trim(), "" | "y" | "Y" | "yes" | "YES" | "Yes")
}

/// The live implementation of everything `plan` needs.
pub struct Live {
    pub versions_dir: String,
}

impl Env for Live {
    fn capture(&self, pane: &str) -> String {
        tmux::ask_raw(&["capture-pane", "-p", "-t", pane]).unwrap_or_default()
    }
    fn capture_zoomed(&self, pane: &str) -> Option<String> {
        capture_zoomed(pane)
    }
    fn hook_state(&self, pane: &str, pid: i32) -> Option<String> {
        taimux_core::hook::hook_state_of(pane, pid)
    }
    fn hook_mode(&self, pane: &str, pid: i32) -> Option<String> {
        taimux_core::hook::hook_entry(pane, pid).map(|e| e.mode)
    }
    fn own_state(&self, pid: i32, screen: &str) -> Option<state::State> {
        taimux_core::status::of(pid, &|| screen.to_string()).and_then(|o| o.state())
    }
    fn elsewhere(&self, pane: &str, pid: i32) -> Option<Elsewhere> {
        // the screen is only read for a pane whose conversation has moved
        let o =
            taimux_core::status::of(pid, &|| self.capture(pane)).filter(|o| o.via.elsewhere())?;
        let id = if o.job.is_empty() {
            o.session_id.get(..8).unwrap_or(&o.session_id)
        } else {
            &o.job
        };
        Some(Elsewhere {
            id: id.to_string(),
            pid: o.pid,
            version: version_of_pid(o.pid, &self.versions_dir),
            transcript: o.transcript().map(|t| t.display().to_string()),
        })
    }
    fn background(&self) -> Vec<BgSession> {
        taimux_core::status::background()
            .into_iter()
            .map(|o| {
                let id = if o.job.is_empty() {
                    o.session_id.get(..8).unwrap_or(&o.session_id).to_string()
                } else {
                    o.job.clone()
                };
                BgSession {
                    version: version_of_pid(o.pid, &self.versions_dir),
                    state: o.state(),
                    transcript: o.transcript().map(|t| t.display().to_string()),
                    in_flight: taimux_core::status::in_flight(&id),
                    pid: o.pid,
                    name: o.name,
                    id,
                }
            })
            .collect()
    }
    fn version_of_pid(&self, pid: i32) -> Option<String> {
        version_of_pid(pid, &self.versions_dir)
    }
    fn cwd_of(&self, pid: i32) -> Option<String> {
        std::fs::read_link(format!("/proc/{}/cwd", pid))
            .ok()
            .map(|p| p.to_string_lossy().into_owned())
            .filter(|s| !s.is_empty())
    }
    fn argv_of(&self, pid: i32) -> Vec<String> {
        conv::argv_of(pid)
    }
    fn resolve(&self, pane: &str, cwd: &str, title: &str, pid: i32) -> Result<String, String> {
        conv::resolve(pane, cwd, title, pid)
            .map(|r| format!("{}\t{}", r.transcript.display(), r.why))
    }
    fn read_transcript(&self, path: &str) -> Option<String> {
        std::fs::read_to_string(path).ok()
    }
    fn now(&self) -> i64 {
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs() as i64)
            .unwrap_or(0)
    }
}

/// What a session started right now would run, refusing rather than guessing when
/// the launcher points somewhere unexpected.
pub fn installed(launcher: &str, versions_dir: &str) -> Result<String, String> {
    let target = std::fs::canonicalize(launcher)
        .map(|p| p.to_string_lossy().into_owned())
        .unwrap_or_default();
    let prefix = format!("{}/", versions_dir);
    match target.strip_prefix(&prefix) {
        Some(rest) if !rest.is_empty() => Ok(rest.split('/').next().unwrap_or(rest).to_string()),
        _ => Err(format!(
            "restart: {} does not point into {} (got '{}')",
            launcher,
            versions_dir,
            if target.is_empty() {
                "nothing"
            } else {
                &target
            }
        )),
    }
}

pub fn versions_dir() -> String {
    format!(
        "{}/.local/share/claude/versions",
        std::env::var("HOME").unwrap_or_default()
    )
}

pub fn launcher() -> String {
    format!(
        "{}/.local/bin/claude",
        std::env::var("HOME").unwrap_or_default()
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_timestamp_becomes_epoch_seconds() {
        // 2026-09-02T01:23:45Z
        assert_eq!(parse_iso8601("2026-09-02T01:23:45.678Z"), Some(1788312225));
        assert_eq!(parse_iso8601("1970-01-01T00:00:00Z"), Some(0));
        // a leap day, which a hand-rolled calendar is where it goes wrong
        assert_eq!(parse_iso8601("2024-02-29T00:00:00Z"), Some(1709164800));
    }

    /// Anything not of that exact shape reads as "no answer", which the caller
    /// treats as not-evidence rather than as busy: guessing busy would skip a
    /// pane on a malformed line forever.
    #[test]
    fn an_unparseable_timestamp_is_no_answer() {
        assert_eq!(parse_iso8601(""), None);
        assert_eq!(parse_iso8601("yesterday"), None);
        assert_eq!(parse_iso8601("2026-09-02 01:23:45"), None);
        assert_eq!(parse_iso8601("2026-13-02T01:23:45Z"), None);
    }

    #[test]
    fn a_tool_call_still_running_is_not_settled() {
        let t = r#"{"type":"assistant","message":{"content":[{"type":"tool_use"}]},"timestamp":"2020-01-01T00:00:00Z"}"#;
        assert_eq!(
            transcript_is_settled(t, 1788312225),
            Err("a tool call is still running".into())
        );
    }

    /// Insurance for the screen reading, which is the most fragile thing here.
    #[test]
    fn recent_activity_is_not_settled_whatever_the_screen_said() {
        let t = r#"{"type":"user","timestamp":"2026-09-02T01:23:45Z"}"#;
        assert!(transcript_is_settled(t, 1788312225 + 10).is_err());
        assert!(transcript_is_settled(t, 1788312225 + 100).is_ok());
    }

    #[test]
    fn an_empty_or_odd_transcript_does_not_block() {
        assert!(transcript_is_settled("", 0).is_ok());
        assert!(transcript_is_settled("not json at all\n", 0).is_ok());
        // no timestamp: nothing to judge recency by
        assert!(transcript_is_settled(r#"{"type":"user"}"#, 0).is_ok());
    }

    /// A dialog is what `state::awaits_input` recognises, so the fixture has to
    /// be one it would: either the footer in the last few lines, or a numbered
    /// choice on the LOWEST prompt line. A made-up shape asserts nothing.
    #[test]
    fn a_dialog_on_screen_blocks_a_restart() {
        let footer = "some output\n\nDo you want to proceed?\n";
        assert_eq!(
            screen_has_no_dialog(footer),
            Err("a dialog is waiting for an answer".into())
        );
        let choice = "some output\n1. Yes\n2. No\n❯ 1. Yes\n";
        assert_eq!(
            screen_has_no_dialog(choice),
            Err("a dialog is waiting for an answer".into())
        );
        // an ordinary idle screen is not a dialog
        assert!(screen_has_no_dialog("some output\n❯ \n").is_ok());
    }

    /// A half-pressed Ctrl-C is the one state where the keystroke that starts a
    /// restart is also an answer to something else.
    #[test]
    fn a_half_pressed_ctrl_c_blocks_a_restart() {
        let screen = "work\n\nPress Ctrl-C again to exit\n";
        assert_eq!(
            screen_has_no_dialog(screen),
            Err("a Ctrl-C is already half-pressed".into())
        );
    }

    #[test]
    fn an_empty_prompt_box_is_no_draft() {
        assert!(screen_has_no_draft("stuff\n❯ \n").is_ok());
        // the non-breaking space claude pads the box with is not a draft
        assert!(screen_has_no_draft("stuff\n❯ \u{a0}\u{a0}\n").is_ok());
        assert_eq!(
            screen_has_no_draft("stuff\n❯ half a thought\n"),
            Err("unsent text in the prompt box".into())
        );
    }

    /// The four rows a pane has to be given before any of this can be asked of
    /// it, and the two it can be left at.
    #[test]
    fn a_pane_tall_enough_to_read_is_left_alone() {
        // already showing its box: nothing to gain, and nothing touched
        assert!(zoom_steps("%1", false, 6, 40, "%2", "%3").is_none());
        assert!(zoom_steps("%1", false, 40, 40, "%2", "%3").is_none());
        // a window no taller than the pane has no rows to lend it
        assert!(zoom_steps("%1", false, 3, 3, "%2", "%3").is_none());
        assert!(zoom_steps("%1", false, 3, 5, "%2", "%3").is_none());
    }

    /// The common shape: a three-row pane in a window nobody has zoomed. One
    /// zoom out and back, and the pane that was active is active again with the
    /// pane that was behind it still behind it.
    #[test]
    fn a_short_pane_is_zoomed_and_the_selection_put_back() {
        let (go, back) = zoom_steps("%1", false, 3, 17, "%2", "%3").unwrap();
        assert_eq!(go, vec![vec!["resize-pane", "-Z", "-t", "%1"]]);
        assert_eq!(
            back,
            vec![
                vec!["resize-pane", "-Z", "-t", "%1"],
                vec!["select-pane", "-t", "%3"],
                vec!["select-pane", "-t", "%2"],
            ]
        );
    }

    /// A window that arrives zoomed on another pane takes TWO `-Z` to zoom this
    /// one, because the first is spent switching the other one off, and it is
    /// owed a re-zoom at the end.
    #[test]
    fn a_window_zoomed_elsewhere_is_handed_back_zoomed() {
        let (go, back) = zoom_steps("%1", true, 3, 17, "%2", "%3").unwrap();
        assert_eq!(
            go,
            vec![
                vec!["resize-pane", "-Z", "-t", "%1"],
                vec!["resize-pane", "-Z", "-t", "%1"],
            ]
        );
        assert_eq!(
            back,
            vec![
                vec!["resize-pane", "-Z", "-t", "%1"],
                vec!["select-pane", "-t", "%3"],
                vec!["select-pane", "-t", "%2"],
                vec!["resize-pane", "-Z", "-t", "%2"],
            ]
        );
    }

    /// Zooming the pane that is already active changes no selection, so putting
    /// one back would be the only thing that moved it.
    #[test]
    fn an_active_short_pane_has_no_selection_to_restore() {
        let (go, back) = zoom_steps("%1", false, 3, 17, "%1", "%3").unwrap();
        assert_eq!(go.len(), 1);
        assert_eq!(back, vec![vec!["resize-pane", "-Z", "-t", "%1"]]);
    }

    /// No box at all means the screen is not what it is expected to be, and that
    /// is a refusal rather than a shrug.
    #[test]
    fn no_prompt_box_is_a_refusal() {
        assert_eq!(
            screen_has_no_draft("just some text\n"),
            Err("no prompt box on screen".into())
        );
        // …but a genuinely blank screen is not judged at all
        assert!(screen_has_no_draft("").is_ok());
        assert!(screen_has_no_draft("   \n\n").is_ok());
    }

    #[test]
    fn a_bare_enter_confirms() {
        assert!(confirm_yes(""));
        assert!(confirm_yes("y"));
        assert!(confirm_yes("YES"));
        assert!(!confirm_yes("n"));
        assert!(!confirm_yes("no"));
        assert!(!confirm_yes("maybe"));
    }

    #[test]
    fn the_launcher_must_point_into_the_versions_dir() {
        let root = std::env::temp_dir().join(format!("jmrs{}", std::process::id()));
        let vers = root.join("versions");
        std::fs::create_dir_all(&vers).unwrap();
        std::fs::write(vers.join("2.1.258"), "x").unwrap();
        let link = root.join("claude");
        std::os::unix::fs::symlink(vers.join("2.1.258"), &link).unwrap();
        assert_eq!(
            installed(&link.to_string_lossy(), &vers.to_string_lossy()),
            Ok("2.1.258".into())
        );
        // pointing elsewhere is a refusal that names what it found
        std::fs::write(root.join("elsewhere"), "x").unwrap();
        std::fs::remove_file(&link).unwrap();
        std::os::unix::fs::symlink(root.join("elsewhere"), &link).unwrap();
        let e = installed(&link.to_string_lossy(), &vers.to_string_lossy()).expect_err("refused");
        assert!(e.contains("elsewhere"));
        let _ = std::fs::remove_dir_all(&root);
    }
}

/// A claude process that is not any pane's foreground job: Zed's ACP bridge, a
/// background agent, one of the daemon's spare pty hosts.
///
/// Reported, never touched. A restart types into a PANE, and these have none, so
/// the only useful thing to do about a stale one is name it.
pub fn nonpane_pids(matched: &[i32], versions_dir: &str) -> Vec<i32> {
    let mut out = Vec::new();
    for e in std::fs::read_dir("/proc").into_iter().flatten().flatten() {
        let Some(pid) = e.file_name().to_str().and_then(|s| s.parse::<i32>().ok()) else {
            continue;
        };
        if matched.contains(&pid) {
            continue;
        }
        // Either its comm is "claude" (pgrep -x claude) or it is running out of
        // the versions directory (pgrep -f "^<vdir>/").
        let comm = std::fs::read_to_string(format!("/proc/{}/comm", pid)).unwrap_or_default();
        let argv = conv::argv_of(pid);
        let is_claude = comm.trim() == "claude"
            || argv
                .first()
                .map(|a| a.starts_with(&format!("{}/", versions_dir)))
                .unwrap_or(false);
        if is_claude {
            out.push(pid);
        }
    }
    out.sort_unstable();
    out
}

/// The object in a JSON array whose `key` starts with `prefix`, as raw text.
///
/// A brace matcher rather than a parser, and rather than the `jq` the bash
/// version shelled out to. It only has to find one element of one array, and the
/// depth count is what makes it safe against nested objects: taking everything
/// between the first `{` and the first `}` would truncate any element with a
/// nested field.
fn json_object_with_prefix(text: &str, key: &str, prefix: &str) -> Option<String> {
    let needle = format!("\"{}\":\"{}", key, prefix);
    let at = text.find(&needle).or_else(|| {
        let spaced = format!("\"{}\": \"{}", key, prefix);
        text.find(&spaced)
    })?;
    // back to the opening brace of the object holding it
    let mut depth = 0i32;
    let bytes = text.as_bytes();
    let mut start = None;
    for i in (0..at).rev() {
        match bytes[i] {
            b'}' => depth += 1,
            b'{' => {
                if depth == 0 {
                    start = Some(i);
                    break;
                }
                depth -= 1;
            }
            _ => {}
        }
    }
    let start = start?;
    // forward to its matching close
    let mut depth = 0i32;
    for i in start..bytes.len() {
        match bytes[i] {
            b'{' => depth += 1,
            b'}' => {
                depth -= 1;
                if depth == 0 {
                    return Some(text[start..=i].to_string());
                }
            }
            _ => {}
        }
    }
    None
}

/// What to say about a claude that has no pane.
///
/// `agents_json` is `claude agents --json`, which costs about three seconds of
/// CLI startup, so it is fetched once by the caller and only when something needs
/// naming. Its own `pid` field points at the pty-host wrapper rather than at the
/// session, so it is read for kind, state and name and nothing else.
pub fn describe_nonpane(argv: &[String], agents_json: &str) -> String {
    if argv.is_empty() {
        return "gone".into();
    }
    let (mut sid, mut res, mut forked) = (String::new(), String::new(), false);
    for i in 1..argv.len() {
        match argv[i].as_str() {
            "--fork-session" => forked = true,
            "--session-id" => sid = argv.get(i + 1).cloned().unwrap_or_default(),
            "-r" | "--resume" => res = argv.get(i + 1).cloned().unwrap_or_default(),
            _ => {}
        }
    }
    let own = base_id(if sid.is_empty() { &res } else { &sid });
    let parent = if forked && !res.is_empty() {
        base_id(&res)
    } else {
        String::new()
    };

    let (mut kind, mut st, mut name) = ("?".to_string(), "?".to_string(), String::new());
    if !own.is_empty() {
        if let Some(obj) = json_object_with_prefix(agents_json, "sessionId", &own) {
            let f = |k: &str| taimux_core::json::field(&obj, k);
            let k = f("kind");
            if !k.is_empty() {
                kind = k;
            }
            let s = {
                let a = f("state");
                if a.is_empty() {
                    f("status")
                } else {
                    a
                }
            };
            if !s.is_empty() {
                st = s;
            }
            name = f("name");
        }
    }
    let mut out = format!("{} {}", kind, st);
    if forked {
        out.push_str(" fork");
    }
    if !name.is_empty() {
        out.push_str(&format!(" \"{}\"", name));
    }
    if !own.is_empty() {
        out.push_str(&format!(" [{}]", own.chars().take(8).collect::<String>()));
    }
    if !parent.is_empty() {
        out.push_str(&format!(
            " of [{}]",
            parent.chars().take(8).collect::<String>()
        ));
    }
    out
}

/// `basename x .jsonl`: a session id, whether it arrived as one or as a path.
fn base_id(s: &str) -> String {
    if s.is_empty() {
        return String::new();
    }
    let b = s.rsplit('/').next().unwrap_or(s);
    b.strip_suffix(".jsonl").unwrap_or(b).to_string()
}

#[cfg(test)]
mod nonpane_tests {
    use super::*;

    fn v(a: &[&str]) -> Vec<String> {
        a.iter().map(|s| s.to_string()).collect()
    }

    #[test]
    fn a_session_id_is_read_out_of_a_path_or_taken_as_it_stands() {
        assert_eq!(base_id("/a/b/263946b5-9bd7.jsonl"), "263946b5-9bd7");
        assert_eq!(base_id("263946b5"), "263946b5");
        assert_eq!(base_id(""), "");
    }

    /// The depth count is the whole point: taking everything between the first
    /// brace and the first close would truncate any element with a nested field,
    /// and `claude agents --json` has them.
    #[test]
    fn the_right_object_comes_back_whole() {
        let j = r#"[{"sessionId":"aaa111","kind":"task","meta":{"a":1},"name":"first"},
                    {"sessionId":"bbb222","kind":"agent","name":"second"}]"#;
        let o = json_object_with_prefix(j, "sessionId", "bbb222").expect("found");
        assert!(o.contains("second"));
        assert!(!o.contains("first"));
        let o = json_object_with_prefix(j, "sessionId", "aaa").expect("found by prefix");
        assert!(o.contains("first"));
        assert!(
            o.contains("\"meta\":{\"a\":1}"),
            "nested field truncated: {}",
            o
        );
        assert!(json_object_with_prefix(j, "sessionId", "zzz").is_none());
    }

    #[test]
    fn a_process_with_no_argv_is_simply_gone() {
        assert_eq!(describe_nonpane(&[], "[]"), "gone");
    }

    #[test]
    fn an_unnamed_session_still_says_what_it_can() {
        let d = describe_nonpane(&v(&["claude", "--session-id", "263946b5-9bd7"]), "[]");
        assert_eq!(d, "? ? [263946b5]");
    }

    #[test]
    fn a_named_one_says_kind_state_and_name() {
        let j =
            r#"[{"sessionId":"263946b5-9bd7","kind":"task","state":"running","name":"the thing"}]"#;
        let d = describe_nonpane(&v(&["claude", "--session-id", "263946b5-9bd7"]), j);
        assert_eq!(d, "task running \"the thing\" [263946b5]");
    }

    /// `status` is the older field name, and one of the two is what a given
    /// version emits.
    #[test]
    fn status_stands_in_for_state() {
        let j = r#"[{"sessionId":"aaa11111","kind":"agent","status":"idle"}]"#;
        let d = describe_nonpane(&v(&["claude", "--session-id", "aaa11111"]), j);
        assert_eq!(d, "agent idle [aaa11111]");
    }

    /// A fork names both itself and its parent, because that is the pair you need
    /// to work out which one is the stale one.
    #[test]
    fn a_fork_names_its_parent_too() {
        let d = describe_nonpane(
            &v(&[
                "claude",
                "--session-id",
                "child111",
                "--fork-session",
                "--resume",
                "/p/parent22.jsonl",
            ]),
            "[]",
        );
        assert_eq!(d, "? ? fork [child111] of [parent22]");
    }
}

#[cfg(test)]
mod plan_tests {
    use super::*;

    /// A machine with one stale pane, one current one, and whatever else the test
    /// asks for. The `Env` trait exists for this: the live differential can only
    /// reach "nothing to restart" while every session is on the installed
    /// version, so the branch that actually acts needs a fixture.
    struct Fake {
        /// pid -> version
        vers: HashMap<i32, String>,
        /// pane -> screen
        screens: HashMap<String, String>,
        /// pane -> resolved transcript, or the refusal
        resolved: HashMap<String, Result<String, String>>,
        /// pane -> what the same pane shows once it has been zoomed, for a pane
        /// too short to draw a prompt box at the size it sits at
        zoomed: HashMap<String, String>,
        /// how many panes were zoomed to be read, since a zoom is something the
        /// user watching that window sees happen
        zooms: std::cell::Cell<usize>,
        /// pane -> the hook line's state, for the panes that have one
        hooks: HashMap<String, String>,
        /// pane -> the hook line's permission mode
        modes: HashMap<String, String>,
        /// pid -> what the session says it is doing, for the ones that say
        own: HashMap<i32, state::State>,
        /// pid -> the background session it shows: its id, its worker's
        /// version, and the transcript it writes
        away: HashMap<i32, (String, String, Option<String>)>,
        /// every background session running, as the files list them
        bgs: Vec<BgSession>,
        transcript: String,
        now: i64,
    }

    impl Env for Fake {
        fn capture(&self, pane: &str) -> String {
            self.screens.get(pane).cloned().unwrap_or_default()
        }
        fn capture_zoomed(&self, pane: &str) -> Option<String> {
            let bigger = self.zoomed.get(pane).cloned();
            if bigger.is_some() {
                self.zooms.set(self.zooms.get() + 1);
            }
            bigger
        }
        fn hook_state(&self, pane: &str, _pid: i32) -> Option<String> {
            self.hooks.get(pane).cloned()
        }
        fn hook_mode(&self, pane: &str, _pid: i32) -> Option<String> {
            self.modes.get(pane).cloned()
        }
        fn own_state(&self, pid: i32, _screen: &str) -> Option<state::State> {
            self.own.get(&pid).copied()
        }
        fn elsewhere(&self, _pane: &str, pid: i32) -> Option<Elsewhere> {
            self.away.get(&pid).map(|(id, ver, transcript)| Elsewhere {
                id: id.clone(),
                pid: 1000 + pid,
                version: Some(ver.clone()),
                transcript: transcript.clone(),
            })
        }
        fn background(&self) -> Vec<BgSession> {
            self.bgs.clone()
        }
        fn version_of_pid(&self, pid: i32) -> Option<String> {
            self.vers.get(&pid).cloned()
        }
        fn cwd_of(&self, _pid: i32) -> Option<String> {
            Some("/w".into())
        }
        fn argv_of(&self, _pid: i32) -> Vec<String> {
            vec!["claude".into()]
        }
        fn resolve(&self, pane: &str, _c: &str, _t: &str, _p: i32) -> Result<String, String> {
            self.resolved
                .get(pane)
                .cloned()
                .unwrap_or_else(|| Err("no candidate".into()))
        }
        fn read_transcript(&self, _path: &str) -> Option<String> {
            Some(self.transcript.clone())
        }
        fn now(&self) -> i64 {
            self.now
        }
    }

    fn fake() -> Fake {
        let mut vers = HashMap::new();
        vers.insert(11, "2.1.100".to_string()); // stale
        vers.insert(22, "2.1.258".to_string()); // current
        let mut screens = HashMap::new();
        // an idle screen with an empty prompt box
        screens.insert("%1".to_string(), "some output\n❯ \n".to_string());
        screens.insert("%2".to_string(), "some output\n❯ \n".to_string());
        let mut resolved = HashMap::new();
        resolved.insert("%1".to_string(), Ok("/t/a.jsonl\tpane map".to_string()));
        Fake {
            vers,
            screens,
            resolved,
            zoomed: HashMap::new(),
            zooms: std::cell::Cell::new(0),
            hooks: HashMap::new(),
            modes: HashMap::new(),
            own: HashMap::new(),
            away: HashMap::new(),
            bgs: Vec::new(),
            transcript: r#"{"type":"user","timestamp":"2020-01-01T00:00:00Z"}"#.to_string(),
            now: 1788312225,
        }
    }

    fn opts() -> Opts {
        Opts {
            include_busy: false,
            only_panes: Vec::new(),
            force_transcript: None,
            self_pane: String::new(),
        }
    }

    const ROWS: &str = "%1\tw:1.1\t/w\tclaude\t11\tclaude\tproj: the stale one\n\
                        %2\tw:2.1\t/w\tclaude\t22\tclaude\tproj: the current one";

    fn plan_of(e: &Fake, o: &Opts) -> Plan {
        plan(ROWS, "2.1.258", "/l/claude", o, e, "/nowhere", &|| {
            "[]".into()
        })
    }

    #[test]
    fn a_stale_pane_is_planned_and_a_current_one_is_not() {
        let p = plan_of(&fake(), &opts());
        assert_eq!(p.go.len(), 1);
        assert_eq!(p.go[0].pane, "%1");
        assert_eq!(p.go[0].cmd, "command claude --resume /t/a.jsonl");
        assert_eq!(p.go[0].via, "2.1.100 -> 2.1.258, pane map, idle");
        assert!(p.skipped.is_empty());
    }

    /// A session comes back in the mode it is in, not the one it was launched
    /// in: a plain resume starts in the startup default, which put every pane
    /// flipped to auto back in manual. The footer is read first, because a
    /// `shift+tab` at an idle prompt moves nothing else, the hook line included.
    #[test]
    fn a_session_comes_back_in_the_mode_it_is_in() {
        let rule = "────────────────────────────────";
        let mut e = fake();
        e.screens.insert(
            "%1".into(),
            format!("some output\n{rule}\n❯ \n{rule}\n  ⏵⏵ accept edits on (shift+tab to cycle)\n"),
        );
        e.modes.insert("%1".into(), "auto".into()); // its last turn's
        let p = plan_of(&e, &opts());
        assert_eq!(p.go.len(), 1, "{:?}", p.skipped);
        assert_eq!(
            p.go[0].cmd,
            "command claude --permission-mode acceptEdits --resume /t/a.jsonl"
        );

        // a footer that names nothing leaves it to the hook line
        let mut e = fake();
        e.modes.insert("%1".into(), "plan".into());
        let p = plan_of(&e, &opts());
        assert_eq!(
            p.go[0].cmd,
            "command claude --permission-mode plan --resume /t/a.jsonl"
        );

        // and a line that has heard no mode yet leaves the argv as it is
        let mut e = fake();
        e.modes.insert("%1".into(), "-".into());
        assert_eq!(
            plan_of(&e, &opts()).go[0].cmd,
            "command claude --resume /t/a.jsonl"
        );
    }

    /// The rendered plan is the whole user interface of `restart -n`, so its
    /// exact shape is what the bash comparison was made on.
    #[test]
    fn the_rendered_plan_reads_the_way_it_always_did() {
        let out = render(&plan_of(&fake(), &opts()));
        assert_eq!(
            out,
            "claude: 2.1.258 installed at /l/claude\n\n\
             to restart (1):\n\
             \x20 %1    w:1.1          proj: the stale one\n\
             \x20       2.1.100 -> 2.1.258, pane map, idle\n\
             \x20       command claude --resume /t/a.jsonl\n"
        );
    }

    /// Restarting the pane taimux is running in would kill taimux mid-restart.
    #[test]
    fn this_pane_is_never_restarted() {
        let mut o = opts();
        o.self_pane = "%1".into();
        let p = plan_of(&fake(), &o);
        assert!(p.go.is_empty());
        assert!(p.skipped[0].contains("this pane"));
        assert!(p.skipped[0].contains("killing it would kill taimux"));
    }

    #[test]
    fn a_pane_that_is_not_idle_waits_for_include_busy() {
        let mut e = fake();
        // an activity line: mid-turn
        e.screens
            .insert("%1".into(), "Twisting… (35s · ↓ 1.6k tokens)\n❯ \n".into());
        let p = plan_of(&e, &opts());
        assert!(p.go.is_empty());
        assert!(p.skipped[0].contains("rerun when idle, or --include-busy"));

        let mut o = opts();
        o.include_busy = true;
        assert_eq!(plan_of(&e, &o).go.len(), 1);
    }

    /// What the session says outranks a screen and a hook line that both look
    /// idle: a permission granted to a tool that is still running shows neither
    /// a counter nor a fresh line, and restarting it would kill the tool.
    #[test]
    fn a_session_that_says_it_is_busy_is_busy() {
        let mut e = fake();
        e.hooks.insert("%1".into(), "input".into());
        e.own.insert(11, state::State::Run);
        let p = plan_of(&e, &opts());
        assert!(p.go.is_empty());
        assert!(
            p.skipped[0].contains("run: rerun when idle"),
            "{:?}",
            p.skipped
        );
        // and an Esc the hook line never heard of frees it again
        e.hooks.insert("%1".into(), "run".into());
        e.own.insert(11, state::State::Idle);
        assert_eq!(plan_of(&e, &opts()).go.len(), 1);
    }

    /// A pane showing a background session is put back by respawning the
    /// session's worker and attaching the pane to it again. Retyping it would
    /// resume the conversation the pane started on as a second branch, beside
    /// the one agent view goes on running, so the ladder is never asked: the
    /// job id is all either command takes.
    #[test]
    fn a_pane_showing_a_background_session_is_respawned_and_attached_again() {
        let mut e = fake();
        e.own.insert(11, state::State::Idle);
        e.away
            .insert(11, ("2447b564".into(), "2.1.100".into(), None));
        e.resolved.insert("%1".into(), Err("never asked".into()));
        let p = plan_of(&e, &opts());
        assert_eq!(p.go.len(), 1, "{:?}", p.skipped);
        let g = &p.go[0];
        assert_eq!(g.pane, "%1");
        assert_eq!(g.pid, 11, "the pane's own process, the client");
        assert_eq!(g.respawn.as_deref(), Some("2447b564"));
        assert_eq!(g.cmd, "command claude attach 2447b564");
        assert_eq!(
            g.via,
            "2.1.100 -> 2.1.258, background session 2447b564, idle"
        );
        assert!(!p.unresolved);
    }

    /// The version that counts on a pane attached to a background session is
    /// its worker's, either way round: a current client on a stale worker is
    /// behind, and a stale client on a current worker has nothing to gain.
    #[test]
    fn an_attached_pane_is_judged_by_its_workers_version() {
        let mut e = fake();
        e.away
            .insert(22, ("880ae832".into(), "2.1.250".into(), None));
        let p = plan_of(&e, &opts());
        assert_eq!(p.go.len(), 2, "{:?}", p.skipped);
        assert_eq!(
            (p.go[0].pane.as_str(), p.go[0].respawn.as_deref()),
            ("%1", None)
        );
        assert_eq!(
            (p.go[1].pane.as_str(), p.go[1].respawn.as_deref()),
            ("%2", Some("880ae832"))
        );
        assert!(p.go[1].via.starts_with("2.1.250 -> 2.1.258, "));

        let mut e = fake();
        e.away
            .insert(11, ("880ae832".into(), "2.1.258".into(), None));
        let p = plan_of(&e, &opts());
        assert!(p.go.is_empty());
        assert!(
            p.skipped.iter().all(|s| !s.starts_with("%1")),
            "{:?}",
            p.skipped
        );
    }

    /// A respawn ends the worker, so it waits on everything a retype waits on,
    /// read off the session the pane shows: what it says it is doing, the
    /// screen, and its own transcript.
    #[test]
    fn a_background_session_waits_like_any_pane() {
        let bg = |e: &mut Fake| {
            e.away.insert(
                11,
                (
                    "2447b564".into(),
                    "2.1.100".into(),
                    Some("/t/bg.jsonl".into()),
                ),
            );
        };
        let mut busy = opts();
        busy.include_busy = true;

        // a turn in flight in the worker
        let mut e = fake();
        bg(&mut e);
        e.own.insert(11, state::State::Run);
        let p = plan_of(&e, &opts());
        assert!(p.go.is_empty());
        assert!(
            p.skipped[0].contains("2.1.100, run: rerun when idle, or --include-busy"),
            "{:?}",
            p.skipped
        );
        assert_eq!(plan_of(&e, &busy).go.len(), 1);

        // a shell its last turn left running
        let mut e = fake();
        bg(&mut e);
        e.screens.insert(
            "%1".into(),
            "✻ Cogitated for 3s · done 4:55 PM · 1 shell still running\n❯ \n".into(),
        );
        assert!(plan_of(&e, &opts()).skipped[0].contains("work still in flight"));

        // a permission prompt, whatever --include-busy says
        let mut e = fake();
        bg(&mut e);
        e.screens.insert(
            "%1".into(),
            "some output\n\nDo you want to proceed?\n".into(),
        );
        let p = plan_of(&e, &busy);
        assert!(p.go.is_empty());
        assert!(
            p.skipped[0].contains("a dialog is waiting"),
            "{:?}",
            p.skipped
        );

        // a draft in its prompt box, which lives in the worker
        let mut e = fake();
        bg(&mut e);
        e.screens
            .insert("%1".into(), "stuff\n❯ half a thought\n".into());
        assert!(plan_of(&e, &opts()).skipped[0].contains("unsent text in the prompt box"));

        // its transcript written to a moment ago
        let mut e = fake();
        bg(&mut e);
        e.transcript = r#"{"type":"user","timestamp":"2026-09-02T01:23:40Z"}"#.into();
        assert!(plan_of(&e, &opts()).skipped[0].contains("not settled"));
        // …and no transcript to read is no evidence either way
        e.away
            .insert(11, ("2447b564".into(), "2.1.100".into(), None));
        assert_eq!(plan_of(&e, &opts()).go.len(), 1);

        // and never the pane taimux runs in
        let mut e = fake();
        bg(&mut e);
        let mut me = opts();
        me.self_pane = "%1".into();
        assert!(plan_of(&e, &me).skipped[0].contains("this pane"));
    }

    /// Two panes on one background session both go in the plan, carrying the
    /// same session: the respawn takes both clients off it, so both are
    /// attached again, and `restart` respawns it once.
    #[test]
    fn two_panes_on_one_background_session_are_both_attached_again() {
        let mut e = fake();
        e.vers.insert(22, "2.1.100".into());
        e.away
            .insert(11, ("2447b564".into(), "2.1.100".into(), None));
        e.away
            .insert(22, ("2447b564".into(), "2.1.100".into(), None));
        let p = plan_of(&e, &opts());
        assert_eq!(p.go.len(), 2, "{:?}", p.skipped);
        assert!(p
            .go
            .iter()
            .all(|g| g.respawn.as_deref() == Some("2447b564")));
    }

    /// `--transcript` names a conversation to resume in the pane, and the one
    /// thing a respawn never does is resume anything in the pane.
    #[test]
    fn a_given_transcript_does_not_apply_to_a_background_session() {
        let mut e = fake();
        e.away
            .insert(11, ("2447b564".into(), "2.1.100".into(), None));
        let mut o = opts();
        o.only_panes = vec!["%1".into()];
        o.force_transcript = Some("/t/other.jsonl".into());
        let p = plan_of(&e, &o);
        assert!(p.go.is_empty());
        assert!(
            p.skipped[0].contains("--transcript does not apply"),
            "{:?}",
            p.skipped
        );
    }

    /// The id is typed into the pane's shell, so it has to be one that a shell
    /// reads as a single plain word.
    #[test]
    fn an_id_unsafe_to_type_is_refused() {
        let mut e = fake();
        e.away
            .insert(11, ("2447b564; rm -rf ~".into(), "2.1.100".into(), None));
        let p = plan_of(&e, &opts());
        assert!(p.go.is_empty());
        assert!(p.skipped[0].contains("not safe to type"), "{:?}", p.skipped);
        assert!(typable_id("2447b564"));
        assert!(typable_id("58b11e6b-39fd-484a-aa0f-44e86a8eb6d1"));
        assert!(!typable_id(""));
        assert!(!typable_id("a b"));
        assert!(!typable_id("$(x)"));
    }

    /// An idle background session behind the installed version, no pane
    /// showing it, its record clean.
    fn bg_session() -> BgSession {
        BgSession {
            id: "f3836aef".into(),
            pid: 500,
            version: Some("2.1.100".into()),
            name: "jumpmux: stage".into(),
            state: Some(state::State::Idle),
            transcript: Some("/t/bg.jsonl".into()),
            in_flight: Some(taimux_core::status::InFlight {
                tasks: 0,
                queued: 0,
            }),
        }
    }

    /// One no pane shows has nothing to type into, so a respawn is all of it,
    /// and only a whole plan looks for one: `--pane` names panes.
    #[test]
    fn a_background_session_no_pane_shows_is_respawned() {
        let mut e = fake();
        let mut current = bg_session();
        current.id = "aaaaaaaa".into();
        current.pid = 501;
        current.version = Some("2.1.258".into());
        e.bgs = vec![bg_session(), current];
        let p = plan_of(&e, &opts());
        assert_eq!(p.go.len(), 1, "the stale pane, as before");
        assert_eq!(p.go_bg.len(), 1, "{:?}", p.skipped);
        assert_eq!((p.go_bg[0].id.as_str(), p.go_bg[0].pid), ("f3836aef", 500));
        assert_eq!(p.go_bg[0].via, "2.1.100 -> 2.1.258, no pane, idle");
        let out = render(&p);
        assert!(out.contains("to restart (2):\n"), "{out}");
        assert!(
            out.ends_with(
                "\x20 f3836aef background     jumpmux: stage\n\
                 \x20       2.1.100 -> 2.1.258, no pane, idle\n\
                 \x20       claude respawn f3836aef\n"
            ),
            "{out}"
        );

        let mut o = opts();
        o.only_panes = vec!["%1".into()];
        assert!(plan_of(&e, &o).go_bg.is_empty());
    }

    /// A worker some pane shows is that pane's to put back, attach and all.
    #[test]
    fn a_background_session_a_pane_shows_is_left_to_the_pane() {
        let mut e = fake();
        e.away
            .insert(11, ("f3836aef".into(), "2.1.100".into(), None));
        let mut b = bg_session();
        b.pid = 1011; // the Fake's worker for pid 11
        e.bgs = vec![b];
        let p = plan_of(&e, &opts());
        assert!(p.go_bg.is_empty(), "planned twice");
        assert_eq!(p.go[0].respawn.as_deref(), Some("f3836aef"));
    }

    /// The guards a pane gets, read off what there is in place of a screen.
    #[test]
    fn a_background_session_no_pane_shows_waits_like_any_pane() {
        let mut busy = opts();
        busy.include_busy = true;
        let with = |f: &dyn Fn(&mut BgSession)| {
            let mut e = fake();
            let mut b = bg_session();
            f(&mut b);
            e.bgs = vec![b];
            e
        };
        let refused = |e: &Fake, o: &Opts, why: &str| {
            let p = plan_of(e, o);
            assert!(p.go_bg.is_empty(), "planned despite {why}");
            assert!(
                p.skipped
                    .iter()
                    .any(|s| s.starts_with("f3836aef background  2.1.100, ") && s.contains(why)),
                "{why}: {:?}",
                p.skipped
            );
        };

        // waiting on an answer, whatever --include-busy says
        let e = with(&|b| b.state = Some(state::State::Input));
        refused(&e, &busy, "waiting for an answer: claude attach f3836aef");
        // a turn in flight
        let e = with(&|b| b.state = Some(state::State::Run));
        refused(&e, &opts(), "run: rerun when idle, or --include-busy");
        assert_eq!(plan_of(&e, &busy).go_bg.len(), 1);
        // saying nothing at all
        let e = with(&|b| b.state = None);
        refused(&e, &busy, "says nothing of what it is doing");
        // a reply saved for its next start, which the respawn would send
        let e = with(&|b| {
            b.in_flight = Some(taimux_core::status::InFlight {
                tasks: 0,
                queued: 1,
            })
        });
        refused(&e, &busy, "a reply is saved for its next start");
        // a shell its last turn left running
        let e = with(&|b| {
            b.in_flight = Some(taimux_core::status::InFlight {
                tasks: 1,
                queued: 0,
            })
        });
        refused(&e, &opts(), "work still in flight");
        assert_eq!(plan_of(&e, &busy).go_bg.len(), 1);
        // a record that says nothing of it is not taken to mean none
        let e = with(&|b| b.in_flight = None);
        refused(&e, &opts(), "says nothing of work in flight");
        assert_eq!(plan_of(&e, &busy).go_bg.len(), 1);
        // its transcript written to a moment ago
        let mut e = with(&|_| {});
        e.transcript = r#"{"type":"user","timestamp":"2026-09-02T01:23:40Z"}"#.into();
        refused(&e, &opts(), "not settled");
        // an id that is not one
        let e = with(&|b| b.id = "f38; x".into());
        assert!(plan_of(&e, &busy).go_bg.is_empty());
    }

    /// The plan says both halves, since the respawn is the half that never
    /// touches the pane and would otherwise go unmentioned.
    #[test]
    fn the_rendered_plan_names_the_respawn() {
        let mut e = fake();
        e.away
            .insert(11, ("2447b564".into(), "2.1.100".into(), None));
        assert_eq!(
            render(&plan_of(&e, &opts())),
            "claude: 2.1.258 installed at /l/claude\n\n\
             to restart (1):\n\
             \x20 %1    w:1.1          proj: the stale one\n\
             \x20       2.1.100 -> 2.1.258, background session 2447b564, idle\n\
             \x20       claude respawn 2447b564, then command claude attach 2447b564\n"
        );
    }

    /// Idle at its prompt, and still not restartable without asking: the shells
    /// a finished turn left running are the session's children and die with it.
    #[test]
    fn a_pane_with_work_in_flight_waits_for_include_busy() {
        let mut e = fake();
        e.screens.insert(
            "%1".into(),
            "✻ Cogitated for 1m 3s · done 4:55 PM · 2 shells still running\n❯ \n".into(),
        );
        let p = plan_of(&e, &opts());
        assert!(p.go.is_empty());
        assert!(
            p.skipped[0].contains("work still in flight"),
            "{:?}",
            p.skipped
        );

        // The line alone says so as well, on a screen that shows nothing of it.
        let mut e = fake();
        e.hooks.insert("%1".into(), "bg".into());
        let p = plan_of(&e, &opts());
        assert!(p.go.is_empty());
        assert!(
            p.skipped[0].contains("work still in flight"),
            "{:?}",
            p.skipped
        );

        let mut o = opts();
        o.include_busy = true;
        assert_eq!(plan_of(&e, &o).go.len(), 1);
    }

    /// Even with --include-busy: a half-answered permission prompt is the one
    /// state where the Ctrl-C that starts a restart means something else.
    #[test]
    fn a_dialog_blocks_a_restart_even_with_include_busy() {
        let mut e = fake();
        e.screens
            .insert("%1".into(), "output\n\nDo you want to proceed?\n".into());
        let mut o = opts();
        o.include_busy = true;
        let p = plan_of(&e, &o);
        assert!(p.go.is_empty());
        assert!(p.skipped[0].contains("a dialog is waiting for an answer"));
    }

    #[test]
    fn an_unsent_draft_is_left_alone() {
        let mut e = fake();
        e.screens
            .insert("%1".into(), "output\n❯ half a thought\n".into());
        let p = plan_of(&e, &opts());
        assert!(p.skipped[0].contains("unsent text in the prompt box"));
    }

    /// The pane this whole thing is for: three rows, no box on it, and a session
    /// sitting idle behind that. Read at a size it can be read at, it is an
    /// ordinary restart.
    #[test]
    fn a_pane_too_short_for_its_box_is_read_zoomed() {
        let mut e = fake();
        e.screens.insert(
            "%1".into(),
            "  current: 2.1.100 · latest…\n────────\n".into(),
        );
        e.zoomed.insert("%1".into(), "some output\n❯ \n".into());
        let p = plan_of(&e, &opts());
        assert_eq!(e.zooms.get(), 1);
        assert_eq!(p.go.len(), 1);
        assert_eq!(p.go[0].pane, "%1");
        assert!(p.skipped.is_empty());
    }

    /// And the point of reading it rather than assuming: a draft is invisible at
    /// three rows too, so the zoomed read is the only thing that can find one.
    /// Refused here for what is actually in the box, not for the box being
    /// missing.
    #[test]
    fn a_draft_hidden_by_a_short_pane_still_refuses() {
        let mut e = fake();
        e.screens
            .insert("%1".into(), "  current: 2.1.100…\n".into());
        e.zoomed
            .insert("%1".into(), "output\n❯ half a thought\n".into());
        let p = plan_of(&e, &opts());
        assert_eq!(e.zooms.get(), 1);
        assert!(p.go.is_empty());
        assert!(p.skipped[0].contains("unsent text in the prompt box"));
    }

    /// A dialog is off the bottom of a short pane with the box, so the zoomed
    /// read is what finds that too, and a dialog is refused with or without
    /// `--include-busy`.
    #[test]
    fn a_dialog_hidden_by_a_short_pane_is_found_by_the_zoom() {
        let mut e = fake();
        e.screens.insert("%1".into(), "  Bash command\n".into());
        e.zoomed.insert(
            "%1".into(),
            "Do you want to proceed?\n❯ 1. Yes\n  2. No\n".into(),
        );
        let mut o = opts();
        o.include_busy = true;
        let p = plan_of(&e, &o);
        assert!(p.go.is_empty());
        assert!(p.skipped[0].contains("a dialog is waiting for an answer"));
    }

    /// A pane already showing its box is never zoomed: the read is already good,
    /// and a zoom is something the person watching that window sees happen.
    #[test]
    fn a_pane_that_shows_its_box_is_not_zoomed() {
        let e = fake();
        let p = plan_of(&e, &opts());
        assert_eq!(e.zooms.get(), 0);
        assert_eq!(p.go.len(), 1);
    }

    /// A transcript touched in the last 45 seconds is left alone whatever the
    /// screen said, because the screen reading is the fragile half.
    #[test]
    fn a_recently_active_transcript_is_left_alone() {
        let mut e = fake();
        e.transcript = r#"{"type":"user","timestamp":"2026-09-02T01:23:45Z"}"#.into();
        e.now = 1788312225 + 10;
        let p = plan_of(&e, &opts());
        assert!(p.skipped[0].contains("active in the last 45s"));
    }

    #[test]
    fn an_unresolved_pane_says_so_and_earns_the_paragraph() {
        let mut e = fake();
        e.resolved
            .insert("%1".into(), Err("3 transcripts share this title".into()));
        let p = plan_of(&e, &opts());
        assert!(p.go.is_empty());
        assert!(p.unresolved);
        assert!(p.skipped[0].contains("unresolved: 3 transcripts share this title"));
        assert!(render(&p).contains("restart it by hand"));
    }

    /// Two panes on one conversation is the same mistake on a restart as on a
    /// restore: the second one to claim it gets skipped rather than resumed.
    #[test]
    fn one_transcript_is_never_resumed_into_two_panes() {
        let mut e = fake();
        e.vers.insert(22, "2.1.100".into()); // make the second one stale too
        e.resolved
            .insert("%2".into(), Ok("/t/a.jsonl\tpane map".into()));
        let p = plan_of(&e, &opts());
        assert_eq!(p.go.len(), 1);
        assert_eq!(p.go[0].pane, "%1");
        assert!(p.skipped[0].contains("resolves to the same transcript as %1"));
    }

    #[test]
    fn only_panes_narrows_the_plan_without_changing_the_verdicts() {
        let mut o = opts();
        o.only_panes = vec!["%2".into()];
        let p = plan_of(&fake(), &o);
        assert!(p.go.is_empty());
        assert!(p.skipped.is_empty()); // %1 was not considered at all
    }

    #[test]
    fn a_pane_with_no_session_process_is_reported_not_dropped() {
        let rows = "%9\tw:9.9\t/w\tclaude\t0\tclaude\tno pid here";
        let p = plan(rows, "2.1.258", "/l", &opts(), &fake(), "/nowhere", &|| {
            "[]".into()
        });
        assert!(p.go.is_empty());
        assert_eq!(p.skipped.len(), 1);
        assert!(p.skipped[0].contains("no session process was found"));
    }

    #[test]
    fn nothing_to_restart_says_so() {
        let mut e = fake();
        e.vers.insert(11, "2.1.258".into());
        let out = render(&plan_of(&e, &opts()));
        assert!(out.contains("nothing to restart."));
        assert!(!out.contains("to restart ("));
    }

    /// --transcript names the conversation outright, which is the escape hatch
    /// for a pane the ladder refuses.
    #[test]
    fn a_given_transcript_overrides_the_ladder() {
        let mut e = fake();
        e.resolved.insert("%1".into(), Err("no candidate".into()));
        let mut o = opts();
        o.force_transcript = Some("/given.jsonl".into());
        let p = plan_of(&e, &o);
        assert_eq!(p.go.len(), 1);
        assert!(p.go[0].via.contains("--transcript, given"));
        assert!(p.go[0].cmd.contains("--resume /given.jsonl"));
    }
}