omni-dev 0.43.0

AI-powered git commit rewriter, PR generator, and MCP server for Jira, Confluence, Datadog, Gmail, and Drive.
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
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
//! The worktrees UI's event loop and mutable state (issue #1585 Phases 2–3):
//! the tree pane's cursor/marks and action popups, one embedded terminal
//! tab, and the single `tokio::select!` that merges crossterm input, PTY
//! events, and hub redraw signals.
//!
//! Extracted from `mod.rs` in Phase 3 — the point where PTY state gave the
//! type enough weight to justify its own file. Phase 4 adds the mouse
//! contract (`handle_mouse`, applying what `mouse.rs` decides); tabs/splits
//! extend `App` further.

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

use alacritty_terminal::event::Event as TermEvent;
use alacritty_terminal::grid::Scroll;
use alacritty_terminal::selection::SelectionType;
use alacritty_terminal::term::TermMode;
use anyhow::Result;
use crossterm::event::{
    Event, EventStream, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseButton, MouseEvent,
    MouseEventKind,
};
use futures::StreamExt;
use ratatui::backend::CrosstermBackend;
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::widgets::{Block, Borders};
use ratatui::{Frame, Terminal};
use tokio::sync::mpsc;

use super::actions::{self, ActionFlow, ActionKind, CheckReport, Dispatcher, Target};
use super::hub::{HubCommand, ViewModelHandle};
use super::keys::{self, ChromeKey, KeyRoute};
use super::mouse::{self, DragOrigin, Hit, RegionMap, TreeClick, WheelRoute};
use super::panes;
use super::terminal::{GridSize, TabEffect, TabId, TabKind, TerminalTab};
use super::tree::TreeState;
use super::view_model::WorktreesViewModel;
use super::{clipboard, popup, render, row_colors};
use crate::sessions::relocate::{self, RelocationMode};

/// Which pane receives keys.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
enum Focus {
    #[default]
    Tree,
    Terminal,
}

/// Minimum interval between redraws while PTY output is streaming: a burst
/// of `Wakeup` events produces one frame, not one frame per event.
const FRAME_INTERVAL: Duration = Duration::from_millis(16);

/// The render layer's mutable state: cursor/marks, the current action-flow
/// popup, the Move/Copy-Claude-Session-Here picker wizard when active, and
/// the terminal tab. Everything here is local UI state, not daemon truth —
/// see `tree::TreeState`'s own doc comment.
struct App {
    tree: TreeState,
    flow: ActionFlow,
    menu: Option<popup::ActionMenu>,
    relocate: Option<RelocateStep>,
    focus: Focus,
    /// The terminal side: a vertical stack of tab groups (Phase 4b).
    panes: panes::PaneLayout,
    /// `q` with a live child asks first; the answer lands here.
    quit_confirm: bool,
    /// A one-line message for the status bar, cleared on the next key.
    notice: Option<String>,
    pty_tx: mpsc::UnboundedSender<(TabId, TermEvent)>,
    commands: mpsc::UnboundedSender<HubCommand>,
    /// The hit-testable regions of the last drawn frame.
    regions: RegionMap,
    /// The terminal side's rect as of the last frame — what a splitter drag
    /// recomputes weights against.
    terminal_area: Option<Rect>,
    /// The drag in progress, if any, and the region it is clamped to.
    drag: DragOrigin,
    clicks: mouse::ClickTracker,
}

/// The Move/Copy-Claude-Session-Here wizard's steps (issue #1585 Phase 2
/// §5): pick which session (skipped when the source row has exactly one),
/// then pick a destination worktree, then confirm. Kept out of the generic
/// [`ActionFlow`] since a relocation's parameters (a resolved session id
/// plus a source/destination pair) don't fit the uniform `targets: &[Target]`
/// fan-out shape every other action uses.
enum RelocateStep {
    PickSession {
        mode: RelocationMode,
        source_worktree: PathBuf,
        source_dir: PathBuf,
        sessions: Vec<actions::relocate_types::SessionInfo>,
        selected: usize,
    },
    PickDestination {
        mode: RelocationMode,
        source_dir: PathBuf,
        session: actions::relocate_types::SessionInfo,
        candidates: Vec<PathBuf>,
        selected: usize,
    },
    Confirm {
        mode: RelocationMode,
        source_dir: PathBuf,
        session: actions::relocate_types::SessionInfo,
        dest_worktree: PathBuf,
        prompt: actions::ConfirmPrompt,
    },
}

/// The event loop: one `select!` over crossterm input, the shared PTY event
/// channel, and the hub's view updates, redrawing at most every
/// [`FRAME_INTERVAL`] while anything is dirty. Quits on `q` from the tree
/// (after a confirm when a child is live).
pub async fn run(
    terminal: &mut Terminal<CrosstermBackend<std::io::Stdout>>,
    mut handle: ViewModelHandle,
    dispatcher: Dispatcher,
    commands: mpsc::UnboundedSender<HubCommand>,
) -> Result<()> {
    let mut events = EventStream::new();
    let (pty_tx, mut pty_rx) = mpsc::unbounded_channel();
    let mut app = App {
        tree: TreeState::default(),
        flow: ActionFlow::Idle,
        menu: None,
        relocate: None,
        focus: Focus::Tree,
        panes: panes::PaneLayout::default(),
        quit_confirm: false,
        notice: None,
        pty_tx,
        commands,
        regions: RegionMap::default(),
        terminal_area: None,
        drag: DragOrigin::None,
        clicks: mouse::ClickTracker::default(),
    };
    let mut last_drawn_generation: Option<u64> = None;
    let mut dirty = true;
    let mut last_draw = tokio::time::Instant::now() - FRAME_INTERVAL;

    loop {
        let view = handle.view.borrow_and_update().clone();
        let generation_moved = last_drawn_generation != Some(view.generation);
        if (dirty || generation_moved) && last_draw.elapsed() >= FRAME_INTERVAL {
            terminal.draw(|frame| draw(frame, &view, &mut app))?;
            last_drawn_generation = Some(view.generation);
            dirty = false;
            last_draw = tokio::time::Instant::now();
        }
        // Coalesce: while dirty, wait out the rest of the frame interval;
        // otherwise a slow fallback tick keeps the status bar's
        // reconnecting/polling state fresh between real events.
        let wait = if dirty || generation_moved {
            FRAME_INTERVAL.saturating_sub(last_draw.elapsed())
        } else {
            Duration::from_millis(500)
        };

        tokio::select! {
            biased;
            ev = events.next() => {
                match ev {
                    Some(Ok(Event::Key(key))) if key.kind == KeyEventKind::Press => {
                        app.notice = None;
                        if handle_key(&mut app, &view, &dispatcher, key).await {
                            break;
                        }
                        dirty = true;
                    }
                    Some(Ok(Event::Mouse(mouse))) => {
                        if handle_mouse(&mut app, &view, mouse) {
                            dirty = true;
                        }
                    }
                    Some(Ok(Event::Paste(text))) => {
                        if app.focus == Focus::Terminal {
                            if let Some(tab) = app.panes.active_tab().filter(|t| t.is_alive()) {
                                tab.write_input(keys::paste_bytes(&text, tab.mode()));
                            }
                        }
                    }
                    Some(Ok(Event::FocusGained)) => app.forward_focus(true),
                    Some(Ok(Event::FocusLost)) => app.forward_focus(false),
                    Some(Ok(Event::Resize(..))) => dirty = true,
                    Some(Ok(_)) => {}
                    Some(Err(_)) | None => break,
                }
            }
            pty = pty_rx.recv() => {
                match pty {
                    Some((tab_id, event)) => {
                        if app.handle_pty_event(tab_id, event) {
                            dirty = true;
                        }
                    }
                    None => break,
                }
            }
            changed = handle.view.changed() => {
                if changed.is_err() {
                    break; // the hub actor is gone
                }
            }
            () = tokio::time::sleep(wait) => {}
        }
    }

    for group in &mut app.panes.groups {
        for tab in &mut group.tabs {
            tab.shutdown();
        }
    }
    Ok(())
}

impl App {
    /// Absorbs one emulator event; returns whether a redraw is needed.
    fn handle_pty_event(&mut self, tab_id: TabId, event: TermEvent) -> bool {
        let Some(effect) = self.panes.handle_event(tab_id, event) else {
            return false; // an event from a tab that has already been closed
        };
        match effect {
            TabEffect::None => false,
            TabEffect::Redraw => true,
            TabEffect::CopyToClipboard(text) => {
                if clipboard::copy_text(&text).is_err() {
                    self.notice = Some("clipboard unavailable".to_string());
                }
                false
            }
            TabEffect::Exited => {
                self.notice = Some("terminal exited — alt-w to close the tab".to_string());
                true
            }
        }
    }

    /// Forwards host focus in/out to a child that asked for it
    /// (`TermMode::FOCUS_IN_OUT`), the way a real terminal would. Only the
    /// focused tab hears about it — a background tab never had focus to
    /// gain or lose.
    fn forward_focus(&self, gained: bool) {
        if let Some(tab) = self.panes.active_tab().filter(|t| t.is_alive()) {
            if tab.mode().contains(TermMode::FOCUS_IN_OUT) {
                tab.write_input(if gained {
                    b"\x1b[I".to_vec()
                } else {
                    b"\x1b[O".to_vec()
                });
            }
        }
    }

    /// Opens a tab of `kind` in `worktree`, focusing an existing live one
    /// for the same worktree and kind rather than opening a duplicate. With
    /// `split`, the tab lands in a new group below the focused one.
    fn open_tab(&mut self, kind: TabKind, worktree: PathBuf, size: GridSize, split: bool) {
        // Reusing an existing tab is the *open* gesture's convenience. A
        // split is an explicit "give me another pane", so it always makes
        // one — including on a worktree that already has a tab.
        if !split {
            if let Some(addr) = self.panes.find_in_worktree(&worktree, kind) {
                self.panes.focus(addr);
                self.focus = Focus::Terminal;
                return;
            }
        }
        let tx = self.pty_tx.clone();
        let target = worktree.clone();
        let spawn = move |id| TerminalTab::spawn(id, kind, target, size, tx);
        let opened = if split {
            self.panes.split(spawn)
        } else {
            self.panes.open_tab(spawn)
        };
        match opened {
            Ok(_) => {
                self.focus = Focus::Terminal;
                let _ = self.commands.send(HubCommand::SetOpenTab(worktree));
            }
            Err(e) => self.notice = Some(format!("{e:#}")),
        }
    }

    /// Closes the focused tab. The `here` cue is only cleared once the
    /// *last* tab on that worktree has gone, since several tabs may share
    /// one worktree.
    fn close_tab(&mut self) {
        let Some(worktree) = self.panes.close_active() else {
            return;
        };
        if !self.panes.open_worktrees().contains(&worktree) {
            let _ = self.commands.send(HubCommand::ClearOpenTab(worktree));
        }
        if self.panes.is_empty() {
            self.focus = Focus::Tree;
        }
    }

    fn cursor_worktree(&self, view: &WorktreesViewModel) -> Option<PathBuf> {
        match self.tree.targets_for_cursor_only(view).into_iter().next()? {
            Target::Worktree { path, .. } => Some(path),
            Target::Repo { root, .. } => Some(root),
        }
    }
}

// --- Layout and drawing ---------------------------------------------------

struct Areas {
    tree: Rect,
    terminal: Option<Rect>,
    status: Rect,
}

/// The tree on the left, the terminal pane on the right when a tab exists
/// (full width otherwise), and a one-line status bar.
fn layout(area: Rect, has_terminal: bool) -> Areas {
    let rows = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Min(1), Constraint::Length(1)])
        .split(area);
    if !has_terminal {
        return Areas {
            tree: rows[0],
            terminal: None,
            status: rows[1],
        };
    }
    let cols = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([Constraint::Percentage(38), Constraint::Min(20)])
        .split(rows[0]);
    Areas {
        tree: cols[0],
        terminal: Some(cols[1]),
        status: rows[1],
    }
}

fn draw(frame: &mut Frame<'_>, view: &WorktreesViewModel, app: &mut App) {
    let areas = layout(frame.area(), !app.panes.is_empty());
    render::draw_tree_pane(
        frame,
        areas.tree,
        view,
        &mut app.tree,
        app.focus == Focus::Tree,
    );
    // `arrange` both lays the stack out and resizes each visible group's
    // active tab to the grid it is about to be drawn into, so the emulator
    // is never read at a size it was not rendered at.
    app.terminal_area = areas.terminal;
    let group_rects = match areas.terminal {
        Some(area) => app.panes.arrange(area),
        None => Vec::new(),
    };
    app.panes
        .draw(frame, &group_rects, app.focus == Focus::Terminal);

    // The region map mirrors exactly what was just drawn, offsets included.
    let splitters = group_rects
        .iter()
        .take(group_rects.len().saturating_sub(1))
        .map(|r| super::layout::boundary_row(r.body))
        .collect();
    app.regions = RegionMap {
        tree: Block::default().borders(Borders::ALL).inner(areas.tree),
        tree_offset: app.tree.offset,
        groups: group_rects
            .iter()
            .map(|r| mouse::GroupRegion {
                strip: r.strip,
                grid: r.grid,
                tab_spans: r.tab_spans.clone(),
            })
            .collect(),
        splitters,
        splitter_cols: areas
            .terminal
            .map_or((0, 0), |a| (a.x, a.x.saturating_add(a.width))),
    };
    render::draw_status_bar(frame, areas.status, view, &app.tree, &status_hint(app));
    draw_popups(frame, app);
}

fn status_hint(app: &App) -> String {
    if let Some(notice) = &app.notice {
        return notice.clone();
    }
    match (&app.flow, app.focus) {
        (ActionFlow::Done { outcome }, _) => match outcome {
            actions::ActionOutcome::Done { summary } => summary.clone(),
            actions::ActionOutcome::BatchDone { results } => {
                let failed = results.iter().filter(|(_, r)| r.is_err()).count();
                if failed == 0 {
                    format!("done: {} target(s)", results.len())
                } else {
                    format!("{failed} of {} target(s) failed", results.len())
                }
            }
            actions::ActionOutcome::Failed { error } => format!("failed: {error}"),
        },
        (ActionFlow::Failed { error }, _) => format!("failed: {error}"),
        (_, Focus::Terminal) => {
            "alt-e tree  alt-t tab  alt-s split  alt-[/] cycle  alt-w close  alt-c copy".to_string()
        }
        (_, Focus::Tree) => {
            "↑↓ move  space mark  enter/alt-t shell tab  alt-⇧t claude tab  a actions  c/C colour  q quit".to_string()
        }
    }
}

fn draw_popups(frame: &mut Frame<'_>, app: &App) {
    let area = frame.area();
    if app.quit_confirm {
        let modal = popup::ConfirmModal {
            prompt: actions::ConfirmPrompt {
                title: "Quit?".to_string(),
                body_lines: vec![
                    "A terminal tab is still running; quitting sends it SIGHUP.".to_string()
                ],
                ..Default::default()
            },
        };
        popup::draw_confirm_modal(frame, area, &modal);
        return;
    }
    if let Some(menu) = &app.menu {
        popup::draw_action_menu(frame, area, menu);
        return;
    }
    match &app.relocate {
        Some(RelocateStep::PickSession {
            sessions, selected, ..
        }) => {
            let labels: Vec<String> = sessions
                .iter()
                .map(|s| format!("{}  ({})", s.id, relative_mtime(s.modified)))
                .collect();
            let refs: Vec<&str> = labels.iter().map(String::as_str).collect();
            popup::draw_list_popup(frame, area, "Move which Claude session?", &refs, *selected);
            return;
        }
        Some(RelocateStep::PickDestination {
            candidates,
            selected,
            ..
        }) => {
            let labels: Vec<String> = candidates.iter().map(|p| p.display().to_string()).collect();
            let refs: Vec<&str> = labels.iter().map(String::as_str).collect();
            popup::draw_list_popup(frame, area, "Move to which worktree?", &refs, *selected);
            return;
        }
        Some(RelocateStep::Confirm { prompt, .. }) => {
            popup::draw_confirm_modal(
                frame,
                area,
                &popup::ConfirmModal {
                    prompt: prompt.clone(),
                },
            );
            return;
        }
        None => {}
    }
    if let ActionFlow::AwaitingConfirm { prompt, .. } = &app.flow {
        popup::draw_confirm_modal(
            frame,
            area,
            &popup::ConfirmModal {
                prompt: prompt.clone(),
            },
        );
    }
}

fn relative_mtime(modified: std::time::SystemTime) -> String {
    match std::time::SystemTime::now().duration_since(modified) {
        Ok(elapsed) => format!("{}s ago", elapsed.as_secs()),
        Err(_) => "just now".to_string(),
    }
}

// --- Mouse handling ---------------------------------------------------------

/// Handles one mouse event under the contract in `mouse.rs`. Returns
/// whether a redraw is needed. Popups are chrome, so the mouse is inert
/// while one is open.
fn handle_mouse(app: &mut App, view: &WorktreesViewModel, mouse: MouseEvent) -> bool {
    if app.quit_confirm
        || app.menu.is_some()
        || app.relocate.is_some()
        || matches!(app.flow, ActionFlow::AwaitingConfirm { .. })
    {
        return false;
    }
    let (col, row, mods) = (mouse.column, mouse.row, mouse.modifiers);
    match mouse.kind {
        MouseEventKind::Down(button) => {
            app.notice = None;
            match app.regions.hit(col, row) {
                Hit::Tree { row: tree_row } => {
                    tree_mouse_down(app, view, tree_row, button, mods, (col, row))
                }
                Hit::Terminal {
                    group,
                    col: gc,
                    line,
                } => terminal_mouse_down(app, group, button, mods, (gc, line), (col, row)),
                Hit::TabStrip { group, tab } => strip_mouse_down(app, group, tab, button),
                Hit::Splitter { index } => {
                    app.drag = DragOrigin::Splitter { index };
                    false
                }
                Hit::Chrome => false,
            }
        }
        MouseEventKind::Drag(button) => match app.drag {
            DragOrigin::Tree { anchor } => {
                let rows = TreeState::visible_rows(view).len();
                app.tree.set_cursor(app.regions.tree_row_clamped(row), rows);
                app.tree.mark_range(view, anchor, app.tree.cursor);
                true
            }
            DragOrigin::Terminal { group } => {
                let Some((gc, line)) = app.regions.clamp_to_grid(group, col, row) else {
                    return false;
                };
                if let Some(tab) = app.panes.group_tab(group) {
                    tab.selection_update(gc, line);
                }
                true
            }
            DragOrigin::Splitter { index } => drag_splitter(app, index, row),
            DragOrigin::Child { group } => {
                forward_to_child(app, group, MouseEventKind::Drag(button), mods, (col, row));
                false
            }
            DragOrigin::None => false,
        },
        MouseEventKind::Up(button) => {
            if let DragOrigin::Child { group } = std::mem::take(&mut app.drag) {
                forward_to_child(app, group, MouseEventKind::Up(button), mods, (col, row));
            }
            false
        }
        MouseEventKind::Moved => {
            // Only a child that asked for all-motion reporting cares.
            if let Hit::Terminal { group, .. } = app.regions.hit(col, row) {
                forward_to_child(app, group, MouseEventKind::Moved, mods, (col, row));
            }
            false
        }
        MouseEventKind::ScrollUp | MouseEventKind::ScrollDown => {
            let up = mouse.kind == MouseEventKind::ScrollUp;
            match app.regions.hit(col, row) {
                Hit::Tree { .. } => {
                    let rows = TreeState::visible_rows(view).len();
                    app.tree.move_cursor(if up { -1 } else { 1 }, rows);
                    true
                }
                // The wheel over a tab strip cycles that group's tabs.
                Hit::TabStrip { group, .. } => {
                    app.panes.focused = group;
                    app.panes.cycle_tab(if up { -1 } else { 1 });
                    true
                }
                Hit::Terminal {
                    group,
                    col: gc,
                    line,
                } => {
                    let Some(tab) = app.panes.group_tab(group) else {
                        return false;
                    };
                    match mouse::route_wheel(up, mods, gc, line, tab.mode()) {
                        WheelRoute::Forward(bytes) | WheelRoute::ArrowKeys(bytes) => {
                            if tab.is_alive() {
                                tab.write_input(bytes);
                            }
                            false
                        }
                        WheelRoute::ScrollDisplay(lines) => {
                            tab.scroll(Scroll::Delta(lines));
                            true
                        }
                    }
                }
                Hit::Splitter { .. } | Hit::Chrome => false,
            }
        }
        MouseEventKind::ScrollLeft | MouseEventKind::ScrollRight => {
            if let Hit::Terminal { group, .. } = app.regions.hit(col, row) {
                forward_to_child(app, group, mouse.kind, mods, (col, row));
            }
            false
        }
    }
}

/// A button-down on a tab strip: left activates the tab (or focuses the
/// group when the click is past the last one), middle closes it — the
/// conventional tab-strip gestures.
fn strip_mouse_down(app: &mut App, group: usize, tab: Option<usize>, button: MouseButton) -> bool {
    app.focus = Focus::Terminal;
    app.drag = DragOrigin::None;
    app.panes.focused = group.min(app.panes.group_count().saturating_sub(1));
    let Some(tab) = tab else {
        return true;
    };
    match button {
        MouseButton::Middle => {
            let addr = panes::TabAddr { group, tab };
            if let Some(worktree) = app.panes.close_tab(addr) {
                if !app.panes.open_worktrees().contains(&worktree) {
                    let _ = app.commands.send(HubCommand::ClearOpenTab(worktree));
                }
                if app.panes.is_empty() {
                    app.focus = Focus::Tree;
                }
            }
        }
        MouseButton::Left | MouseButton::Right => {
            app.panes.focus(panes::TabAddr { group, tab });
        }
    }
    true
}

/// Drags splitter `index` to screen row `row`, resizing only the two groups
/// either side of it.
fn drag_splitter(app: &mut App, index: usize, row: u16) -> bool {
    let Some(area) = app.terminal_area else {
        return false;
    };
    let next = super::layout::drag_splitter(area, &app.panes.weights, index, row);
    if next == app.panes.weights {
        return false;
    }
    app.panes.weights = next;
    true
}

/// A button-down on tree row `tree_row` (which may be past the last row).
fn tree_mouse_down(
    app: &mut App,
    view: &WorktreesViewModel,
    tree_row: usize,
    button: MouseButton,
    mods: KeyModifiers,
    (col, row): (u16, u16),
) -> bool {
    app.focus = Focus::Tree;
    app.drag = DragOrigin::None;
    let rows = TreeState::visible_rows(view).len();
    if tree_row >= rows {
        return true; // below the last row: just the focus change
    }
    let count = app.clicks.click(col, row, Instant::now());
    match mouse::classify_tree_click(button, mods, count) {
        TreeClick::Focus => app.tree.set_cursor(tree_row, rows),
        TreeClick::ToggleMark => {
            app.tree.set_cursor(tree_row, rows);
            if let Some(path) = cursor_row_path(&app.tree, view) {
                app.tree.toggle_mark(path);
            }
        }
        TreeClick::ExtendRange => {
            let from = app.tree.cursor;
            app.tree.set_cursor(tree_row, rows);
            app.tree.mark_range(view, from, tree_row);
        }
        TreeClick::Open => {
            app.tree.set_cursor(tree_row, rows);
            open_tab_for_cursor(app, view, TabKind::Shell, false);
        }
    }
    if button == MouseButton::Left {
        app.drag = DragOrigin::Tree { anchor: tree_row };
    }
    true
}

/// A button-down on group `group`'s grid at (`gc`, `line`): the child's if
/// it asked for the mouse (contract §4), else the start of a selection —
/// simple, word or line by click count. Middle/right buttons neither paste
/// nor select: there is no clipboard→child path here by design.
fn terminal_mouse_down(
    app: &mut App,
    group: usize,
    button: MouseButton,
    mods: KeyModifiers,
    (gc, line): (u16, u16),
    (col, row): (u16, u16),
) -> bool {
    app.focus = Focus::Terminal;
    app.drag = DragOrigin::None;
    // Clicking a group focuses it, so the next key goes where the eye is.
    app.panes.focused = group.min(app.panes.group_count().saturating_sub(1));
    let click = app.clicks.click(col, row, Instant::now());
    let Some(tab) = app.panes.group_tab(group) else {
        return true;
    };
    let mode = tab.mode();
    if tab.is_alive() && mouse::forwards_to_child(mode, mods) {
        if let Some(bytes) = mouse::encode_mouse(MouseEventKind::Down(button), mods, gc, line, mode)
        {
            tab.write_input(bytes);
        }
        app.drag = DragOrigin::Child { group };
        return true;
    }
    if button == MouseButton::Left {
        let ty = match click {
            1 => SelectionType::Simple,
            2 => SelectionType::Semantic,
            _ => SelectionType::Lines,
        };
        tab.selection_start(gc, line, ty);
        app.drag = DragOrigin::Terminal { group };
    }
    true
}

/// Encodes `kind` at the screen position (clamped into group `group`'s grid
/// — a child drag stays in the grid like any other) for a live child that
/// asked for the mouse, and writes it.
fn forward_to_child(
    app: &App,
    group: usize,
    kind: MouseEventKind,
    mods: KeyModifiers,
    (col, row): (u16, u16),
) {
    let Some(tab) = app.panes.group_tab(group).filter(|t| t.is_alive()) else {
        return;
    };
    let Some((gc, line)) = app.regions.clamp_to_grid(group, col, row) else {
        return;
    };
    let mode = tab.mode();
    if !mouse::forwards_to_child(mode, mods) {
        return;
    }
    if let Some(bytes) = mouse::encode_mouse(kind, mods, gc, line, mode) {
        tab.write_input(bytes);
    }
}

// --- Key handling -----------------------------------------------------------

/// Handles one key press. Returns `true` when the app should quit.
async fn handle_key(
    app: &mut App,
    view: &WorktreesViewModel,
    dispatcher: &Dispatcher,
    key: KeyEvent,
) -> bool {
    if app.quit_confirm {
        match key.code {
            KeyCode::Char('y') | KeyCode::Enter => return true,
            KeyCode::Char('n') | KeyCode::Esc => app.quit_confirm = false,
            _ => {}
        }
        return false;
    }

    // Chrome chords first, in every focus state and over every popup.
    if let Some(chrome) = keys::chrome_key(&key) {
        handle_chrome_key(app, view, chrome);
        return false;
    }

    // A focused, live terminal takes everything else verbatim.
    if app.focus == Focus::Terminal {
        match app.panes.active_tab().filter(|t| t.is_alive()) {
            Some(tab) => {
                if let KeyRoute::Passthrough(bytes) = keys::route(&key, tab.mode()) {
                    tab.write_input(bytes);
                }
                return false;
            }
            None => app.focus = Focus::Tree, // the child exited; fall through
        }
    }

    let code = key.code;
    if app.relocate.is_some() {
        handle_relocate_key(app, view, dispatcher, code);
        return false;
    }
    if let Some(menu) = &mut app.menu {
        match code {
            KeyCode::Up | KeyCode::Char('k') => menu.move_selection(-1),
            KeyCode::Down | KeyCode::Char('j') => menu.move_selection(1),
            KeyCode::Esc => app.menu = None,
            KeyCode::Enter => {
                if let Some(action) = menu.selected_action() {
                    app.menu = None;
                    match action {
                        ActionKind::MoveClaudeSessionHere | ActionKind::CopyClaudeSessionHere => {
                            let mode = if action == ActionKind::MoveClaudeSessionHere {
                                RelocationMode::Move
                            } else {
                                RelocationMode::Copy
                            };
                            start_relocate_flow(app, view, mode);
                        }
                        _ => {
                            let targets = app.tree.targets(view);
                            run_action(app, dispatcher, action, targets).await;
                        }
                    }
                }
            }
            _ => {}
        }
        return false;
    }

    match &app.flow {
        ActionFlow::AwaitingConfirm {
            action, targets, ..
        } => {
            match code {
                KeyCode::Char('y') | KeyCode::Enter => {
                    let action = *action;
                    let targets = targets.clone();
                    app.flow = ActionFlow::Executing {
                        action,
                        targets: targets.clone(),
                    };
                    let outcome = dispatcher.execute(action, &targets).await;
                    app.flow = ActionFlow::Done { outcome };
                }
                KeyCode::Char('n') | KeyCode::Esc => app.flow = ActionFlow::Idle,
                _ => {}
            }
            return false;
        }
        ActionFlow::Done { .. } | ActionFlow::Failed { .. } => {
            app.flow = ActionFlow::Idle; // any key dismisses
            return false;
        }
        _ => {}
    }

    // Tree-focused, no popup: navigation, marking, and the entry points into
    // the action menu / row-colour pickers / terminal tabs.
    match code {
        KeyCode::Char('q') => {
            if app.panes.any_alive() {
                app.quit_confirm = true;
            } else {
                return true;
            }
        }
        // Esc clears an active multi-select first; only quits once nothing
        // is marked, so a stray Esc while reviewing a selection can't lose it.
        KeyCode::Esc => {
            if !app.tree.marked.is_empty() {
                app.tree.clear_marks();
            } else if app.panes.any_alive() {
                app.quit_confirm = true;
            } else {
                return true;
            }
        }
        KeyCode::Up | KeyCode::Char('k') => {
            let rows = TreeState::visible_rows(view).len();
            app.tree.move_cursor(-1, rows);
        }
        KeyCode::Down | KeyCode::Char('j') => {
            let rows = TreeState::visible_rows(view).len();
            app.tree.move_cursor(1, rows);
        }
        KeyCode::Char(' ') => {
            if let Some(path) = cursor_row_path(&app.tree, view) {
                app.tree.toggle_mark(path);
            }
        }
        KeyCode::Enter => open_tab_for_cursor(app, view, TabKind::Shell, false),
        KeyCode::Char('a') => {
            let targets = app.tree.targets(view);
            let items = actions::applicable_actions(&targets)
                .into_iter()
                .map(|(action, label)| popup::MenuItem { action, label })
                .collect();
            app.menu = Some(popup::ActionMenu::new(items));
        }
        KeyCode::Char('c') => {
            let items = row_colors::KNOWN_ROW_COLORS
                .iter()
                .map(|&color| popup::MenuItem {
                    action: ActionKind::SetRowColor(color),
                    label: color,
                })
                .collect();
            app.menu = Some(popup::ActionMenu::new(items));
        }
        KeyCode::Char('C') => {
            let targets = app.tree.targets(view);
            let outcome = dispatcher
                .execute(ActionKind::ClearRowColor, &targets)
                .await;
            app.flow = ActionFlow::Done { outcome };
        }
        _ => {}
    }
    false
}

fn handle_chrome_key(app: &mut App, view: &WorktreesViewModel, chrome: ChromeKey) {
    match chrome {
        ChromeKey::FocusTree => app.focus = Focus::Tree,
        ChromeKey::FocusTerminal => {
            if app.panes.is_empty() {
                app.notice = Some("no terminal tab — enter or alt-t opens one".to_string());
            } else {
                app.focus = Focus::Terminal;
            }
        }
        ChromeKey::NewShellTab => open_tab_for_cursor(app, view, TabKind::Shell, false),
        ChromeKey::NewClaudeTab => open_tab_for_cursor(app, view, TabKind::Claude, false),
        ChromeKey::SplitShellTab => open_tab_for_cursor(app, view, TabKind::Shell, true),
        ChromeKey::CloseTab => app.close_tab(),
        ChromeKey::NextTab => app.panes.cycle_tab(1),
        ChromeKey::PrevTab => app.panes.cycle_tab(-1),
        ChromeKey::SelectTab(index) => {
            if !app.panes.select_tab(index) {
                app.notice = Some(format!("no tab {}", index + 1));
            }
        }
        ChromeKey::NextGroup => app.panes.cycle_group(1),
        ChromeKey::PrevGroup => app.panes.cycle_group(-1),
        ChromeKey::MoveTabDown => {
            if !app.panes.move_tab_to_group(1) {
                app.notice = Some("no group below to move this tab to".to_string());
            }
        }
        ChromeKey::MoveTabUp => {
            if !app.panes.move_tab_to_group(-1) {
                app.notice = Some("no group above to move this tab to".to_string());
            }
        }
        ChromeKey::ResetLayout => app.panes.reset_weights(),
        ChromeKey::Copy => {
            let text = app
                .panes
                .active_tab()
                .and_then(TerminalTab::selection_to_string);
            app.notice = Some(match text {
                Some(text) if clipboard::copy_text(&text).is_ok() => {
                    // Copying consumes the selection, as in tmux/screen.
                    if let Some(tab) = app.panes.active_tab() {
                        tab.clear_selection();
                    }
                    "copied".to_string()
                }
                Some(_) => "clipboard unavailable".to_string(),
                None => "nothing selected".to_string(),
            });
        }
        ChromeKey::ScrollPageUp => {
            if let Some(tab) = app.panes.active_tab() {
                tab.scroll(Scroll::PageUp);
            }
        }
        ChromeKey::ScrollPageDown => {
            if let Some(tab) = app.panes.active_tab() {
                tab.scroll(Scroll::PageDown);
            }
        }
    }
}

/// Opens (or focuses) a `kind` tab in the cursor worktree, in a new group
/// below when `split`. The initial size is a placeholder — the first `draw`
/// resizes the emulator to the real pane before its grid is ever read.
fn open_tab_for_cursor(app: &mut App, view: &WorktreesViewModel, kind: TabKind, split: bool) {
    let Some(worktree) = app.cursor_worktree(view) else {
        app.notice = Some("no row selected".to_string());
        return;
    };
    // Refuse a split that could not be drawn rather than silently dropping
    // the new group off the bottom of the pane.
    if split {
        let height = app.terminal_area.map_or(0, |a| a.height);
        if height < panes::min_height_for(app.panes.group_count() + 1) {
            app.notice = Some("not enough height to split — close a group first".to_string());
            return;
        }
    }
    app.open_tab(
        kind,
        worktree,
        GridSize {
            cols: 80,
            lines: 24,
        },
        split,
    );
}

/// Runs the generic check→(confirm)→execute flow for every [`ActionKind`]
/// except the two session-relocation variants (routed separately — see
/// [`start_relocate_flow`]).
async fn run_action(
    app: &mut App,
    dispatcher: &Dispatcher,
    action: ActionKind,
    targets: Vec<Target>,
) {
    app.flow = ActionFlow::Checking {
        action,
        targets: targets.clone(),
    };
    match dispatcher.check(action, &targets).await {
        CheckReport::ProceedWithoutConfirm => {
            app.flow = ActionFlow::Executing {
                action,
                targets: targets.clone(),
            };
            let outcome = dispatcher.execute(action, &targets).await;
            app.flow = ActionFlow::Done { outcome };
        }
        CheckReport::NeedsConfirm { prompt, .. } => {
            app.flow = ActionFlow::AwaitingConfirm {
                action,
                targets,
                prompt,
            };
        }
        CheckReport::Refused { reason } => {
            app.flow = ActionFlow::Failed { error: reason };
        }
    }
}

/// The cursor row's path — a repo root or a worktree path — regardless of
/// mark state (used for `space` to toggle a mark on the row under the
/// cursor).
fn cursor_row_path(tree: &TreeState, view: &WorktreesViewModel) -> Option<PathBuf> {
    match tree.targets_for_cursor_only(view).first()? {
        Target::Repo { root, .. } => Some(root.clone()),
        Target::Worktree { path, .. } => Some(path.clone()),
    }
}

/// Starts the Move/Copy-Claude-Session-Here wizard from the cursor row (the
/// action menu only offers this action for a single worktree target with at
/// least one session — see `actions::applicable_actions` — so the cursor row
/// is unambiguous here).
fn start_relocate_flow(app: &mut App, view: &WorktreesViewModel, mode: RelocationMode) {
    let Some(Target::Worktree { path, .. }) = tree_only_target(&app.tree, view) else {
        app.flow = ActionFlow::Failed {
            error: "no worktree row selected".to_string(),
        };
        return;
    };
    let Some(source_dir) = relocate::project_dir_for(&path) else {
        app.flow = ActionFlow::Failed {
            error: "could not resolve the Claude projects directory".to_string(),
        };
        return;
    };
    let mut sessions = match relocate::enumerate_sessions(&source_dir) {
        Ok(sessions) => sessions,
        Err(e) => {
            app.flow = ActionFlow::Failed {
                error: format!("{e:#}"),
            };
            return;
        }
    };
    if sessions.is_empty() {
        app.flow = ActionFlow::Failed {
            error: "no Claude sessions found here".to_string(),
        };
        return;
    }
    if sessions.len() == 1 {
        let session = sessions.remove(0);
        let candidates = other_worktree_paths(view, &path);
        app.relocate = Some(RelocateStep::PickDestination {
            mode,
            source_dir,
            session,
            candidates,
            selected: 0,
        });
    } else {
        app.relocate = Some(RelocateStep::PickSession {
            mode,
            source_worktree: path,
            source_dir,
            sessions,
            selected: 0,
        });
    }
}

fn tree_only_target(tree: &TreeState, view: &WorktreesViewModel) -> Option<Target> {
    tree.targets_for_cursor_only(view).into_iter().next()
}

fn other_worktree_paths(view: &WorktreesViewModel, exclude: &Path) -> Vec<PathBuf> {
    view.repos
        .iter()
        .flat_map(|repo| repo.worktrees.iter())
        .map(|wt| wt.path.clone())
        .filter(|p| p != exclude)
        .collect()
}

fn handle_relocate_key(
    app: &mut App,
    view: &WorktreesViewModel,
    dispatcher: &Dispatcher,
    code: KeyCode,
) {
    match code {
        KeyCode::Esc => app.relocate = None,
        KeyCode::Up | KeyCode::Char('k') => move_relocate_selection(app, -1),
        KeyCode::Down | KeyCode::Char('j') => move_relocate_selection(app, 1),
        KeyCode::Enter | KeyCode::Char('y') => advance_relocate(app, view, dispatcher),
        KeyCode::Char('n') => {
            if matches!(app.relocate, Some(RelocateStep::Confirm { .. })) {
                app.relocate = None;
            }
        }
        _ => {}
    }
}

fn move_relocate_selection(app: &mut App, delta: isize) {
    match &mut app.relocate {
        Some(RelocateStep::PickSession {
            sessions, selected, ..
        }) => *selected = clamp_selection(*selected, delta, sessions.len()),
        Some(RelocateStep::PickDestination {
            candidates,
            selected,
            ..
        }) => *selected = clamp_selection(*selected, delta, candidates.len()),
        Some(RelocateStep::Confirm { .. }) | None => {}
    }
}

fn clamp_selection(current: usize, delta: isize, len: usize) -> usize {
    if len == 0 {
        return 0;
    }
    let max = len - 1;
    let current = current.min(max) as isize;
    (current + delta).clamp(0, max as isize) as usize
}

fn advance_relocate(app: &mut App, view: &WorktreesViewModel, dispatcher: &Dispatcher) {
    match app.relocate.take() {
        Some(RelocateStep::PickSession {
            mode,
            source_worktree,
            source_dir,
            mut sessions,
            selected,
        }) => {
            if selected >= sessions.len() {
                return;
            }
            let session = sessions.swap_remove(selected);
            let candidates = other_worktree_paths(view, &source_worktree);
            app.relocate = Some(RelocateStep::PickDestination {
                mode,
                source_dir,
                session,
                candidates,
                selected: 0,
            });
        }
        Some(RelocateStep::PickDestination {
            mode,
            source_dir,
            session,
            candidates,
            selected,
            ..
        }) => {
            let Some(dest_worktree) = candidates.into_iter().nth(selected) else {
                return;
            };
            match dispatcher.check_relocate_session(&source_dir, &session, &dest_worktree) {
                CheckReport::NeedsConfirm { prompt, .. } => {
                    app.relocate = Some(RelocateStep::Confirm {
                        mode,
                        source_dir,
                        session,
                        dest_worktree,
                        prompt,
                    });
                }
                CheckReport::Refused { reason } => {
                    app.flow = ActionFlow::Failed { error: reason };
                }
                CheckReport::ProceedWithoutConfirm => {
                    let outcome = dispatcher.execute_relocate_session(
                        &source_dir,
                        &session,
                        &dest_worktree,
                        mode,
                    );
                    app.flow = ActionFlow::Done { outcome };
                }
            }
        }
        Some(RelocateStep::Confirm {
            mode,
            source_dir,
            session,
            dest_worktree,
            ..
        }) => {
            let outcome =
                dispatcher.execute_relocate_session(&source_dir, &session, &dest_worktree, mode);
            app.flow = ActionFlow::Done { outcome };
        }
        None => {}
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;

    use crossterm::event::KeyModifiers;
    use ratatui::backend::TestBackend;

    use super::super::client::WorktreesClient;
    use super::super::view_model::{RepoRow, WorktreeRow};

    fn view_with(paths: &[&str]) -> WorktreesViewModel {
        let worktrees = paths
            .iter()
            .map(|p| WorktreeRow {
                path: PathBuf::from(p),
                branch: Some("main".to_string()),
                head_sha: None,
                upstream_sha: None,
                is_main: false,
                open: false,
                window_key: None,
                pr: None,
                pr_none: false,
                operation: None,
                rebasing: false,
                pushing: false,
                ahead_behind: super::super::view_model::AheadBehindState::Unknown,
                sessions: Vec::new(),
                row_color: None,
                here: false,
            })
            .collect();
        WorktreesViewModel {
            repos: vec![RepoRow {
                main_repo: "repo".to_string(),
                github: None,
                root: PathBuf::from("/repo"),
                polling_enabled: false,
                row_color: None,
                worktrees,
            }],
            ..Default::default()
        }
    }

    /// An app wired to a nonexistent daemon socket (no action here reaches
    /// it) with the hub-command receiver returned for assertions.
    fn test_app() -> (App, Dispatcher, mpsc::UnboundedReceiver<HubCommand>) {
        let (commands, commands_rx) = mpsc::unbounded_channel();
        let (pty_tx, _pty_rx) = mpsc::unbounded_channel();
        let dispatcher = Dispatcher::new(
            WorktreesClient::new("/tmp/nonexistent-omni-dev-app-test.sock"),
            commands.clone(),
        );
        let app = App {
            tree: TreeState::default(),
            flow: ActionFlow::Idle,
            menu: None,
            relocate: None,
            focus: Focus::Tree,
            panes: panes::PaneLayout::default(),
            quit_confirm: false,
            notice: None,
            pty_tx,
            commands,
            regions: RegionMap::default(),
            terminal_area: None,
            drag: DragOrigin::None,
            clicks: mouse::ClickTracker::default(),
        };
        (app, dispatcher, commands_rx)
    }

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

    fn alt(c: char) -> KeyEvent {
        KeyEvent::new(KeyCode::Char(c), KeyModifiers::ALT)
    }

    fn alt_key(code: KeyCode, extra: KeyModifiers) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::ALT | extra)
    }

    /// Installs an already-spawned tab as the app's only tab — the pane
    /// stack's equivalent of Phase 3's `app.terminal = Some(tab)`.
    #[cfg(unix)]
    fn install_tab(app: &mut App, tab: TerminalTab) {
        app.panes
            .open_tab(move |_| Ok(tab))
            .expect("installing a prebuilt tab cannot fail");
    }

    /// The first rendered group's grid rect.
    fn grid_rect(app: &App) -> Rect {
        app.regions
            .groups
            .first()
            .map(|g| g.grid)
            .expect("a terminal region")
    }

    /// The app's single active tab, for assertions.
    fn only_tab(app: &App) -> &TerminalTab {
        app.panes.active_tab().expect("a tab")
    }

    fn only_tab_mut(app: &mut App) -> Option<&mut TerminalTab> {
        let focused = app.panes.focused;
        app.panes.groups.get_mut(focused)?.active_tab_mut()
    }

    /// Shuts every tab down, so a test's children never outlive it.
    fn shutdown_all(app: &mut App) {
        for group in &mut app.panes.groups {
            for tab in &mut group.tabs {
                tab.shutdown();
            }
        }
    }

    fn mouse_at(kind: MouseEventKind, col: u16, row: u16, modifiers: KeyModifiers) -> MouseEvent {
        MouseEvent {
            kind,
            column: col,
            row,
            modifiers,
        }
    }

    fn draw_into(terminal: &mut Terminal<TestBackend>, view: &WorktreesViewModel, app: &mut App) {
        terminal.draw(|frame| draw(frame, view, app)).unwrap();
    }

    /// Polls `cond` for up to ten seconds.
    async fn wait_until(mut cond: impl FnMut() -> bool) -> bool {
        for _ in 0..100 {
            if cond() {
                return true;
            }
            tokio::time::sleep(Duration::from_millis(100)).await;
        }
        false
    }

    #[cfg(unix)]
    fn scripted_tab(app: &App, script: &str, cwd: PathBuf) -> TerminalTab {
        let request = super::super::terminal::pty::SpawnRequest {
            tab: 1,
            program: Some((
                "/bin/sh".to_string(),
                vec!["-c".to_string(), script.to_string()],
            )),
            cwd,
            size: GridSize { cols: 40, lines: 6 },
            extra_env: Vec::new(),
        };
        TerminalTab::from_request(TabKind::Shell, request, app.pty_tx.clone()).unwrap()
    }

    fn buffer_text(terminal: &Terminal<TestBackend>) -> String {
        terminal
            .backend()
            .buffer()
            .content
            .iter()
            .map(ratatui::buffer::Cell::symbol)
            .collect()
    }

    #[tokio::test]
    async fn tree_keys_move_mark_open_menus_and_quit() {
        let (mut app, dispatcher, mut commands) = test_app();
        let view = view_with(&["/repo/a", "/repo/b"]);

        assert!(!handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char('j'))).await);
        assert_eq!(app.tree.cursor, 1);
        assert!(!handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char('k'))).await);
        assert_eq!(app.tree.cursor, 0);
        assert!(!handle_key(&mut app, &view, &dispatcher, press(KeyCode::Down)).await);

        // Space marks the cursor row; Esc clears marks before it quits.
        assert!(!handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char(' '))).await);
        assert_eq!(app.tree.marked.len(), 1);
        assert!(!handle_key(&mut app, &view, &dispatcher, press(KeyCode::Esc)).await);
        assert!(app.tree.marked.is_empty());
        assert!(handle_key(&mut app, &view, &dispatcher, press(KeyCode::Esc)).await);
        assert!(handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char('q'))).await);

        // The action menu opens on `a`, navigates, and closes on Esc.
        assert!(!handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char('a'))).await);
        assert!(app.menu.is_some());
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Down)).await;
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char('k'))).await;
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Esc)).await;
        assert!(app.menu.is_none());

        // The colour picker dispatches a local SetRowColor through the hub.
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char('c'))).await;
        assert!(app.menu.is_some());
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Enter)).await;
        assert!(matches!(app.flow, ActionFlow::Done { .. }));
        assert!(matches!(
            commands.try_recv(),
            Ok(HubCommand::SetRowColor(..))
        ));
        assert!(status_hint(&app).starts_with("Set colour"));
        // Any key dismisses the outcome.
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char('x'))).await;
        assert_eq!(app.flow, ActionFlow::Idle);

        // `C` clears directly, no popup.
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char('C'))).await;
        assert!(matches!(
            commands.try_recv(),
            Ok(HubCommand::ClearRowColor(_))
        ));
        assert!(matches!(app.flow, ActionFlow::Done { .. }));
        app.flow = ActionFlow::Idle;

        // An unknown key is ignored.
        assert!(!handle_key(&mut app, &view, &dispatcher, press(KeyCode::F(9))).await);
    }

    #[tokio::test]
    async fn an_action_that_needs_the_daemon_fails_visibly_when_it_is_down() {
        let (mut app, dispatcher, _commands) = test_app();
        let view = view_with(&["/repo/a"]);
        app.tree.cursor = 1; // the worktree row, not the repo header
                             // Open the menu and pick "Close Window" (ProceedWithoutConfirm, one
                             // daemon call) — the socket does not exist, so the batch reports it.
        let targets = app.tree.targets(&view);
        run_action(&mut app, &dispatcher, ActionKind::CloseWindow, targets).await;
        match &app.flow {
            ActionFlow::Done {
                outcome: actions::ActionOutcome::BatchDone { results },
            } => assert!(results.iter().all(|(_, r)| r.is_err())),
            other => panic!("unexpected flow: {other:?}"),
        }
        assert!(status_hint(&app).contains("failed"));

        // A two-phase check against a dead daemon is refused, not confirmed.
        let targets = app.tree.targets(&view);
        run_action(&mut app, &dispatcher, ActionKind::CloseWorktree, targets).await;
        assert!(matches!(app.flow, ActionFlow::Failed { .. }));
        assert!(status_hint(&app).starts_with("failed:"));

        // A confirm that arrives is answered by y/n.
        app.flow = ActionFlow::AwaitingConfirm {
            action: ActionKind::CloseWorktree,
            targets: Vec::new(),
            prompt: actions::ConfirmPrompt::default(),
        };
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char('n'))).await;
        assert_eq!(app.flow, ActionFlow::Idle);
        app.flow = ActionFlow::AwaitingConfirm {
            action: ActionKind::CloseWorktree,
            targets: Vec::new(),
            prompt: actions::ConfirmPrompt::default(),
        };
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char('y'))).await;
        assert!(matches!(app.flow, ActionFlow::Done { .. }));
    }

    #[tokio::test]
    async fn chrome_chords_without_a_terminal_leave_notices() {
        let (mut app, dispatcher, _commands) = test_app();
        let view = view_with(&["/repo/a"]);
        handle_key(&mut app, &view, &dispatcher, alt('l')).await;
        assert!(app
            .notice
            .as_deref()
            .unwrap_or("")
            .contains("no terminal tab"));
        handle_key(&mut app, &view, &dispatcher, alt('c')).await;
        assert_eq!(app.notice.as_deref(), Some("nothing selected"));
        handle_key(&mut app, &view, &dispatcher, alt('w')).await; // no tab: no-op
        assert_eq!(app.focus, Focus::Tree);
        handle_key(&mut app, &view, &dispatcher, alt('e')).await;
        assert_eq!(app.focus, Focus::Tree);
        handle_key(
            &mut app,
            &view,
            &dispatcher,
            KeyEvent::new(KeyCode::PageUp, KeyModifiers::SHIFT),
        )
        .await;
        handle_key(
            &mut app,
            &view,
            &dispatcher,
            KeyEvent::new(KeyCode::PageDown, KeyModifiers::SHIFT),
        )
        .await;
        // A stray PTY event for a tab that no longer exists is ignored.
        assert!(!app.handle_pty_event(99, TermEvent::Wakeup));
        app.forward_focus(true); // no terminal: no-op
    }

    #[tokio::test]
    async fn relocate_wizard_fails_cleanly_without_sessions_and_cancels() {
        let (mut app, dispatcher, _commands) = test_app();
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().to_string_lossy().into_owned();
        let view = view_with(&[&path, "/repo/other"]);

        // No Claude sessions exist for a fresh temp dir.
        start_relocate_flow(&mut app, &view, RelocationMode::Move);
        assert!(matches!(app.flow, ActionFlow::Failed { .. }));
        app.flow = ActionFlow::Idle;

        // Navigating and cancelling each picker step.
        let session = actions::relocate_types::SessionInfo {
            id: "s1".to_string(),
            jsonl_path: dir.path().join("s1.jsonl"),
            modified: std::time::SystemTime::UNIX_EPOCH,
            has_sidecar: false,
        };
        app.relocate = Some(RelocateStep::PickSession {
            mode: RelocationMode::Copy,
            source_worktree: dir.path().to_path_buf(),
            source_dir: dir.path().to_path_buf(),
            sessions: vec![session.clone(), session.clone()],
            selected: 0,
        });
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Down)).await;
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Up)).await;
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Enter)).await;
        assert!(matches!(
            app.relocate,
            Some(RelocateStep::PickDestination { .. })
        ));
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char('j'))).await;
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char('n'))).await; // no-op here
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Esc)).await;
        assert!(app.relocate.is_none());

        // The confirm step can be declined.
        app.relocate = Some(RelocateStep::Confirm {
            mode: RelocationMode::Copy,
            source_dir: dir.path().to_path_buf(),
            session,
            dest_worktree: PathBuf::from("/repo/other"),
            prompt: actions::ConfirmPrompt::default(),
        });
        let mut terminal = Terminal::new(TestBackend::new(80, 24)).unwrap();
        terminal.draw(|frame| draw(frame, &view, &mut app)).unwrap();
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char('n'))).await;
        assert!(app.relocate.is_none());
        assert_eq!(clamp_selection(5, 1, 0), 0);
        assert!(relative_mtime(std::time::SystemTime::now()).ends_with("ago"));
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn a_terminal_tab_takes_focus_keys_and_closes_cleanly() {
        let (mut app, dispatcher, mut commands) = test_app();
        let dir = tempfile::tempdir().unwrap();
        let here = dir.path().to_path_buf();
        let view = view_with(&[&here.to_string_lossy(), "/repo/other"]);

        // Inject a scripted shell as the tab, exactly as open_tab would.
        let request = super::super::terminal::pty::SpawnRequest {
            tab: 1,
            program: Some((
                "/bin/sh".to_string(),
                vec!["-c".to_string(), "sleep 5".to_string()],
            )),
            cwd: here.clone(),
            size: GridSize { cols: 40, lines: 6 },
            extra_env: Vec::new(),
        };
        let tab = TerminalTab::from_request(TabKind::Shell, request, app.pty_tx.clone()).unwrap();
        install_tab(&mut app, tab);
        app.focus = Focus::Terminal;

        // Keys go to the child, Esc included; chords are still chrome.
        assert!(!handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char('x'))).await);
        assert!(!handle_key(&mut app, &view, &dispatcher, press(KeyCode::Esc)).await);
        assert!(!handle_key(&mut app, &view, &dispatcher, press(KeyCode::CapsLock)).await);
        handle_key(&mut app, &view, &dispatcher, alt('e')).await;
        assert_eq!(app.focus, Focus::Tree);
        handle_key(&mut app, &view, &dispatcher, alt('l')).await;
        assert_eq!(app.focus, Focus::Terminal);
        assert!(status_hint(&app).contains("alt-e tree"));
        app.forward_focus(false);
        app.forward_focus(true);

        // Opening the same worktree again focuses the tab it already has
        // rather than opening a duplicate (Phase 4b: a second worktree now
        // opens a second tab instead of being refused).
        app.focus = Focus::Tree;
        app.open_tab(
            TabKind::Shell,
            here.clone(),
            GridSize {
                cols: 80,
                lines: 24,
            },
            false,
        );
        assert_eq!(app.focus, Focus::Terminal);
        assert_eq!(app.panes.groups[0].tabs.len(), 1, "no duplicate tab");

        // Drawing lays out both panes, resizes the emulator to the pane, and
        // shows the quit confirm when `q` is pressed with a live child.
        let mut terminal = Terminal::new(TestBackend::new(100, 20)).unwrap();
        terminal.draw(|frame| draw(frame, &view, &mut app)).unwrap();
        assert!(buffer_text(&terminal).contains("WORKTREES"));
        app.focus = Focus::Tree;
        assert!(!handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char('q'))).await);
        assert!(app.quit_confirm);
        terminal.draw(|frame| draw(frame, &view, &mut app)).unwrap();
        assert!(buffer_text(&terminal).contains("Quit?"));
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char('n'))).await;
        assert!(!app.quit_confirm);
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Esc)).await;
        assert!(app.quit_confirm);
        handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char('x'))).await; // ignored
        assert!(handle_key(&mut app, &view, &dispatcher, press(KeyCode::Char('y'))).await);
        app.quit_confirm = false;

        // Live PTY events flow through the tab; then alt-w closes it.
        assert!(app.handle_pty_event(1, TermEvent::Wakeup));
        assert!(!app.handle_pty_event(1, TermEvent::Bell));
        assert!(app.handle_pty_event(1, TermEvent::ChildExit(std::process::ExitStatus::default())));
        assert!(app
            .notice
            .as_deref()
            .unwrap_or("")
            .contains("terminal exited"));
        only_tab_mut(&mut app).unwrap().exit_status = None; // pretend it is still live
        handle_key(&mut app, &view, &dispatcher, alt('w')).await;
        assert!(app.panes.is_empty());
        assert_eq!(app.focus, Focus::Tree);
        assert!(matches!(commands.try_recv(), Ok(HubCommand::ClearOpenTab(p)) if p == here));
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn open_tab_for_cursor_spawns_and_reports_here_beside_an_exited_tab() {
        let (mut app, _dispatcher, mut commands) = test_app();
        let dir = tempfile::tempdir().unwrap();
        let here = dir.path().to_path_buf();
        let view = view_with(&[&here.to_string_lossy()]);
        app.tree.cursor = 1; // the worktree row, not the repo header

        // Route the real spawn through a scripted child by pre-seeding an
        // exited tab: open_tab must close it and spawn afresh.
        let request = super::super::terminal::pty::SpawnRequest {
            tab: 1,
            program: Some((
                "/bin/sh".to_string(),
                vec!["-c".to_string(), "true".to_string()],
            )),
            cwd: here.clone(),
            size: GridSize { cols: 40, lines: 6 },
            extra_env: Vec::new(),
        };
        let mut tab =
            TerminalTab::from_request(TabKind::Shell, request, app.pty_tx.clone()).unwrap();
        tab.exit_status = Some(std::process::ExitStatus::default());
        install_tab(&mut app, tab);

        // A missing cursor row is a notice, not a spawn.
        let empty = WorktreesViewModel::default();
        open_tab_for_cursor(&mut app, &empty, TabKind::Shell, false);
        assert_eq!(app.notice.as_deref(), Some("no row selected"));

        // With a row: an exited tab is not reused (it keeps its grid and
        // exit status on screen until closed), so the user's shell is
        // spawned as a second tab beside it and reported open.
        open_tab_for_cursor(&mut app, &view, TabKind::Shell, false);
        match commands.try_recv() {
            Ok(HubCommand::SetOpenTab(p)) => assert_eq!(p, here),
            other => {
                // Spawning the login shell can legitimately fail on a
                // minimal CI image; then the notice carries the error.
                assert!(
                    app.notice.is_some(),
                    "neither a tab nor a notice: {other:?}"
                );
            }
        }
        shutdown_all(&mut app);
    }

    #[tokio::test]
    async fn mouse_on_the_tree_focuses_marks_ranges_scrolls_and_ignores_chrome() {
        let (mut app, _dispatcher, _commands) = test_app();
        let view = view_with(&["/repo/a", "/repo/b", "/repo/c"]); // 4 rows with the header
        let mut terminal = Terminal::new(TestBackend::new(80, 12)).unwrap();
        draw_into(&mut terminal, &view, &mut app);
        let tree = app.regions.tree;
        assert_eq!((tree.x, tree.y), (1, 1), "inside the border");
        let none = KeyModifiers::NONE;
        let down = |row: u16, mods| mouse_at(MouseEventKind::Down(MouseButton::Left), 5, row, mods);

        // The border is chrome; a click there does nothing.
        assert!(!handle_mouse(&mut app, &view, down(0, none)));
        // A click on row 2 moves the cursor there.
        assert!(handle_mouse(&mut app, &view, down(tree.y + 2, none)));
        assert_eq!(app.tree.cursor, 2);
        assert_eq!(app.drag, DragOrigin::Tree { anchor: 2 });
        assert!(!handle_mouse(
            &mut app,
            &view,
            mouse_at(MouseEventKind::Up(MouseButton::Left), 5, 3, none)
        ));
        assert_eq!(app.drag, DragOrigin::None);
        assert!(app.tree.marked.is_empty(), "a click alone marks nothing");

        // ^-click toggles a mark; ⇧-click marks the range from the cursor.
        assert!(handle_mouse(
            &mut app,
            &view,
            down(tree.y + 3, KeyModifiers::CONTROL)
        ));
        assert!(app.tree.marked.contains(&PathBuf::from("/repo/c")));
        assert!(handle_mouse(
            &mut app,
            &view,
            down(tree.y + 1, KeyModifiers::SHIFT)
        ));
        assert_eq!(app.tree.cursor, 1);
        assert_eq!(app.tree.marked.len(), 3, "rows 1..=3 marked");
        app.tree.clear_marks();

        // A drag from row 1 to below the pane range-marks down to the last
        // row and stops there (clamped to the tree).
        assert!(handle_mouse(&mut app, &view, down(tree.y + 1, none)));
        assert!(handle_mouse(
            &mut app,
            &view,
            mouse_at(MouseEventKind::Drag(MouseButton::Left), 200, 200, none)
        ));
        assert_eq!(app.tree.cursor, 3);
        assert_eq!(app.tree.marked.len(), 3);
        handle_mouse(
            &mut app,
            &view,
            mouse_at(MouseEventKind::Up(MouseButton::Left), 200, 200, none),
        );

        // The wheel moves the cursor; below the last row only focus changes.
        assert!(handle_mouse(
            &mut app,
            &view,
            mouse_at(MouseEventKind::ScrollUp, 5, tree.y, none)
        ));
        assert_eq!(app.tree.cursor, 2);
        assert!(handle_mouse(
            &mut app,
            &view,
            mouse_at(MouseEventKind::ScrollDown, 5, tree.y, none)
        ));
        assert_eq!(app.tree.cursor, 3);
        assert!(handle_mouse(&mut app, &view, down(tree.y + 8, none)));
        assert_eq!(app.tree.cursor, 3);
        // A right-click focuses without starting a drag.
        assert!(handle_mouse(
            &mut app,
            &view,
            mouse_at(MouseEventKind::Down(MouseButton::Right), 5, tree.y, none)
        ));
        assert_eq!(app.tree.cursor, 0);
        assert_eq!(app.drag, DragOrigin::None);
        assert!(!handle_mouse(
            &mut app,
            &view,
            mouse_at(MouseEventKind::Drag(MouseButton::Right), 5, 3, none)
        ));
        // Moves and horizontal wheel are inert with no terminal.
        assert!(!handle_mouse(
            &mut app,
            &view,
            mouse_at(MouseEventKind::Moved, 5, 3, none)
        ));
        assert!(!handle_mouse(
            &mut app,
            &view,
            mouse_at(MouseEventKind::ScrollLeft, 5, 3, none)
        ));

        // With a popup open the mouse is inert.
        app.menu = Some(popup::ActionMenu::new(Vec::new()));
        assert!(!handle_mouse(&mut app, &view, down(tree.y, none)));
        app.menu = None;
        app.quit_confirm = true;
        assert!(!handle_mouse(&mut app, &view, down(tree.y, none)));
        app.quit_confirm = false;
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn a_double_click_on_a_row_opens_a_shell_tab_there() {
        let (mut app, _dispatcher, _commands) = test_app();
        let dir = tempfile::tempdir().unwrap();
        let view = view_with(&[&dir.path().to_string_lossy()]);
        let mut terminal = Terminal::new(TestBackend::new(80, 12)).unwrap();
        draw_into(&mut terminal, &view, &mut app);
        let y = app.regions.tree.y + 1; // the worktree row
        let click = mouse_at(
            MouseEventKind::Down(MouseButton::Left),
            5,
            y,
            KeyModifiers::NONE,
        );
        handle_mouse(&mut app, &view, click);
        handle_mouse(
            &mut app,
            &view,
            mouse_at(
                MouseEventKind::Up(MouseButton::Left),
                5,
                y,
                KeyModifiers::NONE,
            ),
        );
        handle_mouse(&mut app, &view, click);
        assert_eq!(app.tree.cursor, 1);
        // Either the login shell spawned (and took focus) or, on a minimal
        // image, the failure is reported — never silence.
        assert!(
            !app.panes.is_empty() || app.notice.is_some(),
            "double-click neither opened a tab nor reported a failure"
        );
        if !app.panes.is_empty() {
            assert_eq!(app.focus, Focus::Terminal);
        }
        app.close_tab();
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn mouse_on_the_terminal_selects_by_drag_word_and_line_and_scrolls() {
        let (mut app, _dispatcher, _commands) = test_app();
        let dir = tempfile::tempdir().unwrap();
        let view = view_with(&[&dir.path().to_string_lossy()]);
        let tab = scripted_tab(
            &app,
            "printf 'hello world\\nsecond line\\n'; sleep 3",
            dir.path().to_path_buf(),
        );
        install_tab(&mut app, tab);
        let mut terminal = Terminal::new(TestBackend::new(100, 12)).unwrap();
        draw_into(&mut terminal, &view, &mut app);
        let grid = grid_rect(&app);
        assert!(
            wait_until(|| only_tab(&app).selection_to_string().is_none() && {
                draw_into(&mut terminal, &view, &mut app);
                buffer_text(&terminal).contains("second line")
            })
            .await,
            "the child's output never rendered"
        );
        let none = KeyModifiers::NONE;
        let at = |kind, col: u16, line: u16| mouse_at(kind, grid.x + col, grid.y + line, none);

        // Click focuses the terminal; drag selects; the drag is clamped so
        // overshooting the pane still ends on its last cell.
        app.focus = Focus::Tree;
        assert!(handle_mouse(
            &mut app,
            &view,
            at(MouseEventKind::Down(MouseButton::Left), 0, 0)
        ));
        assert_eq!(app.focus, Focus::Terminal);
        assert_eq!(app.drag, DragOrigin::Terminal { group: 0 });
        assert!(handle_mouse(
            &mut app,
            &view,
            at(MouseEventKind::Drag(MouseButton::Left), 4, 0)
        ));
        assert!(!handle_mouse(
            &mut app,
            &view,
            at(MouseEventKind::Up(MouseButton::Left), 4, 0)
        ));
        assert_eq!(app.drag, DragOrigin::None);
        assert_eq!(
            only_tab(&app).selection_to_string().as_deref(),
            Some("hello")
        );
        assert!(handle_mouse(
            &mut app,
            &view,
            at(MouseEventKind::Down(MouseButton::Left), 0, 1)
        ));
        assert!(handle_mouse(
            &mut app,
            &view,
            mouse_at(MouseEventKind::Drag(MouseButton::Left), 0, 0, none)
        ));
        assert!(handle_mouse(
            &mut app,
            &view,
            mouse_at(MouseEventKind::Drag(MouseButton::Left), 500, 500, none)
        ));
        let clamped = only_tab(&app).selection_to_string().unwrap();
        assert!(clamped.starts_with("second line"), "got {clamped:?}");
        handle_mouse(
            &mut app,
            &view,
            at(MouseEventKind::Up(MouseButton::Left), 0, 1),
        );

        // Double-click selects the word, triple-click the line.
        let dbl = at(MouseEventKind::Down(MouseButton::Left), 7, 0);
        handle_mouse(&mut app, &view, dbl);
        handle_mouse(
            &mut app,
            &view,
            at(MouseEventKind::Up(MouseButton::Left), 7, 0),
        );
        handle_mouse(&mut app, &view, dbl);
        assert_eq!(
            only_tab(&app).selection_to_string().as_deref(),
            Some("world")
        );
        handle_mouse(
            &mut app,
            &view,
            at(MouseEventKind::Up(MouseButton::Left), 7, 0),
        );
        handle_mouse(&mut app, &view, dbl);
        // A line selection's text carries the line's own trailing newline.
        let line = only_tab(&app).selection_to_string();
        assert_eq!(line.as_deref().map(str::trim_end), Some("hello world"));
        handle_mouse(
            &mut app,
            &view,
            at(MouseEventKind::Up(MouseButton::Left), 7, 0),
        );
        draw_into(&mut terminal, &view, &mut app); // the selection renders
                                                   // alt-c copies (OSC 52 fallback in CI) and consumes the selection.
        handle_chrome_key(&mut app, &view, ChromeKey::Copy);
        assert_eq!(app.notice.as_deref(), Some("copied"));
        assert!(only_tab(&app).selection_to_string().is_none());

        // The wheel scrolls the emulator's history (no child mouse mode, not
        // the alt screen); a middle click neither pastes nor selects.
        assert!(handle_mouse(
            &mut app,
            &view,
            at(MouseEventKind::ScrollUp, 1, 1)
        ));
        assert!(handle_mouse(
            &mut app,
            &view,
            at(MouseEventKind::ScrollDown, 1, 1)
        ));
        assert!(handle_mouse(
            &mut app,
            &view,
            at(MouseEventKind::Down(MouseButton::Middle), 1, 1)
        ));
        assert_eq!(app.drag, DragOrigin::None);
        assert!(!handle_mouse(
            &mut app,
            &view,
            at(MouseEventKind::Moved, 1, 1)
        ));
        assert!(!handle_mouse(
            &mut app,
            &view,
            at(MouseEventKind::ScrollRight, 1, 1)
        ));
        app.close_tab();
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn a_child_that_asked_for_the_mouse_receives_it_unless_alt_is_held() {
        let (mut app, _dispatcher, _commands) = test_app();
        let dir = tempfile::tempdir().unwrap();
        let view = view_with(&[&dir.path().to_string_lossy()]);
        // Enable SGR click reporting, then print the first nine bytes the
        // TUI sends (exactly one SGR press) in a form the grid can show.
        let script = "stty -echo -icanon min 1 time 0; printf '\\033[?1000h\\033[?1006h'; \
                      dd bs=1 count=9 2>/dev/null | od -An -c; sleep 2";
        let tab = scripted_tab(&app, script, dir.path().to_path_buf());
        install_tab(&mut app, tab);
        let mut terminal = Terminal::new(TestBackend::new(100, 12)).unwrap();
        draw_into(&mut terminal, &view, &mut app);
        let grid = grid_rect(&app);
        assert!(
            wait_until(|| only_tab(&app).mode().contains(TermMode::SGR_MOUSE)).await,
            "the child never enabled mouse reporting"
        );
        let none = KeyModifiers::NONE;

        // Alt-click: the TUI keeps the mouse and starts a selection.
        assert!(handle_mouse(
            &mut app,
            &view,
            mouse_at(
                MouseEventKind::Down(MouseButton::Left),
                grid.x,
                grid.y,
                KeyModifiers::ALT
            )
        ));
        assert_eq!(app.drag, DragOrigin::Terminal { group: 0 });
        handle_mouse(
            &mut app,
            &view,
            mouse_at(
                MouseEventKind::Up(MouseButton::Left),
                grid.x,
                grid.y,
                KeyModifiers::ALT,
            ),
        );

        // A plain click goes to the child, as does its release and any
        // motion in between; the child prints what it got.
        assert!(handle_mouse(
            &mut app,
            &view,
            mouse_at(
                MouseEventKind::Down(MouseButton::Left),
                grid.x,
                grid.y,
                none
            )
        ));
        assert_eq!(app.drag, DragOrigin::Child { group: 0 });
        assert!(!handle_mouse(
            &mut app,
            &view,
            mouse_at(
                MouseEventKind::Drag(MouseButton::Left),
                grid.x + 1,
                grid.y,
                none
            )
        ));
        assert!(!handle_mouse(
            &mut app,
            &view,
            mouse_at(
                MouseEventKind::Up(MouseButton::Left),
                grid.x + 1,
                grid.y,
                none
            )
        ));
        assert_eq!(app.drag, DragOrigin::None);
        assert!(
            wait_until(|| {
                draw_into(&mut terminal, &view, &mut app);
                let text: String = buffer_text(&terminal).split_whitespace().collect();
                text.contains("033[<0;1;1M")
            })
            .await,
            "the child never echoed the SGR press: {}",
            buffer_text(&terminal)
        );
        // A wheel notch is forwarded too (no redraw needed for that).
        assert!(!handle_mouse(
            &mut app,
            &view,
            mouse_at(MouseEventKind::ScrollUp, grid.x, grid.y, none)
        ));
        app.close_tab();
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn tab_chords_split_cycle_select_move_and_reset_the_stack() {
        let (mut app, dispatcher, mut commands) = test_app();
        let dir = tempfile::tempdir().unwrap();
        let here = dir.path().to_path_buf();
        let view = view_with(&[&here.to_string_lossy(), "/repo/other"]);
        let mut terminal = Terminal::new(TestBackend::new(100, 30)).unwrap();

        // Seed one tab, then draw so a terminal area exists for splits.
        let tab = scripted_tab(&app, "sleep 5", here.clone());
        install_tab(&mut app, tab);
        draw_into(&mut terminal, &view, &mut app);
        assert_eq!(app.panes.group_count(), 1);

        // alt-s splits into a second group; alt-↑/↓ move focus between them.
        app.tree.cursor = 1;
        handle_key(&mut app, &view, &dispatcher, alt('s')).await;
        assert_eq!(app.panes.group_count(), 2, "alt-s split the stack");
        assert_eq!(app.panes.focused, 1);
        draw_into(&mut terminal, &view, &mut app);
        handle_key(
            &mut app,
            &view,
            &dispatcher,
            alt_key(KeyCode::Up, KeyModifiers::NONE),
        )
        .await;
        assert_eq!(app.panes.focused, 0);
        handle_key(
            &mut app,
            &view,
            &dispatcher,
            alt_key(KeyCode::Down, KeyModifiers::NONE),
        )
        .await;
        assert_eq!(app.panes.focused, 1);

        // alt-⇧↑ moves the tab into the group above, emptying its own.
        handle_key(
            &mut app,
            &view,
            &dispatcher,
            alt_key(KeyCode::Up, KeyModifiers::SHIFT),
        )
        .await;
        assert_eq!(app.panes.group_count(), 1);
        assert_eq!(app.panes.groups[0].tabs.len(), 2);
        // With one group there is nowhere to move to, and it says so.
        handle_key(
            &mut app,
            &view,
            &dispatcher,
            alt_key(KeyCode::Down, KeyModifiers::SHIFT),
        )
        .await;
        assert!(app.notice.as_deref().unwrap_or("").contains("no group"));

        // alt-[ / alt-] cycle tabs, alt-1..9 select, out of range notices.
        assert_eq!(app.panes.groups[0].active, 1);
        handle_key(&mut app, &view, &dispatcher, alt(']')).await;
        assert_eq!(app.panes.groups[0].active, 0, "wraps");
        handle_key(&mut app, &view, &dispatcher, alt('[')).await;
        assert_eq!(app.panes.groups[0].active, 1);
        handle_key(&mut app, &view, &dispatcher, alt('1')).await;
        assert_eq!(app.panes.groups[0].active, 0);
        handle_key(&mut app, &view, &dispatcher, alt('9')).await;
        assert!(app.notice.as_deref().unwrap_or("").contains("no tab 9"));

        // alt-0 resets the weights.
        app.panes.weights = vec![7];
        handle_key(&mut app, &view, &dispatcher, alt('0')).await;
        assert_eq!(app.panes.weights, vec![1]);

        // Both tabs are on one worktree, so the cue only clears at the last
        // close — the ref-counted `here` rule.
        while let Ok(cmd) = commands.try_recv() {
            drop(cmd); // discard the opens
        }
        handle_key(&mut app, &view, &dispatcher, alt('w')).await;
        assert!(app.panes.any_alive(), "one tab left");
        assert!(
            commands.try_recv().is_err(),
            "the cue stays while a tab remains"
        );
        handle_key(&mut app, &view, &dispatcher, alt('w')).await;
        assert!(app.panes.is_empty());
        assert!(matches!(commands.try_recv(), Ok(HubCommand::ClearOpenTab(p)) if p == here));
        assert_eq!(app.focus, Focus::Tree);
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn a_split_is_refused_when_the_pane_is_too_short_to_draw_it() {
        let (mut app, dispatcher, _commands) = test_app();
        let dir = tempfile::tempdir().unwrap();
        let here = dir.path().to_path_buf();
        let view = view_with(&[&here.to_string_lossy()]);
        let tab = scripted_tab(&app, "sleep 5", here);
        install_tab(&mut app, tab);
        // Six rows of terminal cannot hold two four-row groups.
        let mut terminal = Terminal::new(TestBackend::new(100, 7)).unwrap();
        draw_into(&mut terminal, &view, &mut app);
        app.tree.cursor = 1;
        handle_key(&mut app, &view, &dispatcher, alt('s')).await;
        assert_eq!(app.panes.group_count(), 1, "the split was refused");
        assert!(app
            .notice
            .as_deref()
            .unwrap_or("")
            .contains("not enough height"));
        app.close_tab();
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn the_tab_strip_activates_closes_and_the_splitter_resizes() {
        let (mut app, _dispatcher, _commands) = test_app();
        let dir = tempfile::tempdir().unwrap();
        let here = dir.path().to_path_buf();
        let view = view_with(&[&here.to_string_lossy()]);
        let mut terminal = Terminal::new(TestBackend::new(100, 30)).unwrap();

        // Two tabs in one group, then a second group below.
        for _ in 0..2 {
            let tab = scripted_tab(&app, "sleep 5", here.clone());
            install_tab(&mut app, tab);
        }
        let tab = scripted_tab(&app, "sleep 5", here);
        app.panes.split(move |_| Ok(tab)).unwrap();
        draw_into(&mut terminal, &view, &mut app);
        assert_eq!(app.regions.groups.len(), 2);
        assert_eq!(app.regions.splitters.len(), 1);

        // Clicking tab 1 on the first strip activates it and focuses group 0.
        let strip = app.regions.groups[0].strip;
        let spans = app.regions.groups[0].tab_spans.clone();
        assert_eq!(spans.len(), 2, "two tabs on the strip");
        let none = KeyModifiers::NONE;
        assert!(handle_mouse(
            &mut app,
            &view,
            mouse_at(
                MouseEventKind::Down(MouseButton::Left),
                spans[0].0,
                strip.y,
                none
            )
        ));
        assert_eq!(app.panes.focused, 0);
        assert_eq!(app.panes.groups[0].active, 0);
        assert_eq!(app.focus, Focus::Terminal);

        // The wheel over a strip cycles that group's tabs.
        assert!(handle_mouse(
            &mut app,
            &view,
            mouse_at(MouseEventKind::ScrollDown, spans[0].0, strip.y, none)
        ));
        assert_eq!(app.panes.groups[0].active, 1);

        // Dragging the splitter up shrinks the first group; only the pair
        // either side changes, and it never goes below the minimum.
        let splitter = app.regions.splitters[0];
        let before = app.panes.weights.clone();
        // Pressing on a splitter changes nothing visible — it only arms the
        // drag — so it asks for no redraw.
        assert!(!handle_mouse(
            &mut app,
            &view,
            mouse_at(MouseEventKind::Down(MouseButton::Left), 60, splitter, none)
        ));
        assert_eq!(app.drag, DragOrigin::Splitter { index: 0 });
        assert!(handle_mouse(
            &mut app,
            &view,
            mouse_at(
                MouseEventKind::Drag(MouseButton::Left),
                60,
                splitter - 4,
                none
            )
        ));
        assert_ne!(app.panes.weights, before, "the drag moved the boundary");
        draw_into(&mut terminal, &view, &mut app);
        let rects = app.panes.arrange(app.terminal_area.unwrap());
        assert!(rects.iter().all(|r| r.body.height >= 3));
        handle_mouse(
            &mut app,
            &view,
            mouse_at(
                MouseEventKind::Up(MouseButton::Left),
                60,
                splitter - 4,
                none,
            ),
        );
        assert_eq!(app.drag, DragOrigin::None);

        // A middle click on a tab closes just that tab.
        draw_into(&mut terminal, &view, &mut app);
        let spans = app.regions.groups[0].tab_spans.clone();
        let strip_y = app.regions.groups[0].strip.y;
        let before = app.panes.groups[0].tabs.len();
        assert!(handle_mouse(
            &mut app,
            &view,
            mouse_at(
                MouseEventKind::Down(MouseButton::Middle),
                spans[0].0,
                strip_y,
                none
            )
        ));
        assert_eq!(app.panes.groups[0].tabs.len(), before - 1);

        shutdown_all(&mut app);
    }

    #[test]
    fn layout_gives_the_tree_the_full_width_until_a_tab_exists() {
        let area = Rect::new(0, 0, 100, 30);
        let without = layout(area, false);
        assert_eq!(without.tree.width, 100);
        assert!(without.terminal.is_none());
        assert_eq!(without.status.height, 1);

        let with = layout(area, true);
        let terminal = with.terminal.expect("a terminal pane");
        assert_eq!(with.tree.width + terminal.width, 100);
        assert!(terminal.width >= 20);
        assert_eq!(with.tree.height, 29);
    }
}