kaeru 0.1.6

Reopens your terminal tabs, and the coding agent sessions in them, after the terminal closes or the computer restarts.
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
//! Shell snippets: `kaeru init <shell>` prints the code that one line in your
//! profile loads, and `kaeru shell start` is what that code runs.
//!
//! A snippet registers its tab once, when the shell starts, and keeps the
//! tab's folder up to date. The shell writes the folder itself, so that no
//! process starts on each prompt.

use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use anyhow::{Context, Result};

use crate::agents::{Agent, codex};
use crate::engine::config::Config;
use crate::engine::note::{Note, ShellNote, TerminalRef};
use crate::engine::rules::Liveness;
use crate::engine::rules::TabState;
use crate::engine::tabs::{self, Seen};
use crate::os;
use crate::procs::system::SystemTable;
use crate::procs::{self, ProcInfo, ProcessTable};
use crate::store::{self, Reviewed, Store, StoredNote};
use crate::terminals::{self, Env, Restores, TabToOpen};

/// The PowerShell snippet. It is plain ASCII, because PowerShell reads what
/// `kaeru init` prints in the console's code page.
const POWERSHELL: &str = include_str!("powershell.ps1");

/// The PowerShell function that starts Codex with `--no-daemon`, which the
/// snippet ends with when the `codex-no-daemon` option is on. Plain ASCII,
/// like the snippet.
const POWERSHELL_CODEX: &str = include_str!("powershell-codex.ps1");

/// The bash snippet, for bash 3.2 and later, so that it also runs in the
/// bash that macOS ships.
const BASH: &str = include_str!("bash.sh");

/// The bash function that starts Codex with `--no-daemon`, which the bash
/// and zsh snippets end with when the `codex-no-daemon` option is on. It
/// runs in both shells.
const BASH_CODEX: &str = include_str!("bash-codex.sh");

/// The zsh snippet.
const ZSH: &str = include_str!("zsh.zsh");

/// The fish snippet, for fish 3.1 and later.
const FISH: &str = include_str!("fish.fish");

/// The fish function that starts Codex with `--no-daemon`, which the fish
/// snippet ends with when the `codex-no-daemon` option is on.
const FISH_CODEX: &str = include_str!("fish-codex.fish");

/// The exit code of `kaeru shell start` that tells the snippet to show the
/// picker.
const ASK: u8 = 3;

/// The exit code of `kaeru shell start` that tells the snippet to show the
/// picker through `winpty`, because the terminal gives Windows programs no
/// console, as mintty does.
const ASK_THROUGH_WINPTY: u8 = 5;

/// How long after a terminal that restores its own tabs started kaeru
/// waits for them, before it forgets the notes of tabs that didn't come
/// back. The terminal restores its tabs as it starts.
const RESTORE_WAIT_MS: u64 = 120_000;

/// What `kaeru shell start` tells the snippet.
struct Started {
    /// The tab's `.cwd` file, or `None` when the shell isn't a tab.
    cwd_file: Option<PathBuf>,
    /// Whether this tab shows the picker.
    ask: bool,
    /// Whether the tab's terminal gives Windows programs a console.
    console: bool,
    /// The agent session that ran in this tab before its terminal restored
    /// the tab, and waits to be resumed.
    resume: Option<ToResume>,
}

/// An agent session that ran in a tab before its terminal restored the tab.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ToResume {
    /// The agent's name, such as Claude Code.
    pub agent: String,
    /// Whether the session still runs without a window, because its terminal
    /// ended without ending it, as Warp does on Windows when it crashes.
    pub orphan: bool,
}

/// A shell that `kaeru init` can print a snippet for.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum Shell {
    Powershell,
    Bash,
    Zsh,
    Fish,
}

/// Prints the snippet for `shell`, as the user's options want it.
pub fn print_init(shell: Shell) {
    let config = || {
        Store::open()
            .map(|store| store.config())
            .unwrap_or_default()
    };
    let snippet = match shell {
        Shell::Powershell => powershell_snippet(&config()),
        Shell::Bash => bash_snippet(&config()),
        Shell::Zsh => zsh_snippet(&config()),
        Shell::Fish => fish_snippet(&config()),
    };
    print!("{snippet}");
}

/// Returns the PowerShell snippet: the part that tracks the tab and, when the
/// `codex-no-daemon` option is on, the function that starts Codex with
/// `--no-daemon`.
fn powershell_snippet(config: &Config) -> String {
    let mut snippet = POWERSHELL.to_string();
    if config.codex_no_daemon {
        let one_off: Vec<String> = codex::ONE_OFF_COMMANDS
            .iter()
            .map(|command| format!("'{command}'"))
            .collect();
        snippet.push_str(&POWERSHELL_CODEX.replace("KAERU_ONE_OFF_COMMANDS", &one_off.join(", ")));
    }
    snippet
}

/// Returns the bash snippet: the part that tracks the tab and, when the
/// `codex-no-daemon` option is on, the function that starts Codex with
/// `--no-daemon`.
fn bash_snippet(config: &Config) -> String {
    with_codex_function(BASH, config)
}

/// Returns the zsh snippet, with the same Codex function as bash's.
fn zsh_snippet(config: &Config) -> String {
    with_codex_function(ZSH, config)
}

/// Returns the fish snippet, followed by fish's function that starts Codex
/// with `--no-daemon` when the `codex-no-daemon` option is on.
fn fish_snippet(config: &Config) -> String {
    let mut snippet = FISH.to_string();
    if config.codex_no_daemon {
        snippet.push_str(
            &FISH_CODEX.replace("KAERU_ONE_OFF_COMMANDS", &codex::ONE_OFF_COMMANDS.join(" ")),
        );
    }
    snippet
}

/// Returns `snippet`, followed by the function that starts Codex with
/// `--no-daemon` when the `codex-no-daemon` option is on.
fn with_codex_function(snippet: &str, config: &Config) -> String {
    let mut snippet = snippet.to_string();
    if config.codex_no_daemon {
        snippet.push_str(&BASH_CODEX.replace(
            "KAERU_ONE_OFF_COMMANDS",
            &codex::ONE_OFF_COMMANDS.join(" | "),
        ));
    }
    snippet
}

/// Records a shell that started in a tab, for `kaeru shell start`. It prints
/// the path of the tab's `.cwd` file for the snippet, or nothing when the
/// shell isn't a tab, and exits with code 3 when the tab should show the
/// picker. `parent` is the shell's parent, for a shell whose parent the OS
/// doesn't record. It never fails the shell: problems go to the log.
pub fn start(pid: u32, parent: Option<u32>) -> ExitCode {
    let Ok(store) = Store::open() else {
        return ExitCode::SUCCESS;
    };
    match record(&store, pid, parent) {
        Ok(started) => {
            if let Some(cwd_file) = started.cwd_file {
                println!("{}", cwd_file.display());
            }
            // The terminal is still setting the tab up and sends it input,
            // so kaeru doesn't ask here, which would read that input as the
            // answer. You resume the session when the tab is ready.
            match started.resume {
                Some(ToResume {
                    agent,
                    orphan: false,
                }) => eprintln!(
                    "kaeru: this tab had a {agent} session. To resume it here, run kaeru resume."
                ),
                Some(ToResume {
                    agent,
                    orphan: true,
                }) => eprintln!(
                    "kaeru: this tab had a {agent} session, which still runs without a window \
                     since the terminal closed. To end it and resume it here, run kaeru resume."
                ),
                None => {}
            }
            if started.ask {
                return ExitCode::from(if started.console {
                    ASK
                } else {
                    ASK_THROUGH_WINPTY
                });
            }
        }
        Err(error) => store.log(&format!("shell start: {error:#}")),
    }
    ExitCode::SUCCESS
}

/// Writes the note of the shell with the id `pid`, unless it has one,
/// deletes the notes of closed tabs, and tells the tab about waiting tabs.
fn record(store: &Store, pid: u32, parent: Option<u32>) -> Result<Started> {
    let mut table = SystemTable::snapshot();
    let mut lineage = table.lineage(pid);
    if let Some(parent) = parent {
        lineage = procs::with_parent(lineage, table.lineage(parent));
    }
    let env: Env = std::env::vars().collect();
    let session = os::session_id()?;
    let config = store.config();
    let cwd = std::env::current_dir()?.display().to_string();
    let note = shell_note(pid, &lineage, &env, &session, cwd)?;
    let console = note
        .as_ref()
        .and_then(Note::terminal)
        .is_none_or(|terminal| terminals::gives_a_console(&terminal.adapter));
    let path = match note {
        // A shell that loads its profile again keeps its note, and with it
        // what kaeru already knows about the tab.
        Some(note) if store.path_of(&note).exists() => Some(store.path_of(&note)),
        Some(note) => Some(store.save(&note)?),
        None => None,
    };
    let reviewed = store::review(store, &table, &session, config.single_window_close);
    let note = path.as_ref().and_then(|path| store.read(path).ok());
    let claimed = note
        .as_ref()
        .map(|note| claim(store, &reviewed, note, now_ms(), &table))
        .unwrap_or_default();
    // Only a tab's own shell says anything, so a shell nested in it doesn't.
    let ask = match &note {
        Some(note) => {
            let command_line = lineage
                .first()
                .and_then(|shell| shell.command_line.as_deref())
                .unwrap_or_default();
            let restored = claimed
                .restored
                .then(|| note.terminal().map(|terminal| terminal.adapter.as_str()))
                .flatten();
            let askable = askable(reviewed, restored);
            let runs = runs_a_command(command_line) || std::env::var_os(RUN_VAR).is_some();
            offer(store, &askable, &config, runs)?
        }
        None => false,
    };
    Ok(Started {
        cwd_file: path.map(|path| store::cwd_file(&path)),
        ask,
        console,
        resume: claimed.resume,
    })
}

/// Returns the notes that a new tab may ask about: the ones that are still
/// there after [`claim`], except, in a tab that its terminal brought back by
/// itself, the notes of that terminal's other tabs. The terminal may be
/// bringing them back at the same moment, so asking about them could bring
/// them back twice.
fn askable(reviewed: Vec<Reviewed>, restored: Option<&str>) -> Vec<Reviewed> {
    reviewed
        .into_iter()
        .filter(|reviewed| reviewed.stored.path.exists())
        .filter(|reviewed| {
            restored.is_none_or(|adapter| {
                reviewed
                    .stored
                    .note
                    .terminal()
                    .is_none_or(|terminal| terminal.adapter != adapter)
            })
        })
        .collect()
}

/// What [`claim`] found out about a tab.
#[derive(Debug, Default, PartialEq, Eq)]
struct Claimed {
    /// Whether the tab's terminal brought it back by itself: a note from
    /// the terminal's run before has the tab's id.
    restored: bool,
    /// The agent session that ran in the tab, and waits to be resumed.
    resume: Option<ToResume>,
}

/// Takes over the notes of a tab that its terminal restored by itself, for
/// the shell note `note` of the new tab, and says whether the terminal did,
/// and which agent session ran in the tab and waits to be resumed. A
/// restored tab has the same tab id as before, and a note from the
/// terminal's run before with that id is the tab's: its old shell note is
/// done, and its agent note stays for `kaeru resume`. That agent note may
/// belong to a session that still runs, without a window, because its
/// terminal ended without ending it. Of a terminal that always restores its
/// tabs, waiting notes whose tabs didn't come back, once the terminal has
/// had time to restore them, are forgotten. Of a terminal that only
/// sometimes does, they wait to be offered.
fn claim(
    store: &Store,
    reviewed: &[Reviewed],
    note: &Note,
    now_ms: u64,
    table: &dyn ProcessTable,
) -> Claimed {
    let mut claimed = Claimed::default();
    let Some(terminal) = note.terminal() else {
        return claimed;
    };
    let Some(tab_id) = terminal.tab_id.as_deref() else {
        return claimed;
    };
    let restores = terminals::restores_its_own_tabs(&terminal.adapter);
    if restores == Restores::Never {
        return claimed;
    }
    let waited = now_ms.saturating_sub(terminal.process.started_ms) > RESTORE_WAIT_MS;
    for reviewed in reviewed {
        let Some(old) = reviewed.stored.note.terminal() else {
            continue;
        };
        let from_before = old.adapter == terminal.adapter
            && old.process != terminal.process
            && procs::liveness(table, &old.process) != Liveness::Running;
        if !from_before {
            continue;
        }
        if old.tab_id.as_deref() == Some(tab_id) {
            claimed.restored = true;
            match &reviewed.stored.note {
                Note::Shell(_) => store.remove(&reviewed.stored),
                Note::Agent(agent) => {
                    let orphan = procs::liveness(table, &agent.process) == Liveness::Running;
                    if reviewed.state == TabState::Waiting || orphan {
                        claimed.resume = Some(ToResume {
                            agent: Agent::from_id(&agent.agent).map_or_else(
                                || agent.agent.clone(),
                                |known| known.name().to_string(),
                            ),
                            orphan,
                        });
                    }
                }
            }
        } else if restores == Restores::Always && waited && reviewed.state == TabState::Waiting {
            store.remove(&reviewed.stored);
        }
    }
    claimed
}

/// How long after a terminal that brings back its own tabs started the
/// picker waits before it looks at the waiting tabs. The terminal starts the
/// tabs it brings back all at once, and each takes over its notes when its
/// shell has read its startup files, which can take a few seconds.
const RESTORE_SETTLE_MS: u64 = 5_000;

/// Returns how long the picker waits, in a tab of `terminal`, before it
/// looks at the waiting tabs, so that the tabs that the terminal is bringing
/// back by itself have taken over their notes, and the picker doesn't offer
/// them again. It doesn't wait in a terminal that never brings back its own
/// tabs, or that started long enough ago.
pub fn restore_settle(terminal: &TerminalRef, now_ms: u64) -> Duration {
    if terminals::restores_its_own_tabs(&terminal.adapter) == Restores::Never {
        return Duration::ZERO;
    }
    let age = now_ms.saturating_sub(terminal.process.started_ms);
    Duration::from_millis(RESTORE_SETTLE_MS.saturating_sub(age))
}

/// Returns the time now, in milliseconds since the Unix epoch.
pub fn now_ms() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .ok()
        .and_then(|since| u64::try_from(since.as_millis()).ok())
        .unwrap_or(0)
}

/// Tells a new tab about the tabs that are waiting, and returns whether it
/// shows the picker. It does when the user wants that, the shell wasn't
/// started to run a command, as a reopened agent tab is, and no other tab has
/// asked about these tabs yet. Otherwise it prints a one-line reminder.
/// Waiting notes are deleted when the options leave all of them out, because
/// they would never come back.
fn offer(
    store: &Store,
    reviewed: &[Reviewed],
    config: &Config,
    runs_a_command: bool,
) -> Result<bool> {
    // Tabs that their terminal brings back by itself aren't offered.
    let waiting: Vec<&StoredNote> = reviewed
        .iter()
        .filter(|reviewed| reviewed.state == TabState::Waiting)
        .map(|reviewed| &reviewed.stored)
        .filter(|stored| !left_to_its_terminal(&stored.note, reviewed))
        .collect();
    let notes: Vec<(Note, Seen)> = waiting
        .iter()
        .map(|stored| (stored.note.clone(), store::last_seen(stored)))
        .collect();
    let count = tabs::to_offer(&notes, config).len();
    if count == 0 {
        for stored in &waiting {
            store.remove(stored);
        }
        return Ok(false);
    }
    // Another tab holds the lock while it asks or reopens these tabs, and a
    // tab that it reopens would only repeat what that tab is showing.
    let Some(_lock) = store.try_lock()? else {
        return Ok(false);
    };
    if config.ask_on_start && !runs_a_command {
        let mut new = false;
        for stored in &waiting {
            // Another tab may have asked since the review, so the file on
            // disk decides.
            if let Ok(mut note) = store.read(&stored.path)
                && !note.offered()
            {
                note.set_offered();
                store.save(&note)?;
                new = true;
            }
        }
        if new {
            return Ok(true);
        }
    }
    let (tabs, them) = if count == 1 {
        ("1 tab is".to_string(), "it")
    } else {
        (format!("{count} tabs are"), "them")
    };
    eprintln!("kaeru: {tabs} waiting to come back. Run kaeru to see {them}.");
    Ok(false)
}

/// The start of the name of each file that kaeru writes for bash to bring
/// back a tab with its agent session.
const RUN_FILE_PREFIX: &str = "kaeru-run-";

/// The variable that gives the shell of a reopened tab the code that goes
/// to the tab's folder and resumes its agent session. The snippet takes it
/// out of the environment and runs the code at the first prompt.
pub const RUN_VAR: &str = "KAERU_RUN";

/// Returns the command that a terminal starts in a reopened tab that runs
/// something: the tab's shell, through `env`, with [`RUN_VAR`] set to the
/// code that runs it, so that the tab is the shell you use, with your
/// startup files, which then runs the code as if you typed it. Returns
/// `None` when the tab runs nothing, or when its shell isn't bash, zsh or
/// fish, whose snippets run the code.
pub fn shell_with_run(tab: &TabToOpen) -> Option<Vec<String>> {
    if tab.run.is_empty() {
        return None;
    }
    let name = tab.shell.as_deref()?;
    let shell = match name {
        "bash" => Shell::Bash,
        "zsh" => Shell::Zsh,
        "fish" => Shell::Fish,
        _ => return None,
    };
    let program = tab.shell_exe.clone().unwrap_or_else(|| name.to_string());
    let code = run_code(shell, &tab.cwd, &tab.run);
    Some(vec!["env".into(), format!("{RUN_VAR}={code}"), program])
}

/// How long kaeru keeps the files it wrote for bash. bash reads a file once,
/// when its tab starts, so an old one is done.
const RUN_FILE_AGE: Duration = Duration::from_secs(24 * 60 * 60);

/// Returns the file for bash to read with `--rcfile` instead of `~/.bashrc`,
/// so that a reopened tab runs an agent's resume command and then stays a
/// bash to type in. It reads the files that a login shell reads, as Git Bash
/// and terminals on macOS start bash, or `~/.bashrc` when there are none,
/// then goes to the folder and runs the command.
pub fn bash_run_script(cwd: &str, run: &[String]) -> String {
    format!(
        "# kaeru wrote this file, for bash to read instead of ~/.bashrc when it\n\
         # brings back a tab with its agent session. kaeru deletes it later.\n\
         [ -f /etc/profile ] && . /etc/profile\n\
         __kaeru_login=\n\
         for __kaeru_file in ~/.bash_profile ~/.bash_login ~/.profile; do\n\
         \x20   if [ -f \"$__kaeru_file\" ]; then\n\
         \x20       . \"$__kaeru_file\"\n\
         \x20       __kaeru_login=1\n\
         \x20       break\n\
         \x20   fi\n\
         done\n\
         [ -z \"$__kaeru_login\" ] && [ -f ~/.bashrc ] && . ~/.bashrc\n\
         unset __kaeru_login __kaeru_file\n\
         {}\n",
        bash_run_line(cwd, run)
    )
}

/// Returns the bash line that goes to the folder, then runs the command, if
/// there is one. zsh reads it the same way.
pub fn bash_run_line(cwd: &str, run: &[String]) -> String {
    let cd = format!("cd -- {}", bash_word(cwd));
    if run.is_empty() {
        return cd;
    }
    let words: Vec<String> = run.iter().map(|word| bash_word(word)).collect();
    format!("{cd} && {}", words.join(" "))
}

/// Returns the PowerShell lines that go to the folder, then run the command.
/// Words that aren't plain are quoted.
pub fn powershell_run_lines(cwd: &str, run: &[String]) -> String {
    let words: Vec<String> = run.iter().map(|word| powershell_word(word)).collect();
    format!(
        "Set-Location -LiteralPath '{}'\n& {}",
        cwd.replace('\'', "''"),
        words.join(" ")
    )
}

/// Returns one word of a PowerShell command line: as it is when it holds only
/// letters, digits, `-`, `_` and `.`, and in single quotes otherwise.
fn powershell_word(word: &str) -> String {
    let plain = !word.is_empty()
        && word
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'));
    if plain {
        word.to_string()
    } else {
        format!("'{}'", word.replace('\'', "''"))
    }
}

/// Returns the code that `shell` runs to go to the folder and run the
/// command. The snippet's `kaeru` function runs it for `kaeru resume`.
pub fn run_code(shell: Shell, cwd: &str, run: &[String]) -> String {
    match shell {
        Shell::Powershell => powershell_run_lines(cwd, run),
        // zsh reads bash's quoting the same way.
        Shell::Bash | Shell::Zsh => bash_run_line(cwd, run),
        Shell::Fish => fish_run_line(cwd, run),
    }
}

/// Returns the fish line that goes to the folder, then runs the command, if
/// there is one.
pub fn fish_run_line(cwd: &str, run: &[String]) -> String {
    let cd = format!("cd -- {}", fish_word(cwd));
    if run.is_empty() {
        return cd;
    }
    let words: Vec<String> = run.iter().map(|word| fish_word(word)).collect();
    format!("{cd} && {}", words.join(" "))
}

/// Returns one word of a fish command line: as it is when it holds only
/// letters, digits and `-_./:=@%+,`, and in single quotes otherwise, where
/// fish reads a backslash before a quote or a backslash as an escape.
fn fish_word(word: &str) -> String {
    let plain = !word.is_empty()
        && word
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || "-_./:=@%+,".contains(c));
    if plain {
        word.to_string()
    } else {
        format!("'{}'", word.replace('\\', r"\\").replace('\'', r"\'"))
    }
}

/// Returns one word of a bash command line: as it is when it holds only
/// letters, digits and `-_./:=@%+,`, and in single quotes otherwise.
fn bash_word(word: &str) -> String {
    let plain = !word.is_empty()
        && word
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || "-_./:=@%+,".contains(c));
    if plain {
        word.to_string()
    } else {
        format!("'{}'", word.replace('\'', r"'\''"))
    }
}

/// Writes the file that [`bash_run_script`] returns, in the `run` folder of
/// the state folder, and returns its path. Files from earlier days are
/// deleted first.
///
/// # Errors
///
/// Fails when the folder or the file can't be written.
pub fn write_bash_run_file(state: &Path, cwd: &str, run: &[String]) -> Result<PathBuf> {
    let folder = state.join("run");
    std::fs::create_dir_all(&folder)
        .with_context(|| format!("can't create {}", folder.display()))?;
    if let Ok(entries) = std::fs::read_dir(&folder) {
        for entry in entries.flatten() {
            let old = entry
                .metadata()
                .and_then(|metadata| metadata.modified())
                .ok()
                .and_then(|modified| modified.elapsed().ok())
                .is_some_and(|age| age > RUN_FILE_AGE);
            if old {
                let _ = std::fs::remove_file(entry.path());
            }
        }
    }
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |since| since.as_nanos());
    let file = folder.join(format!("{RUN_FILE_PREFIX}{now}.sh"));
    std::fs::write(&file, bash_run_script(cwd, run))
        .with_context(|| format!("can't write {}", file.display()))?;
    Ok(file)
}

/// Returns whether kaeru leaves a waiting note's tab to its terminal, which
/// brings it back by itself, so that the picker doesn't offer it: every tab
/// of a terminal that always does, and a tab that a terminal that only
/// sometimes does brought back, whose agent session waits there for
/// `kaeru resume`. `reviewed` holds every note, which tells whether such a
/// tab is back: an open tab of the same terminal has its id.
pub fn left_to_its_terminal(note: &Note, reviewed: &[Reviewed]) -> bool {
    let Some(terminal) = note.terminal() else {
        return false;
    };
    match terminals::restores_its_own_tabs(&terminal.adapter) {
        Restores::Never => false,
        Restores::Always => true,
        Restores::Sometimes => {
            terminal.tab_id.is_some()
                && reviewed.iter().any(|other| {
                    other.state == TabState::Open
                        && matches!(other.stored.note, Note::Shell(_))
                        && other.stored.note.terminal().is_some_and(|back| {
                            back.adapter == terminal.adapter
                                && back.tab_id == terminal.tab_id
                                && back.process != terminal.process
                        })
                })
        }
    }
}

/// Returns whether a shell's command line runs a command or a script, as
/// kaeru's reopened agent tabs do, rather than starting a shell to type in:
/// PowerShell with a command, a bash with `-c`, or a bash that reads a file
/// that kaeru wrote. PowerShell takes any prefix of a parameter's name, such
/// as `-c` for `-Command`, and `-ec` for `-EncodedCommand`.
pub fn runs_a_command(command_line: &str) -> bool {
    if command_line.contains(RUN_FILE_PREFIX) {
        return true;
    }
    command_line.split_whitespace().skip(1).any(|argument| {
        let Some(name) = argument.strip_prefix(['-', '/']) else {
            return false;
        };
        let name = name.to_ascii_lowercase();
        !name.is_empty()
            && name.chars().all(|c| c.is_ascii_alphabetic())
            && (name == "ec"
                || ["command", "file", "encodedcommand"]
                    .iter()
                    .any(|parameter| parameter.starts_with(&name)))
    })
}

/// Returns the note for the shell with the id `pid`, from its lineage, or
/// `None` when the shell isn't a tab of a known terminal. A shell inside
/// another program in a tab, such as a nested shell, belongs to that tab,
/// and kaeru can only reopen tabs of terminals that it has an adapter for.
///
/// # Errors
///
/// Fails when the shell's process is gone or its start time can't be read.
fn shell_note(
    pid: u32,
    lineage: &[ProcInfo],
    env: &Env,
    session: &str,
    cwd: String,
) -> Result<Option<Note>> {
    let shell = lineage
        .first()
        .filter(|process| process.pid == pid)
        .context("the shell's process is gone")?;
    let Some((0, terminal)) = terminals::tab_of(&terminals::all(), env, lineage) else {
        return Ok(None);
    };
    Ok(Some(Note::Shell(ShellNote {
        process: shell
            .to_ref()
            .context("the shell's start time can't be read")?,
        shell: shell_name(&shell.name),
        cwd,
        terminal: Some(terminal),
        session: session.into(),
        offered: false,
    })))
}

/// Returns the name kaeru stores for a shell's executable: its file name,
/// without `.exe`, such as `powershell` or `pwsh`.
pub fn shell_name(executable: &str) -> String {
    let path = Path::new(executable);
    let is_exe = path
        .extension()
        .is_some_and(|extension| extension.eq_ignore_ascii_case("exe"));
    let name = if is_exe {
        path.file_stem()
    } else {
        path.file_name()
    };
    name.map_or_else(
        || executable.to_string(),
        |name| name.to_string_lossy().into_owned(),
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::procs::{fake::FakeTable, lineage};

    /// A tab's shell (20) in Windows Terminal (10), with a shell inside it
    /// (30).
    fn tab_table() -> FakeTable {
        FakeTable::new(&[
            (30, Some(20), "pwsh.exe", Some(3_000)),
            (20, Some(10), "powershell.exe", Some(2_000)),
            (10, None, "WindowsTerminal.exe", Some(1_000)),
        ])
    }

    fn tab_env() -> Env {
        Env::from([("WT_SESSION".to_string(), "x".to_string())])
    }

    #[test]
    fn the_shell_of_a_tab_gets_a_note() {
        let table = tab_table();
        let note = shell_note(20, &lineage(&table, 20), &tab_env(), "win-1", "C:\\".into());
        let Some(Note::Shell(note)) = note.unwrap() else {
            panic!("no shell note");
        };
        assert_eq!(note.shell, "powershell");
        assert_eq!(note.terminal.unwrap().process.pid, 10);
    }

    #[test]
    fn a_shell_inside_a_tab_gets_no_note() {
        let table = tab_table();
        let note = shell_note(30, &lineage(&table, 30), &tab_env(), "win-1", "C:\\".into());
        assert!(note.unwrap().is_none());
    }

    #[test]
    fn a_shell_outside_known_terminals_gets_no_note() {
        let table = tab_table();
        let note = shell_note(
            20,
            &lineage(&table, 20),
            &Env::new(),
            "win-1",
            "C:\\".into(),
        );
        assert!(note.unwrap().is_none());
    }

    #[test]
    fn shell_names_drop_the_exe_extension() {
        assert_eq!(shell_name("powershell.exe"), "powershell");
        assert_eq!(shell_name("pwsh.EXE"), "pwsh");
        assert_eq!(shell_name("zsh"), "zsh");
    }

    #[test]
    fn the_powershell_snippet_is_ascii_and_starts_the_tab() {
        assert!(POWERSHELL.is_ascii());
        assert!(POWERSHELL.contains("kaeru shell start --pid $PID"));
    }

    #[test]
    fn the_zsh_snippet_is_ascii_and_starts_the_tab() {
        assert!(ZSH.is_ascii());
        assert!(ZSH.contains("kaeru shell start --pid $$"));
        let with_codex = zsh_snippet(&Config {
            codex_no_daemon: true,
            ..Config::default()
        });
        assert!(with_codex.starts_with(ZSH));
        assert!(with_codex.contains("codex() {"));
        assert!(!zsh_snippet(&Config::default()).contains("codex() {"));
    }

    #[test]
    fn the_bash_snippet_is_ascii_and_starts_the_tab() {
        assert!(BASH.is_ascii());
        assert!(BASH.contains("kaeru shell start --pid \"$__kaeru_pid\""));
        let with_codex = bash_snippet(&Config {
            codex_no_daemon: true,
            ..Config::default()
        });
        assert!(with_codex.starts_with(BASH));
        assert!(with_codex.contains("codex() {"));
        assert!(with_codex.contains(" | exec | "));
        assert!(!with_codex.contains("KAERU_ONE_OFF_COMMANDS"));
        assert!(!bash_snippet(&Config::default()).contains("codex() {"));
    }

    /// Returns a bash to test the snippet with: Git for Windows' on Windows,
    /// and the system's elsewhere. `None` when there is none, so that the
    /// tests that need it can't fail on a machine without it.
    fn test_bash() -> Option<std::path::PathBuf> {
        let bash = if cfg!(windows) {
            std::path::Path::new(&std::env::var_os("ProgramFiles")?).join(r"Git\bin\bash.exe")
        } else {
            std::path::PathBuf::from("/bin/bash")
        };
        bash.is_file().then_some(bash)
    }

    /// Runs `script`, which loads the snippet, in an interactive bash, with a
    /// stand-in for `kaeru` that tracks the tab in `dir`, and returns what it
    /// prints. bash runs no prompt in `-c` mode, so the script calls the
    /// prompt command itself.
    fn run_bash_snippet(bash: &Path, dir: &Path, script: &str) -> String {
        run_bash_snippet_with(bash, dir, "", script)
    }

    /// Runs `script` as [`run_bash_snippet`] does, with `first` at the start
    /// of the stand-in for `kaeru`, so that it can answer some commands
    /// itself.
    fn run_bash_snippet_with(bash: &Path, dir: &Path, first: &str, script: &str) -> String {
        let cwd_file = dir.join("tab.cwd");
        let stand_in = dir.join("kaeru");
        std::fs::write(
            &stand_in,
            format!(
                "#!/bin/sh\n{first}\nprintf '%s\n' '{}'\n",
                cwd_file.display()
            ),
        )
        .unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&stand_in, std::fs::Permissions::from_mode(0o755)).unwrap();
        }
        let snippet_file = dir.join("snippet.sh");
        std::fs::write(&snippet_file, BASH).unwrap();
        let output = std::process::Command::new(bash)
            .args(["--norc", "--noprofile", "-i", "-c"])
            .arg(format!("cd \"$1\" && PATH=\"$PWD:$PATH\" && {script}"))
            .arg("bash")
            .arg(dir)
            .output()
            .unwrap();
        String::from_utf8_lossy(&output.stdout).trim().to_string()
    }

    #[test]
    fn a_bash_run_file_goes_to_the_folder_and_runs_the_command() {
        let script = bash_run_script(
            r"C:\Users\demo\code\it's here",
            &["claude".into(), "--resume".into(), "a b".into()],
        );
        assert!(
            script.ends_with(
                "cd -- 'C:\\Users\\demo\\code\\it'\\''s here' && claude --resume 'a b'\n"
            )
        );
        assert!(script.contains(". /etc/profile"));
        assert!(script.is_ascii());
    }

    #[test]
    fn a_bash_tab_that_reads_kaeru_s_file_runs_a_command() {
        assert!(runs_a_command(
            r#""C:\Program Files\Git\usr\bin\bash.exe" --rcfile C:/state/run/kaeru-run-1.sh -i"#
        ));
        assert!(runs_a_command("bash -c ls"));
        assert!(!runs_a_command("bash -i -l"));
        assert!(!runs_a_command("bash --login -i"));
    }

    #[test]
    fn the_bash_run_file_runs_in_bash() {
        let Some(bash) = test_bash() else { return };
        let dir = tempfile::tempdir().unwrap();
        let folder = dir.path().join("it's a folder");
        std::fs::create_dir(&folder).unwrap();
        let file = write_bash_run_file(
            dir.path(),
            &folder.display().to_string(),
            &["echo".into(), "resumed".into()],
        )
        .unwrap();
        // A HOME without login files, so that only kaeru's file runs.
        let output = std::process::Command::new(bash)
            .env("HOME", dir.path())
            .args(["-c", ". \"$1\"; pwd", "bash"])
            .arg(file.display().to_string().replace('\\', "/"))
            .output()
            .unwrap();
        let printed = String::from_utf8_lossy(&output.stdout);
        let mut lines = printed.lines();
        assert_eq!(lines.next(), Some("resumed"), "{output:?}");
        assert!(
            lines
                .next()
                .is_some_and(|pwd| pwd.ends_with("it's a folder"))
        );
    }

    #[test]
    fn the_bash_prompt_theme_still_sees_whether_the_last_command_failed() {
        let Some(bash) = test_bash() else { return };
        let dir = tempfile::tempdir().unwrap();
        let theme = "PROMPT_COMMAND='echo \"theme sees $?\"'";
        // The theme comes first, as in a ~/.bashrc that loads kaeru last.
        let shown = |command: &str| {
            let script = format!("{theme}; . ./snippet.sh; {command}; eval \"$PROMPT_COMMAND\"");
            run_bash_snippet(&bash, dir.path(), &script)
        };
        assert_eq!(shown("false"), "theme sees 1");
        assert_eq!(shown("true"), "theme sees 0");
    }

    #[test]
    fn the_bash_prompt_writes_the_folder_and_loads_once() {
        let Some(bash) = test_bash() else { return };
        let dir = tempfile::tempdir().unwrap();
        let shown = run_bash_snippet(
            &bash,
            dir.path(),
            ". ./snippet.sh; . ./snippet.sh; eval \"$PROMPT_COMMAND\"; echo \"$PROMPT_COMMAND\"",
        );
        assert_eq!(shown, "__kaeru_prompt", "one prompt function, once");
        let written = std::fs::read_to_string(dir.path().join("tab.cwd")).unwrap();
        let written = PathBuf::from(written.trim().replace('/', std::path::MAIN_SEPARATOR_STR));
        assert_eq!(
            written.canonicalize().unwrap(),
            dir.path().canonicalize().unwrap()
        );
    }

    #[test]
    fn the_bash_function_runs_the_code_that_kaeru_resume_prints() {
        let Some(bash) = test_bash() else { return };
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir(dir.path().join("it's here")).unwrap();
        let answer = format!(
            "if [ \"$*\" = 'resume --shell bash' ]; then\n\
             echo 'Resuming the session' >&2\n\
             printf '%s\\n' {}\n\
             exit 0\nfi",
            bash_word(&bash_run_line("it's here", &["pwd".into()]))
        );
        let shown = run_bash_snippet_with(
            &bash,
            dir.path(),
            &answer,
            ". ./snippet.sh; kaeru resume; kaeru list",
        );
        let mut lines = shown.lines();
        assert!(
            lines.next().is_some_and(|pwd| pwd.ends_with("/it's here")),
            "{shown}"
        );
        // Other commands run kaeru as they are.
        assert!(lines.next().is_some_and(|line| line.ends_with("tab.cwd")));
    }

    /// Writes the `KAERU_RUN` code for `shell` that goes to the folder
    /// `it's here` in `dir`, which it makes, and prints the folder, to the
    /// file `dir/code`, where the test shell reads it from.
    fn write_run_code(dir: &Path, shell: Shell) {
        std::fs::create_dir(dir.join("it's here")).unwrap();
        let code = run_code(shell, "it's here", &["pwd".into()]);
        std::fs::write(dir.join("code"), code).unwrap();
    }

    #[test]
    fn the_bash_prompt_runs_the_code_of_a_reopened_tab_once() {
        let Some(bash) = test_bash() else { return };
        let dir = tempfile::tempdir().unwrap();
        write_run_code(dir.path(), Shell::Bash);
        let script = format!(
            "export {RUN_VAR}=\"$(cat code)\"; . ./snippet.sh; eval \"$PROMPT_COMMAND\"; \
             eval \"$PROMPT_COMMAND\"; echo \"left: ${{{RUN_VAR}-none}}\""
        );
        let shown = run_bash_snippet_with(&bash, dir.path(), "", &script);
        let lines: Vec<&str> = shown.lines().collect();
        assert_eq!(lines.len(), 2, "{shown}");
        assert!(lines[0].ends_with("/it's here"), "{shown}");
        assert_eq!(lines[1], "left: none");
    }

    #[test]
    fn the_zsh_prompt_runs_the_code_of_a_reopened_tab_once() {
        let Some(zsh) = test_zsh() else { return };
        let dir = tempfile::tempdir().unwrap();
        write_run_code(dir.path(), Shell::Zsh);
        let script = format!(
            "export {RUN_VAR}=\"$(cat code)\"; . ./snippet.zsh; __kaeru_precmd; \
             __kaeru_precmd; echo \"left: ${{{RUN_VAR}-none}}\""
        );
        let shown = run_zsh_snippet_with(&zsh, dir.path(), "", &script);
        let lines: Vec<&str> = shown.lines().collect();
        assert_eq!(lines.len(), 2, "{shown}");
        assert!(lines[0].ends_with("/it's here"), "{shown}");
        assert_eq!(lines[1], "left: none");
    }

    #[test]
    fn a_reopened_tab_starts_its_shell_with_the_code_to_run() {
        let tab = |shell: &str, run: &[&str]| TabToOpen {
            title: "api-server".into(),
            cwd: "/home/demo/code/api-server".into(),
            profile: None,
            shell: Some(shell.into()),
            run: run.iter().map(|word| word.to_string()).collect(),
            shell_exe: None,
            rcfile: None,
        };
        let resume = ["claude", "--resume", "00000000-0000-4000-8000-000000000001"];
        assert_eq!(
            shell_with_run(&tab("zsh", &resume)).unwrap(),
            [
                "env",
                "KAERU_RUN=cd -- /home/demo/code/api-server && claude --resume \
                 00000000-0000-4000-8000-000000000001",
                "zsh"
            ]
        );
        let mut in_fish = tab("fish", &resume);
        in_fish.shell_exe = Some("/usr/bin/fish".into());
        let started = shell_with_run(&in_fish).unwrap();
        assert_eq!(started.last().map(String::as_str), Some("/usr/bin/fish"));
        // A tab that runs nothing starts the terminal's own shell, and kaeru
        // doesn't know how to hand the code to other shells.
        assert!(shell_with_run(&tab("bash", &[])).is_none());
        assert!(shell_with_run(&tab("powershell", &resume)).is_none());
    }

    /// Returns a zsh to test the snippet with, the one that macOS ships, or
    /// `None` when there is none, as on most Linux and Windows machines.
    fn test_zsh() -> Option<std::path::PathBuf> {
        ["/bin/zsh", "/usr/bin/zsh"]
            .iter()
            .map(std::path::PathBuf::from)
            .find(|zsh| zsh.is_file())
    }

    /// Runs `script`, which loads the snippet, in an interactive zsh that
    /// reads no startup files, as [`run_bash_snippet_with`] does in bash.
    /// zsh runs no prompt in `-c` mode, so the script calls the precmd
    /// function itself.
    fn run_zsh_snippet_with(zsh: &Path, dir: &Path, first: &str, script: &str) -> String {
        write_zsh_snippet(dir, first);
        let output = std::process::Command::new(zsh)
            .args(["-f", "-i", "-c"])
            .arg(format!("cd \"$1\" && PATH=\"$PWD:$PATH\" && {script}"))
            .arg("zsh")
            .arg(dir)
            .output()
            .unwrap();
        String::from_utf8_lossy(&output.stdout).trim().to_string()
    }

    /// Writes the zsh snippet to `dir`, and a stand-in for `kaeru` that
    /// tracks the tab in `dir/tab.cwd`, with `first` at its start, so that
    /// it can answer some commands itself.
    fn write_zsh_snippet(dir: &Path, first: &str) {
        write_stand_in(dir, first);
        std::fs::write(dir.join("snippet.zsh"), ZSH).unwrap();
    }

    /// Writes a stand-in for `kaeru` to `dir`, which tracks the tab in
    /// `dir/tab.cwd`, with `first` at its start, so that it can answer some
    /// commands itself.
    fn write_stand_in(dir: &Path, first: &str) {
        let cwd_file = dir.join("tab.cwd");
        let stand_in = dir.join("kaeru");
        std::fs::write(
            &stand_in,
            format!(
                "#!/bin/sh\n{first}\nprintf '%s\n' '{}'\n",
                cwd_file.display()
            ),
        )
        .unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&stand_in, std::fs::Permissions::from_mode(0o755)).unwrap();
        }
    }

    /// Returns a fish to test the snippet with, or `None` when there is
    /// none, as on Windows.
    fn test_fish() -> Option<std::path::PathBuf> {
        [
            "/usr/bin/fish",
            "/bin/fish",
            "/usr/local/bin/fish",
            "/opt/homebrew/bin/fish",
        ]
        .iter()
        .map(std::path::PathBuf::from)
        .find(|fish| fish.is_file())
    }

    /// Runs `script`, which loads the snippet, in an interactive fish that
    /// reads no config files, with the stand-in `kaeru` of
    /// [`write_stand_in`] first on the PATH. fish draws no prompt in `-c`
    /// mode, so the script sends the prompt's event itself.
    fn run_fish_snippet_with(fish: &Path, dir: &Path, first: &str, script: &str) -> String {
        write_stand_in(dir, first);
        std::fs::write(dir.join("snippet.fish"), FISH).unwrap();
        let output = std::process::Command::new(fish)
            .args(["--no-config", "-i", "-c"])
            .arg(format!(
                "cd $argv[1]; and set -gx PATH $PWD $PATH; and {script}"
            ))
            .arg(dir)
            .output()
            .unwrap();
        String::from_utf8_lossy(&output.stdout).trim().to_string()
    }

    #[test]
    fn the_fish_snippet_is_ascii_and_starts_the_tab() {
        assert!(FISH.is_ascii() && FISH_CODEX.is_ascii());
        assert!(FISH.contains("kaeru shell start --pid $fish_pid"));
        let with_codex = fish_snippet(&Config {
            codex_no_daemon: true,
            ..Config::default()
        });
        assert!(with_codex.starts_with(FISH));
        assert!(with_codex.contains("function codex"));
        assert!(!with_codex.contains("KAERU_ONE_OFF_COMMANDS"));
        assert!(!fish_snippet(&Config::default()).contains("function codex"));
    }

    #[test]
    fn the_fish_prompt_writes_the_folder_and_loads_once() {
        let Some(fish) = test_fish() else { return };
        let dir = tempfile::tempdir().unwrap();
        let calls = dir.path().join("calls");
        let shown = run_fish_snippet_with(
            &fish,
            dir.path(),
            &format!("echo \"$*\" >>'{}'", calls.display()),
            "source snippet.fish; source snippet.fish; emit fish_prompt; echo $KAERU_SHELL_PID",
        );
        assert!(shown.parse::<u32>().is_ok(), "{shown}");
        let calls = std::fs::read_to_string(calls).unwrap();
        assert_eq!(calls.lines().count(), 1, "loaded once: {calls}");
        let written = std::fs::read_to_string(dir.path().join("tab.cwd")).unwrap();
        assert_eq!(
            PathBuf::from(written.trim()).canonicalize().unwrap(),
            dir.path().canonicalize().unwrap()
        );
    }

    #[test]
    fn the_fish_function_runs_the_code_that_kaeru_resume_prints() {
        let Some(fish) = test_fish() else { return };
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir(dir.path().join("it's \\here")).unwrap();
        let answer = format!(
            "if [ \"$*\" = 'resume --shell fish' ]; then\n\
             echo 'Resuming the session' >&2\n\
             printf '%s\\n' {}\n\
             exit 0\nfi",
            bash_word(&fish_run_line("it's \\here", &["pwd".into()]))
        );
        let shown = run_fish_snippet_with(
            &fish,
            dir.path(),
            &answer,
            "source snippet.fish; kaeru resume; kaeru list",
        );
        let mut lines = shown.lines();
        assert!(
            lines
                .next()
                .is_some_and(|pwd| pwd.ends_with("/it's \\here")),
            "{shown}"
        );
        // Other commands run kaeru as they are.
        assert!(lines.next().is_some_and(|line| line.ends_with("tab.cwd")));
    }

    #[test]
    fn the_fish_prompt_runs_the_code_of_a_reopened_tab_once() {
        let Some(fish) = test_fish() else { return };
        let dir = tempfile::tempdir().unwrap();
        write_run_code(dir.path(), Shell::Fish);
        let script = format!(
            "set -gx {RUN_VAR} (string collect <code); source snippet.fish; \
             emit fish_prompt; emit fish_prompt; set -q {RUN_VAR}; or echo 'left: none'"
        );
        let shown = run_fish_snippet_with(&fish, dir.path(), "", &script);
        let lines: Vec<&str> = shown.lines().collect();
        assert_eq!(lines.len(), 2, "{shown}");
        assert!(lines[0].ends_with("/it's here"), "{shown}");
        assert_eq!(lines[1], "left: none");
    }

    // fish keeps the last command's status for the prompt around the
    // snippet's prompt function. Only a real prompt shows that, so this runs
    // fish with a terminal from util-linux's script, as on Linux.
    #[cfg(target_os = "linux")]
    #[test]
    fn the_fish_prompt_sees_the_last_command_s_status() {
        use std::io::Write;

        let Some(fish) = test_fish() else { return };
        let dir = tempfile::tempdir().unwrap();
        write_stand_in(dir.path(), "");
        std::fs::write(dir.path().join("snippet.fish"), FISH).unwrap();
        let prompts = dir.path().join("prompts");
        let config = format!(
            "set -gx PATH {dir} $PATH\nsource {dir}/snippet.fish\n\
             function fish_prompt\n echo $status >>{prompts}\n echo '> '\nend\n",
            dir = dir.path().display(),
            prompts = prompts.display()
        );
        let config_file = dir.path().join("config.fish");
        std::fs::write(&config_file, config).unwrap();
        let Ok(mut script) = std::process::Command::new("script")
            .args(["-q", "-c"])
            .arg(format!(
                "{} --no-config -i -C 'source {}'",
                fish.display(),
                config_file.display()
            ))
            .arg("/dev/null")
            .current_dir(dir.path())
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .spawn()
        else {
            return;
        };
        let mut input = script.stdin.take().unwrap();
        writeln!(input, "false").unwrap();
        writeln!(input, "true").unwrap();
        writeln!(input, "exit").unwrap();
        drop(input);
        script.wait().unwrap();
        let seen = std::fs::read_to_string(prompts).unwrap_or_default();
        let seen: Vec<&str> = seen.lines().collect();
        assert_eq!(seen, ["0", "1", "0"], "the prompt sees $status");
    }

    /// Waits up to ten seconds for a file to exist, and returns whether it
    /// does.
    #[cfg(target_os = "macos")]
    fn appears(file: &Path) -> bool {
        (0..100).any(|_| {
            std::thread::sleep(std::time::Duration::from_millis(100));
            file.exists()
        })
    }

    // A terminal that goes away hangs up the program in the tab, and zsh can
    // run its precmd functions once more after that program ended. macOS's
    // `script` gives zsh a terminal, as a tab has, and ending `script` hangs
    // it up. In a tab, zsh runs under login, which leads the terminal's
    // session and gets the hangup in zsh's place, so here sh does that.
    #[cfg(target_os = "macos")]
    #[test]
    fn a_prompt_after_the_terminal_hung_up_doesn_t_count() {
        use std::io::Write;

        let Some(zsh) = test_zsh() else { return };
        let dir = tempfile::tempdir().unwrap();
        write_zsh_snippet(dir.path(), "");
        let path = format!(
            "{}:{}",
            dir.path().display(),
            std::env::var("PATH").unwrap_or_default()
        );
        let mut script = std::process::Command::new("script")
            .args(["-q", "/dev/null", "/bin/sh", "-c", "\"$0\" -f -i; :"])
            .arg(&zsh)
            .current_dir(dir.path())
            .env("PATH", path)
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .spawn()
            .unwrap();
        let mut input = script.stdin.take().unwrap();
        writeln!(input, ". ./snippet.zsh").unwrap();
        let cwd_file = dir.path().join("tab.cwd");
        let started = dir.path().join("started");
        assert!(appears(&cwd_file), "the first prompt wrote the folder");
        writeln!(input, ": >started; sleep 60").unwrap();
        assert!(appears(&started), "the command runs");
        let written = std::fs::metadata(&cwd_file).unwrap().modified().unwrap();
        script.kill().unwrap();
        script.wait().unwrap();
        std::thread::sleep(std::time::Duration::from_secs(1));
        let after = std::fs::metadata(&cwd_file).unwrap().modified().unwrap();
        assert_eq!(after, written, "the prompt after the hangup counted");
    }

    #[test]
    fn the_zsh_prompt_writes_the_folder_and_loads_once() {
        let Some(zsh) = test_zsh() else { return };
        let dir = tempfile::tempdir().unwrap();
        let shown = run_zsh_snippet_with(
            &zsh,
            dir.path(),
            "",
            ". ./snippet.zsh; . ./snippet.zsh; __kaeru_precmd; print -r -- $precmd_functions",
        );
        assert_eq!(shown, "__kaeru_precmd", "one precmd function, once");
        let written = std::fs::read_to_string(dir.path().join("tab.cwd")).unwrap();
        assert_eq!(
            PathBuf::from(written.trim()).canonicalize().unwrap(),
            dir.path().canonicalize().unwrap()
        );
    }

    #[test]
    fn the_zsh_precmd_keeps_the_last_command_s_status() {
        let Some(zsh) = test_zsh() else { return };
        let dir = tempfile::tempdir().unwrap();
        let shown = |command: &str| {
            let script = format!(". ./snippet.zsh; {command}; __kaeru_precmd; echo \"sees $?\"");
            run_zsh_snippet_with(&zsh, dir.path(), "", &script)
        };
        assert_eq!(shown("false"), "sees 1");
        assert_eq!(shown("true"), "sees 0");
    }

    #[test]
    fn the_zsh_function_runs_the_code_that_kaeru_resume_prints() {
        let Some(zsh) = test_zsh() else { return };
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir(dir.path().join("it's here")).unwrap();
        let answer = format!(
            "if [ \"$*\" = 'resume --shell zsh' ]; then\n\
             echo 'Resuming the session' >&2\n\
             printf '%s\\n' {}\n\
             exit 0\nfi",
            bash_word(&bash_run_line("it's here", &["pwd".into()]))
        );
        let shown = run_zsh_snippet_with(
            &zsh,
            dir.path(),
            &answer,
            ". ./snippet.zsh; kaeru resume; kaeru list",
        );
        let mut lines = shown.lines();
        assert!(
            lines.next().is_some_and(|pwd| pwd.ends_with("/it's here")),
            "{shown}"
        );
        // Other commands run kaeru as they are.
        assert!(lines.next().is_some_and(|line| line.ends_with("tab.cwd")));
    }

    #[test]
    fn the_codex_function_comes_only_with_its_option() {
        let plain = powershell_snippet(&Config::default());
        assert!(!plain.contains("function global:codex"));
        let with_codex = powershell_snippet(&Config {
            codex_no_daemon: true,
            ..Config::default()
        });
        assert!(with_codex.starts_with(POWERSHELL));
        assert!(with_codex.contains("function global:codex"));
        assert!(with_codex.contains("'exec', "));
        assert!(!with_codex.contains("KAERU_ONE_OFF_COMMANDS"));
        assert!(with_codex.is_ascii());
    }

    /// Runs the snippet's Codex function in Windows PowerShell, with a
    /// stand-in for Codex that prints what it reads and its arguments, and
    /// returns what it printed. The PATH holds only the stand-in and Windows,
    /// so that a real Codex can't run. The stand-in is both a script and a
    /// batch file, because PowerShell may pick either one, as it does for the
    /// npm package's `codex.ps1` and `codex.cmd`.
    #[cfg(windows)]
    fn run_codex_function(calls: &str) -> String {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("codex.ps1"),
            "foreach ($line in $input) { \"in:$line\" }\r\n\
             foreach ($argument in $args) { \"arg:$argument\" }\r\n",
        )
        .unwrap();
        std::fs::write(
            dir.path().join("codex.cmd"),
            "@echo off\r\n\
             for /f \"delims=\" %%l in ('findstr \"^\"') do echo in:%%l\r\n\
             :next\r\nif \"%~1\"==\"\" goto :eof\r\necho arg:%~1\r\nshift\r\ngoto next\r\n",
        )
        .unwrap();
        let function = powershell_snippet(&Config {
            codex_no_daemon: true,
            ..Config::default()
        });
        let function = &function[POWERSHELL.len()..];
        let script = format!(
            "$env:PATH = '{};' + $env:SystemRoot + '\\System32'\n\
             $global:__kaeru_cwd_file = 'tracked'\n{function}\n{calls}",
            dir.path().display()
        );
        let powershell = std::path::Path::new(&std::env::var("SystemRoot").unwrap())
            .join(r"System32\WindowsPowerShell\v1.0\powershell.exe");
        let output = std::process::Command::new(powershell)
            .args([
                "-NoProfile",
                "-NonInteractive",
                "-ExecutionPolicy",
                "Bypass",
            ])
            .args(["-Command", &script])
            .output()
            .unwrap();
        assert!(output.status.success(), "{output:?}");
        String::from_utf8_lossy(&output.stdout).replace("\r\n", "\n")
    }

    /// Runs the PowerShell snippet in Windows PowerShell under a prompt theme
    /// that shows `$?`, with a stand-in for `kaeru` that tracks the tab, then
    /// runs `commands` and returns what the prompt shows. The snippet only
    /// starts in an interactive console, so the test lifts that check.
    #[cfg(windows)]
    fn prompt_after(commands: &str) -> String {
        run_powershell_snippet("", &format!("{commands}\nprompt"))
    }

    /// Runs the PowerShell snippet as [`prompt_after`] does, then `commands`,
    /// with `first` at the start of the stand-in for `kaeru`, so that it can
    /// answer some commands itself, and returns what it all printed.
    #[cfg(windows)]
    fn run_powershell_snippet(first: &str, commands: &str) -> String {
        let dir = tempfile::tempdir().unwrap();
        let cwd_file = dir.path().join("tab.cwd");
        std::fs::write(
            dir.path().join("kaeru.cmd"),
            format!("@echo off\r\n{first}\r\necho {}\r\n", cwd_file.display()),
        )
        .unwrap();
        let snippet = POWERSHELL.replace(
            "$Host.Name -eq 'ConsoleHost' -and -not [Console]::IsInputRedirected -and",
            "$true -and",
        );
        let script = format!(
            "$env:PATH = '{};' + $env:SystemRoot + '\\System32'\n\
             function global:prompt {{ \"theme sees $?\" }}\n{snippet}\n{commands}",
            dir.path().display()
        );
        let powershell = std::path::Path::new(&std::env::var("SystemRoot").unwrap())
            .join(r"System32\WindowsPowerShell\v1.0\powershell.exe");
        let output = std::process::Command::new(powershell)
            .args([
                "-NoProfile",
                "-NonInteractive",
                "-ExecutionPolicy",
                "Bypass",
            ])
            .args(["-Command", &script])
            .output()
            .unwrap();
        String::from_utf8_lossy(&output.stdout).trim().to_string()
    }

    #[cfg(windows)]
    #[test]
    fn the_powershell_function_runs_the_code_that_kaeru_resume_prints() {
        let dir = tempfile::tempdir().unwrap();
        let folder = dir.path().join("it's here");
        std::fs::create_dir(&folder).unwrap();
        // The stand-in echoes each line of the code, with ^ before &, which
        // cmd.exe would read as a second command.
        let code = powershell_run_lines(
            &folder.display().to_string(),
            &["Convert-Path".into(), ".".into()],
        );
        let echoes: Vec<String> = code
            .lines()
            .map(|line| format!("echo {}", line.replace('&', "^&")))
            .collect();
        let answer = format!(
            "if not \"%~1 %~2 %~3\"==\"resume --shell powershell\" goto other\r\n\
             echo Resuming the session 1>&2\r\n{}\r\nexit /b 0\r\n:other",
            echoes.join("\r\n")
        );
        let shown = run_powershell_snippet(&answer, "kaeru resume\nkaeru list");
        let mut lines = shown.lines();
        // Only the end of the path, because the temporary folder can be
        // written in its short form, with names such as DEMO~1.
        let end = format!(
            r"{}\it's here",
            dir.path().file_name().unwrap().to_string_lossy()
        );
        assert!(
            lines.next().is_some_and(|line| line.trim().ends_with(&end)),
            "{shown}"
        );
        // Other commands run kaeru as they are.
        assert!(
            lines
                .next()
                .is_some_and(|line| line.trim().ends_with("tab.cwd"))
        );
    }

    #[cfg(windows)]
    #[test]
    fn the_prompt_theme_still_sees_whether_the_last_command_failed() {
        assert_eq!(
            prompt_after("Get-Item 'C:\\no-such-folder' -ErrorAction SilentlyContinue"),
            "theme sees False"
        );
        assert_eq!(
            prompt_after("Get-Item 'C:\\' | Out-Null"),
            "theme sees True"
        );
    }

    #[cfg(windows)]
    #[test]
    fn the_codex_function_adds_no_daemon_only_for_the_interactive_screen() {
        let printed = run_codex_function(
            "'1'; codex\n\
             '2'; codex resume --last\n\
             '3'; codex exec 'fix the tests'\n\
             '4'; codex --no-daemon\n\
             '5'; codex --remote ws://localhost:1\n\
             '6'; 'fix the tests' | codex exec -",
        );
        assert_eq!(
            printed.trim_end(),
            "1\narg:--no-daemon\n\
             2\narg:--no-daemon\narg:resume\narg:--last\n\
             3\narg:exec\narg:fix the tests\n\
             4\narg:--no-daemon\n\
             5\narg:--remote\narg:ws://localhost:1\n\
             6\nin:fix the tests\narg:exec\narg:-"
        );
    }

    #[test]
    fn a_shell_started_to_run_something_is_recognized() {
        assert!(runs_a_command(
            "powershell.exe -NoExit -EncodedCommand AAAA"
        ));
        assert!(runs_a_command("powershell -ec AAAA"));
        assert!(runs_a_command("pwsh -c Get-Date"));
        assert!(runs_a_command("powershell -File script.ps1"));
        assert!(!runs_a_command("powershell.exe"));
        assert!(!runs_a_command("powershell.exe -NoLogo -NoExit"));
        assert!(!runs_a_command("pwsh -ExecutionPolicy Bypass"));
    }

    /// Returns a store in a temporary folder that holds one waiting tab: a
    /// shell whose terminal is gone.
    fn store_with_a_waiting_tab() -> (tempfile::TempDir, Store) {
        use crate::engine::note::{ProcessRef, TerminalRef};
        use crate::engine::rules::TerminalShape;

        let dir = tempfile::tempdir().unwrap();
        let store = Store::at(dir.path().to_path_buf()).unwrap();
        let note = Note::Shell(ShellNote {
            process: ProcessRef {
                pid: 20,
                started_ms: 2_000,
            },
            shell: "powershell".into(),
            cwd: r"C:\Users\demo\code\web-ui".into(),
            terminal: Some(TerminalRef {
                adapter: "windows-terminal".into(),
                process: ProcessRef {
                    pid: 10,
                    started_ms: 1_000,
                },
                shape: TerminalShape::Tabs,
                tab_id: None,
                profile: None,
                exe: None,
            }),
            session: "win-1".into(),
            offered: false,
        });
        store.save(&note).unwrap();
        (dir, store)
    }

    /// Returns what the store's notes mean when none of their processes run.
    fn review_with_nothing_running(store: &Store) -> Vec<Reviewed> {
        let table = FakeTable::new(&[]);
        store::review(
            store,
            &table,
            "win-1",
            Config::default().single_window_close,
        )
    }

    /// Returns the terminal of a tab of the terminal whose adapter is
    /// `adapter`, with the tab's id.
    fn tab_in(
        adapter: &str,
        tab_id: &str,
        terminal_started_ms: u64,
    ) -> crate::engine::note::TerminalRef {
        use crate::engine::note::{ProcessRef, TerminalRef};
        use crate::engine::rules::TerminalShape;
        TerminalRef {
            adapter: adapter.into(),
            process: ProcessRef {
                pid: 10,
                started_ms: terminal_started_ms,
            },
            shape: TerminalShape::Tabs,
            tab_id: Some(tab_id.into()),
            profile: None,
            exe: None,
        }
    }

    /// Saves the shell note of a tab of the terminal whose adapter is
    /// `adapter`, and its agent note when `agent` says so.
    fn save_tab(store: &Store, adapter: &str, pid: u32, tab_id: &str, agent: bool) {
        use crate::engine::note::{AgentNote, ProcessRef};
        let shell = ProcessRef {
            pid,
            started_ms: 2_000,
        };
        store
            .save(&Note::Shell(ShellNote {
                process: shell,
                shell: "powershell".into(),
                cwd: r"C:\Users\demo\code\api-server".into(),
                terminal: Some(tab_in(adapter, tab_id, 1_000)),
                session: "win-1".into(),
                offered: false,
            }))
            .unwrap();
        if agent {
            store
                .save(&Note::Agent(AgentNote {
                    process: ProcessRef {
                        pid: pid + 1,
                        started_ms: 3_000,
                    },
                    agent: "claude".into(),
                    conversation: "00000000-0000-4000-8000-000000000001".into(),
                    cwd: r"C:\Users\demo\code\api-server".into(),
                    shell: Some(shell),
                    shell_name: Some("powershell".into()),
                    shell_exe: None,
                    terminal: Some(tab_in(adapter, tab_id, 1_000)),
                    transcript: None,
                    session: "win-1".into(),
                    offered: false,
                }))
                .unwrap();
        }
    }

    /// Returns the shell note of a tab that its terminal restored.
    fn restored_tab(adapter: &str, tab_id: &str, terminal_started_ms: u64) -> Note {
        use crate::engine::note::ProcessRef;
        Note::Shell(ShellNote {
            process: ProcessRef {
                pid: 90,
                started_ms: terminal_started_ms + 500,
            },
            shell: "powershell".into(),
            cwd: r"C:\Users\demo\code\api-server".into(),
            terminal: Some(tab_in(adapter, tab_id, terminal_started_ms)),
            session: "win-1".into(),
            offered: false,
        })
    }

    /// Returns the names of the files of the notes in a store.
    fn note_files(store: &Store) -> Vec<String> {
        store
            .notes()
            .iter()
            .map(|stored| {
                stored
                    .path
                    .file_name()
                    .unwrap()
                    .to_string_lossy()
                    .into_owned()
            })
            .collect()
    }

    /// What [`claim`] finds for a restored tab whose agent session waits.
    fn waiting_session(orphan: bool) -> Claimed {
        Claimed {
            restored: true,
            resume: Some(ToResume {
                agent: "Claude Code".into(),
                orphan,
            }),
        }
    }

    #[test]
    fn a_tab_that_warp_restored_takes_over_its_notes() {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::at(dir.path().to_path_buf()).unwrap();
        save_tab(&store, "warp", 20, "tab-a", true);
        save_tab(&store, "warp", 30, "tab-b", false);
        let reviewed = review_with_nothing_running(&store);
        // Tab a comes back, as Warp restores its tabs: its agent can resume.
        let now = 50_000;
        assert_eq!(
            claim(
                &store,
                &reviewed,
                &restored_tab("warp", "tab-a", 40_000),
                now,
                &FakeTable::new(&[])
            ),
            waiting_session(false)
        );
        let left = note_files(&store);
        assert!(left.iter().any(|name| name.starts_with("agent-21-")));
        assert!(!left.iter().any(|name| name.starts_with("shell-20-")));
        // Tab b hasn't come back yet, and Warp started just now: it waits.
        assert!(left.iter().any(|name| name.starts_with("shell-30-")));
        // Long after Warp started, it never will.
        let reviewed = review_with_nothing_running(&store);
        assert_eq!(
            claim(
                &store,
                &reviewed,
                &restored_tab("warp", "tab-c", 40_000),
                40_000 + RESTORE_WAIT_MS + 1,
                &FakeTable::new(&[])
            ),
            Claimed::default()
        );
        assert!(store.notes().is_empty());
    }

    #[test]
    fn a_session_that_outlived_its_crashed_warp_can_be_resumed() {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::at(dir.path().to_path_buf()).unwrap();
        save_tab(&store, "warp", 20, "tab-a", true);
        // Warp is gone, but its tab's shell and agent still run.
        let table = FakeTable::new(&[
            (21, Some(20), "claude.exe", Some(3_000)),
            (20, None, "powershell.exe", Some(2_000)),
        ]);
        let reviewed = store::review(
            &store,
            &table,
            "win-1",
            Config::default().single_window_close,
        );
        assert_eq!(
            claim(
                &store,
                &reviewed,
                &restored_tab("warp", "tab-a", 40_000),
                50_000,
                &table
            ),
            waiting_session(true)
        );
        // The restored tab is the tab now, so the old shell note is done.
        assert_eq!(store.notes().len(), 1);
    }

    #[test]
    fn warp_s_waiting_tabs_are_left_out_of_the_picker() {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::at(dir.path().to_path_buf()).unwrap();
        save_tab(&store, "warp", 20, "tab-a", true);
        let reviewed = review_with_nothing_running(&store);
        assert!(!offer(&store, &reviewed, &Config::default(), false).unwrap());
        assert_eq!(store.notes().len(), 2, "the notes wait for Warp's tab");
    }

    #[test]
    fn a_tab_that_iterm2_restored_takes_over_its_notes_and_the_rest_wait() {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::at(dir.path().to_path_buf()).unwrap();
        save_tab(&store, "iterm2", 20, "tab-a", true);
        save_tab(&store, "iterm2", 30, "tab-b", false);
        let reviewed = review_with_nothing_running(&store);
        assert_eq!(
            claim(
                &store,
                &reviewed,
                &restored_tab("iterm2", "tab-a", 40_000),
                40_000 + RESTORE_WAIT_MS + 1,
                &FakeTable::new(&[])
            ),
            waiting_session(false)
        );
        // iTerm2 doesn't always bring its tabs back, so tab b keeps waiting
        // for the picker, even long after iTerm2 started.
        let left = note_files(&store);
        assert!(!left.iter().any(|name| name.starts_with("shell-20-")));
        assert!(left.iter().any(|name| name.starts_with("agent-21-")));
        assert!(left.iter().any(|name| name.starts_with("shell-30-")));
        // A new tab that iTerm2 didn't restore claims nothing.
        let reviewed = review_with_nothing_running(&store);
        assert_eq!(
            claim(
                &store,
                &reviewed,
                &restored_tab("iterm2", "tab-new", 40_000),
                50_000,
                &FakeTable::new(&[])
            ),
            Claimed::default()
        );
        assert_eq!(store.notes().len(), 2);
    }

    #[test]
    fn iterm2_s_tabs_are_offered_unless_iterm2_brought_them_back() {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::at(dir.path().to_path_buf()).unwrap();
        save_tab(&store, "iterm2", 20, "tab-a", true);
        save_tab(&store, "iterm2", 30, "tab-b", false);
        // iTerm2 brought tab a back: its new shell runs, with the tab's id.
        let back = restored_tab("iterm2", "tab-a", 40_000);
        store.save(&back).unwrap();
        claim(
            &store,
            &review_with_nothing_running(&store),
            &back,
            50_000,
            &FakeTable::new(&[]),
        );
        let table = FakeTable::new(&[
            (90, Some(10), "zsh", Some(40_500)),
            (10, None, "iTermServer-3.6.10", Some(40_000)),
        ]);
        let reviewed = store::review(
            &store,
            &table,
            "win-1",
            Config::default().single_window_close,
        );
        let left: Vec<(bool, bool)> = reviewed
            .iter()
            .filter(|one| one.state == TabState::Waiting)
            .map(|one| {
                let agent = matches!(one.stored.note, Note::Agent(_));
                (agent, left_to_its_terminal(&one.stored.note, &reviewed))
            })
            .collect();
        // Tab a's agent waits for kaeru resume in its tab, and tab b, which
        // iTerm2 didn't bring back, is offered.
        assert!(left.contains(&(true, true)), "{left:?}");
        assert!(left.contains(&(false, false)), "{left:?}");
        assert_eq!(left.len(), 2);
        assert!(offer(&store, &reviewed, &Config::default(), false).unwrap());
    }

    #[test]
    fn a_restored_tab_doesn_t_ask_about_its_terminal_s_other_tabs() {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::at(dir.path().to_path_buf()).unwrap();
        save_tab(&store, "iterm2", 30, "tab-b", false);
        save_tab(&store, "windows-terminal", 50, "tab-c", false);
        let reviewed = review_with_nothing_running(&store);
        // The notes started at the same time, so the order they are read in
        // depends on the file system.
        let adapters = |notes: &[Reviewed]| -> Vec<String> {
            let mut adapters: Vec<String> = notes
                .iter()
                .filter_map(|reviewed| Some(reviewed.stored.note.terminal()?.adapter.clone()))
                .collect();
            adapters.sort();
            adapters
        };
        assert_eq!(
            adapters(&askable(reviewed.clone(), None)),
            ["iterm2", "windows-terminal"]
        );
        // iTerm2 may be bringing tab b back at this moment.
        assert_eq!(
            adapters(&askable(reviewed, Some("iterm2"))),
            ["windows-terminal"]
        );
    }

    #[test]
    fn the_picker_waits_for_a_terminal_that_is_bringing_back_its_tabs() {
        let restoring = tab_in("iterm2", "tab-a", 40_000);
        assert_eq!(
            restore_settle(&restoring, 41_000),
            Duration::from_millis(4_000)
        );
        assert_eq!(restore_settle(&restoring, 60_000), Duration::ZERO);
        let never = tab_in("windows-terminal", "tab-a", 40_000);
        assert_eq!(restore_settle(&never, 41_000), Duration::ZERO);
    }

    #[test]
    fn only_the_first_new_tab_asks() {
        let (_dir, store) = store_with_a_waiting_tab();
        let config = Config::default();
        let reviewed = review_with_nothing_running(&store);
        assert!(offer(&store, &reviewed, &config, false).unwrap());
        let reviewed = review_with_nothing_running(&store);
        assert!(!offer(&store, &reviewed, &config, false).unwrap());
        assert_eq!(store.notes().len(), 1, "the tab still waits");
    }

    #[test]
    fn a_new_tab_waits_quietly_while_another_tab_holds_the_list() {
        let (_dir, store) = store_with_a_waiting_tab();
        // Another tab's picker holds the lock while it asks or reopens.
        let held = store.try_lock().unwrap().unwrap();
        let reviewed = review_with_nothing_running(&store);
        assert!(!offer(&store, &reviewed, &Config::default(), false).unwrap());
        assert!(!store.notes()[0].note.offered(), "it asks later, not now");
        drop(held);
        // A test that starts a program at this moment gives it a copy of the
        // lock file until the program runs, so the lock can take a moment
        // to be free.
        let asked = (0..100).any(|_| {
            let reviewed = review_with_nothing_running(&store);
            let asked = offer(&store, &reviewed, &Config::default(), false).unwrap();
            if !asked {
                std::thread::sleep(std::time::Duration::from_millis(10));
            }
            asked
        });
        assert!(asked);
    }

    #[test]
    fn a_reopened_agent_tab_never_asks() {
        let (_dir, store) = store_with_a_waiting_tab();
        let reviewed = review_with_nothing_running(&store);
        assert!(!offer(&store, &reviewed, &Config::default(), true).unwrap());
        assert!(!store.notes()[0].note.offered());
    }

    #[test]
    fn tabs_that_the_options_leave_out_are_forgotten() {
        let (_dir, store) = store_with_a_waiting_tab();
        let config = Config {
            offer_shells: false,
            ..Config::default()
        };
        let reviewed = review_with_nothing_running(&store);
        assert!(!offer(&store, &reviewed, &config, false).unwrap());
        assert!(store.notes().is_empty());
    }
}