recursive-agent 0.6.0

A minimal, orthogonal, self-improving coding agent kernel in Rust
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
//! Keyboard dispatch, modal handlers, @file autocomplete, history search,
//! and slash-command execution.

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

use crate::tui::events::UserAction;

use super::{
    double_press_window, glob_workspace_files, search_history, App, InputMode, TranscriptBlock,
};

impl App {
    /// Process one key event. Returns an optional [`UserAction`] that
    /// the caller must forward to the backend worker.
    pub fn handle_key(&mut self, key: KeyEvent) -> Option<UserAction> {
        // ── Ctrl+C: highest priority, double-press promotes to exit
        // (Goal 147 §5). Modals + buffer + turn state all decide what
        // the *first* press does; the second press inside the window
        // always quits.
        if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('c') {
            return self.handle_ctrl_c();
        }

        // ── Goal-161: permission modal ───────────────────────────────
        // When a tool-permission request is pending, all keys go to the
        // permission dialog. Y/Enter allow, N/Esc deny.
        if self.pending_permission.is_some() {
            return self.handle_permission_key(key);
        }

        // ── Goal-202: plan-mode pre-confirmation ──────────────────────
        // When the agent has called `request_plan_mode`, y/Enter approve
        // and n/Esc reject — just like the plan approval banner.
        if self.plan_mode_request_pending {
            return self.handle_plan_mode_request_key(key);
        }

        // ── Modal stack ──────────────────────────────────────────────
        // Goal-146: when any modal is on the stack, it owns the key
        // events. Modals may produce UserActions (Goal-147 added the
        // PlanReview y/n/Esc paths that send ConfirmPlan / RejectPlan
        // to the backend).
        if !self.modals.is_empty() {
            return self.handle_modal_key_action(key);
        }

        // ── Ctrl+E: contextual ───────────────────────────────────────
        // When the input buffer is non-empty, Ctrl+E behaves as
        // "move to end-of-line" inside the input. When the buffer
        // is empty, Ctrl+E falls back to Goal-144's "expand the
        // most recent ToolResult" behaviour. This is the conflict
        // resolution the goal calls for in §10.
        if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('e') {
            if self.prompt.buffer.is_empty() {
                self.toggle_last_expandable();
            } else {
                self.prompt.move_end();
            }
            return None;
        }

        // ── Ctrl+A: line-start in the input box ──────────────────────
        if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('a') {
            self.prompt.move_home();
            return None;
        }

        // ── Ctrl+B / Ctrl+F / Ctrl+P / Ctrl+N: emacs-style cursor motion
        // ─────────────────────────────────────────────
        // The previous binding for B/F was "page-scroll the
        // transcript by 10 lines" as a fallback for terminals
        // without reliable PageUp/PageDown. macOS users on
        // iTerm2 / Terminal.app / WezTerm all deliver PageUp and
        // PageDown properly today, so we re-purpose B/F for the
        // emacs / readline convention (cursor left / right). P/N
        // are emacs previous-line / next-line. The transcript
        // scroll still works via PageUp/PageDown, Shift+↑/↓,
        // and the mouse wheel.
        if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('b') {
            self.prompt.move_left();
            return None;
        }
        if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('f') {
            self.prompt.move_right();
            return None;
        }
        if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('p') {
            self.prompt.move_prev_line();
            return None;
        }
        if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('n') {
            self.prompt.move_next_line();
            return None;
        }

        // ── Ctrl+R: history search (Goal 160) ────────────────────────
        // In Prompt mode, Ctrl+R enters HistorySearch. In
        // HistorySearch mode, a second Ctrl+R moves down one match
        // (bash-compatible). In other modes, it is a no-op.
        if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('r') {
            match self.prompt.mode {
                InputMode::Prompt => {
                    self.enter_history_search_mode();
                    return None;
                }
                InputMode::HistorySearch => {
                    // Cycle to next match.
                    if !self.hsearch_matches.is_empty() {
                        self.hsearch_selected =
                            (self.hsearch_selected + 1) % self.hsearch_matches.len();
                    }
                    return None;
                }
                _ => return None,
            }
        }

        // ── Shift+Tab: cycle modes ───────────────────────────────────
        if key.code == KeyCode::BackTab {
            self.prompt.mode = self.prompt.mode.cycle_next();
            return None;
        }

        // ── History-search navigation (Goal 160) ─────────────────────
        if self.prompt.mode == InputMode::HistorySearch {
            return self.handle_history_search_key(key);
        }

        // ── @file autocomplete navigation (Goal 158) ─────────────────
        // When in AtFile mode, route navigation keys to the file
        // completion popup before anything else.
        if self.prompt.mode == InputMode::AtFile {
            return self.handle_atfile_key(key);
        }

        // ── Command-menu navigation (Goal 146) ───────────────────────
        // Intercept Up/Down/Tab/Enter when the user is composing a
        // slash command so the popup behaves like an autocomplete
        // menu rather than scrolling the transcript / submitting.
        if self.prompt.mode == InputMode::Command {
            if let Some(action) = self.handle_command_menu_key(key) {
                return action;
            }
        }

        // ── Chat screen ──────────────────────────────────────────────
        match key.code {
            KeyCode::Enter
                if key.modifiers.contains(KeyModifiers::SHIFT)
                    || key.modifiers.contains(KeyModifiers::ALT)
                    || key.modifiers.contains(KeyModifiers::CONTROL) =>
            {
                // Shift+Enter / Alt+Enter / Ctrl+Enter all insert a
                // literal newline instead of submitting. macOS
                // Terminal.app often intercepts Option+Enter before
                // the app sees it, so we offer Ctrl+Enter as a
                // terminal-independent alternative.
                self.prompt.insert_char('\n');
                None
            }
            // Ctrl+J (emacs "line feed"): insert a newline, never
            // submit. Bound separately from `Enter` because
            // crossterm delivers Ctrl+J as a Char('j') keypress
            // with the CONTROL modifier set, not as KeyCode::Enter.
            KeyCode::Char('j') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                self.prompt.insert_char('\n');
                None
            }
            KeyCode::Enter => self.submit_prompt(),
            // Transcript scrolling — checked **before** history walk
            // because Shift+↑/↓ should win even when the buffer is
            // empty and history exists (otherwise the
            // `should_walk_history_*` guard would silently consume
            // the keypress for history navigation). Goal 150 follow-
            // up: user reported scroll keys still drove the input
            // box, root cause was this ordering.
            KeyCode::Up if key.modifiers.contains(KeyModifiers::SHIFT) => {
                self.scroll_offset = self.scroll_offset.saturating_add(1);
                None
            }
            KeyCode::Down if key.modifiers.contains(KeyModifiers::SHIFT) => {
                self.scroll_offset = self.scroll_offset.saturating_sub(1);
                None
            }
            KeyCode::PageUp => {
                self.scroll_offset = self.scroll_offset.saturating_add(10);
                None
            }
            KeyCode::PageDown => {
                self.scroll_offset = self.scroll_offset.saturating_sub(10);
                None
            }
            KeyCode::Up if self.should_walk_history_up() => {
                self.prompt.history_prev();
                None
            }
            KeyCode::Down if self.should_walk_history_down() => {
                self.prompt.history_next();
                None
            }
            KeyCode::Char('q') if self.prompt.buffer.is_empty() => {
                self.should_quit = true;
                None
            }
            KeyCode::Char(c) => {
                self.handle_char_input(c);
                None
            }
            KeyCode::Backspace => {
                if self.prompt.buffer.is_empty() && self.prompt.mode != InputMode::Prompt {
                    // Empty buffer in a non-Prompt mode: drop back to
                    // Prompt rather than no-op. This is how the user
                    // exits a mode they entered by accident.
                    self.prompt.mode = InputMode::Prompt;
                } else {
                    self.prompt.backspace();
                }
                None
            }
            KeyCode::Delete => {
                self.prompt.delete_forward();
                None
            }
            KeyCode::Left => {
                self.prompt.move_left();
                None
            }
            KeyCode::Right => {
                self.prompt.move_right();
                None
            }
            KeyCode::Home => {
                self.prompt.move_home();
                None
            }
            KeyCode::End => {
                self.prompt.move_end();
                None
            }
            KeyCode::Esc => self.handle_esc(),
            _ => None,
        }
    }

    /// Goal-147: dispatch the Esc key when no modal is active.
    ///
    /// Order of resolution:
    ///   1. Buffer non-empty → clear it and reset to Prompt mode.
    ///   2. A turn is running → emit `UserAction::Interrupt`, push a
    ///      System block, and start the double-press window.
    ///   3. Otherwise → no-op. **Esc never quits** from the chat
    ///      screen (Goal 147). Quitting is owned by `Ctrl+C×2`,
    ///      `Ctrl+D`, `/exit`, or `q` inside a modal.
    ///
    /// The double-press window is tracked but unused for Esc — Esc
    /// has no escalation path; we update the timestamp anyway so
    /// future enhancements can read it without re-plumbing.
    fn handle_esc(&mut self) -> Option<UserAction> {
        use std::time::Instant;

        let now = Instant::now();
        let _within_window = self
            .double_press
            .last_esc_at
            .map(|t| now.duration_since(t) <= double_press_window())
            .unwrap_or(false);
        self.double_press.last_esc_at = Some(now);

        // Step 1: non-empty buffer or non-Prompt mode → clear.
        if !self.prompt.buffer.is_empty() || self.prompt.mode != InputMode::Prompt {
            self.prompt.buffer.clear();
            self.prompt.cursor = 0;
            self.prompt.mode = InputMode::Prompt;
            self.prompt.history_idx = None;
            return None;
        }

        // Step 2: in-flight turn → interrupt.
        if self.turn.running {
            self.push_system("Interrupting… (press Ctrl+C again to exit)");
            return Some(UserAction::Interrupt);
        }

        // Step 3: idle and empty — explicitly no-op (do **not** quit).
        None
    }

    /// Goal-147: dispatch Ctrl+C with double-press semantics.
    ///
    /// Order of resolution:
    ///   1. Two presses inside [`double_press_window`] → real exit.
    ///   2. Modal active → pop the topmost modal (single-press path).
    ///   3. Buffer non-empty → clear it.
    ///   4. Turn running → `UserAction::Interrupt` + System block.
    ///   5. Idle and empty → arm the "press again to exit" hint.
    fn handle_ctrl_c(&mut self) -> Option<UserAction> {
        use std::time::Instant;

        let now = Instant::now();
        let within_window = self
            .double_press
            .last_ctrl_c_at
            .map(|t| now.duration_since(t) <= double_press_window())
            .unwrap_or(false);

        if within_window {
            // Second press inside the window → exit.
            self.should_quit = true;
            self.double_press.last_ctrl_c_at = None;
            return None;
        }

        self.double_press.last_ctrl_c_at = Some(now);

        // Step 2: pop a modal.
        if !self.modals.is_empty() {
            self.modals.pop();
            return None;
        }

        // Step 3: clear buffer.
        if !self.prompt.buffer.is_empty() || self.prompt.mode != InputMode::Prompt {
            self.prompt.buffer.clear();
            self.prompt.cursor = 0;
            self.prompt.mode = InputMode::Prompt;
            self.prompt.history_idx = None;
            return None;
        }

        // Step 4: interrupt the running turn.
        if self.turn.running {
            self.push_system("Interrupting… (press Ctrl+C again to exit)");
            return Some(UserAction::Interrupt);
        }

        // Step 5: idle, empty → arm the second press.
        self.push_system("Press Ctrl+C again to exit");
        None
    }

    /// History walk on Up should fire when (a) we are already
    /// walking (history_idx is Some) — so consecutive ↑ keep
    /// stepping back — or (b) the buffer is empty (entry point per
    /// goal §5).
    fn should_walk_history_up(&self) -> bool {
        if self.prompt.history.is_empty() {
            return false;
        }
        self.prompt.history_idx.is_some() || self.prompt.buffer.is_empty()
    }

    fn should_walk_history_down(&self) -> bool {
        self.prompt.history_idx.is_some()
    }

    fn handle_char_input(&mut self, c: char) {
        // Auto-detect mode from the first character when the buffer
        // is empty. The prefix character itself is consumed (used as
        // the mode marker, not stored).
        if self.prompt.buffer.is_empty() && self.prompt.mode == InputMode::Prompt {
            match c {
                '!' => {
                    self.prompt.mode = InputMode::Bash;
                    return;
                }
                '#' => {
                    self.prompt.mode = InputMode::Note;
                    return;
                }
                '/' => {
                    self.prompt.mode = InputMode::Command;
                    return;
                }
                _ => {}
            }
        }
        // Goal-158: `@` anywhere in Prompt mode triggers AtFile
        // completion. The `@` itself IS inserted into the buffer so
        // the user can see their typing; the query starts empty.
        if c == '@' && self.prompt.mode == InputMode::Prompt {
            self.prompt.insert_char('@');
            self.enter_atfile_mode();
            return;
        }
        self.prompt.insert_char(c);
    }

    /// Dispatch the current buffer based on the active mode. Returns
    /// the [`UserAction`] (if any) the caller must forward to the
    /// backend worker. Always resets the prompt to a clean state.
    fn submit_prompt(&mut self) -> Option<UserAction> {
        if self.prompt.buffer.is_empty() {
            // Don't submit empty prompts. Stay where we are — but if
            // the user is in a non-Prompt mode with nothing typed, do
            // nothing rather than spamming a no-op System block.
            return None;
        }
        let mode = self.prompt.mode;
        let body = self.prompt.buffer.clone();
        let prefixed = format!("{}{}", mode.history_prefix(), body);

        let action = match mode {
            InputMode::Prompt => {
                self.blocks
                    .push(TranscriptBlock::User { text: body.clone() });
                self.scroll_to_bottom();
                self.start_turn();
                Some(UserAction::SendMessage(body))
            }
            InputMode::Bash => {
                self.blocks.push(TranscriptBlock::User {
                    text: format!("!{body}"),
                });
                self.scroll_to_bottom();
                Some(UserAction::RunShell(body))
            }
            InputMode::Note => {
                self.blocks.push(TranscriptBlock::System {
                    text: format!("# {body}"),
                });
                self.scroll_to_bottom();
                None
            }
            InputMode::Command => self.dispatch_slash_command(&body),
            // AtFile mode is handled before submit_prompt is reached
            // (handle_atfile_key intercepts Enter). Treat as Prompt if
            // somehow reached here.
            InputMode::AtFile => {
                self.exit_atfile_mode();
                self.blocks
                    .push(TranscriptBlock::User { text: body.clone() });
                self.scroll_to_bottom();
                self.start_turn();
                Some(UserAction::SendMessage(body))
            }
            // HistorySearch intercepts Enter before submit_prompt.
            // Treat defensively as Prompt.
            InputMode::HistorySearch => {
                self.exit_history_search_mode();
                self.blocks
                    .push(TranscriptBlock::User { text: body.clone() });
                self.scroll_to_bottom();
                self.start_turn();
                Some(UserAction::SendMessage(body))
            }
        };

        self.prompt.record_submission(prefixed);
        self.command_menu_selected = None;
        action
    }

    /// Parse `body` (without the leading `/`) as `name + args`, look
    /// it up in [`App::commands`], and run the handler. Returns an
    /// optional [`UserAction`] for the dispatcher.
    fn dispatch_slash_command(&mut self, body: &str) -> Option<UserAction> {
        use crate::tui::commands::{CommandHandler, CommandOutcome};

        let mut parts = body.split_whitespace();
        let name = parts.next().unwrap_or("");
        let args: Vec<String> = parts.map(String::from).collect();

        // Clone the registry to avoid borrowing self while invoking
        // the handler (which takes &mut self).
        let registry = self.commands.clone();

        // Goal-169: check built-in commands first, then skill commands.
        if let Some(spec) = registry.lookup(name) {
            return match &spec.handler {
                CommandHandler::Sync(f) => {
                    match f(self, &args) {
                        CommandOutcome::Done => {}
                        CommandOutcome::Error(msg) => self.push_error(msg),
                        CommandOutcome::OpenModal(modal) => self.push_modal(modal),
                    }
                    None
                }
                CommandHandler::Async(f) => {
                    let actions = f(self, &args);
                    // The dispatcher only carries one UserAction back to
                    // the caller; queue the rest into App for later. In
                    // practice every async command returns 0 or 1 actions
                    // today.
                    actions.into_iter().next()
                }
            };
        }

        // Goal-169: skill command fallback.
        if let Some(skill) = registry.lookup_skill(name) {
            let args_str = args.join(" ");
            let prompt = skill.expand(&args_str);
            self.push_system(format!(
                "Running skill /{}: {}",
                skill.name, skill.description
            ));
            self.blocks.push(TranscriptBlock::User {
                text: prompt.clone(),
            });
            self.scroll_to_bottom();
            self.start_turn();
            return Some(UserAction::RunSkillPrompt { prompt });
        }

        self.push_error(format!("Unknown command: /{name}. Try /help."));
        None
    }

    // ── Goal-146: command-menu ────────────────────────────────────────

    /// Handle a key in command-completion-menu context. Returns
    /// `Some(action)` (with `action` itself optional) if the key was
    /// consumed; the outer `None` means "fall through to the regular
    /// chat key path".
    pub fn handle_command_menu_key(&mut self, key: KeyEvent) -> Option<Option<UserAction>> {
        use crate::tui::ui::command_menu;
        let matches_count = self.commands.search(&self.prompt.buffer).len();

        match key.code {
            KeyCode::Up => {
                match self.command_menu_selected {
                    None => return None,
                    Some(0) => self.command_menu_selected = None,
                    Some(n) => self.command_menu_selected = Some(n - 1),
                }
                Some(None)
            }
            KeyCode::Down => {
                if matches_count == 0 {
                    return None;
                }
                let next = match self.command_menu_selected {
                    None => 0,
                    Some(n) if n + 1 < matches_count.min(command_menu::MAX_VISIBLE) => n + 1,
                    Some(n) => n,
                };
                self.command_menu_selected = Some(next);
                Some(None)
            }
            KeyCode::Tab => {
                let registry = self.commands.clone();
                let matches = registry.search(&self.prompt.buffer);
                if let Some(target) =
                    command_menu::tab_completion_target(&self.prompt.buffer, &matches)
                {
                    self.prompt.buffer = target;
                    self.prompt.cursor = self.prompt.buffer.len();
                    self.command_menu_selected = None;
                }
                Some(None)
            }
            KeyCode::Enter => {
                // If a menu item is selected, execute it; otherwise
                // fall through to the regular submit path so the
                // user's literal buffer is dispatched.
                if let Some(idx) = self.command_menu_selected {
                    let registry = self.commands.clone();
                    let matches = registry.search(&self.prompt.buffer);
                    if let Some(spec) = matches.get(idx) {
                        let chosen = spec.name.to_string();
                        self.prompt.buffer = chosen;
                        self.prompt.cursor = self.prompt.buffer.len();
                    }
                    self.command_menu_selected = None;
                }
                None
            }
            _ => None,
        }
    }

    // ── Goal-158: @file completion helpers ───────────────────────────

    /// Switch to AtFile mode and populate the initial suggestion list.
    fn enter_atfile_mode(&mut self) {
        self.prompt.mode = InputMode::AtFile;
        self.atfile_query.clear();
        self.atfile_selected = None;
        self.atfile_suggestions = glob_workspace_files("");
    }

    /// Recompute [`App::atfile_suggestions`] from [`App::atfile_query`].
    fn refresh_atfile_suggestions(&mut self) {
        self.atfile_suggestions = glob_workspace_files(&self.atfile_query);
        // Clamp selection so it doesn't point past the new list.
        if let Some(sel) = self.atfile_selected {
            if sel >= self.atfile_suggestions.len() {
                self.atfile_selected = if self.atfile_suggestions.is_empty() {
                    None
                } else {
                    Some(self.atfile_suggestions.len() - 1)
                };
            }
        }
    }

    /// Insert the selected (or first) suggestion into the buffer,
    /// replacing the `@<query>` tail that was typed.
    fn commit_atfile_selection(&mut self) {
        let idx = self.atfile_selected.unwrap_or(0);
        let Some(chosen) = self.atfile_suggestions.get(idx).cloned() else {
            self.exit_atfile_mode();
            return;
        };
        // Replace the `@<query>` suffix in the buffer with `@<chosen>`.
        let at_pos = self
            .prompt
            .buffer
            .rfind('@')
            .unwrap_or(self.prompt.buffer.len());
        self.prompt.buffer.truncate(at_pos);
        self.prompt.buffer.push('@');
        self.prompt.buffer.push_str(&chosen);
        self.prompt.cursor = self.prompt.buffer.len();
        self.exit_atfile_mode();
    }

    /// Return to Prompt mode and clear completion state.
    fn exit_atfile_mode(&mut self) {
        self.prompt.mode = InputMode::Prompt;
        self.atfile_query.clear();
        self.atfile_suggestions.clear();
        self.atfile_selected = None;
    }

    /// Handle a key when [`InputMode::AtFile`] is active.
    pub fn handle_atfile_key(&mut self, key: KeyEvent) -> Option<UserAction> {
        match key.code {
            KeyCode::Esc => {
                // Cancel: exit AtFile mode, keep `@<query>` in buffer.
                self.exit_atfile_mode();
                None
            }
            KeyCode::Enter | KeyCode::Tab => {
                self.commit_atfile_selection();
                None
            }
            KeyCode::Up => {
                match self.atfile_selected {
                    None => {}
                    Some(0) => self.atfile_selected = None,
                    Some(n) => self.atfile_selected = Some(n - 1),
                }
                None
            }
            KeyCode::Down => {
                let count = self.atfile_suggestions.len();
                if count == 0 {
                    return None;
                }
                let next = match self.atfile_selected {
                    None => 0,
                    Some(n) if n + 1 < count => n + 1,
                    Some(n) => n,
                };
                self.atfile_selected = Some(next);
                None
            }
            KeyCode::Backspace => {
                if self.atfile_query.is_empty() {
                    // Delete the `@` from the buffer and exit AtFile mode.
                    self.exit_atfile_mode();
                    self.prompt.backspace(); // removes `@`
                } else {
                    // Delete last char from query and buffer.
                    let last_len = self
                        .atfile_query
                        .chars()
                        .last()
                        .map(|c| c.len_utf8())
                        .unwrap_or(0);
                    let new_len = self.atfile_query.len() - last_len;
                    self.atfile_query.truncate(new_len);
                    self.prompt.backspace();
                    self.refresh_atfile_suggestions();
                }
                None
            }
            KeyCode::Char(c) => {
                self.atfile_query.push(c);
                self.prompt.insert_char(c);
                self.refresh_atfile_suggestions();
                None
            }
            _ => None,
        }
    }

    // ── Goal-160: Ctrl+R history search ───────────────────────────────

    /// Enter HistorySearch mode, clearing the search query and
    /// pre-populating matches with all history entries (most recent first).
    fn enter_history_search_mode(&mut self) {
        self.prompt.mode = InputMode::HistorySearch;
        self.hsearch_query.clear();
        self.hsearch_selected = 0;
        self.hsearch_matches = search_history(&self.prompt.history, "");
    }

    /// Refresh [`App::hsearch_matches`] from [`App::hsearch_query`].
    fn refresh_hsearch_matches(&mut self) {
        self.hsearch_matches = search_history(&self.prompt.history, &self.hsearch_query);
        if self.hsearch_selected >= self.hsearch_matches.len().max(1) {
            self.hsearch_selected = 0;
        }
    }

    /// Fill the prompt buffer with the currently selected history entry
    /// and return to Prompt mode.
    fn commit_history_selection(&mut self) {
        if let Some(&hist_idx) = self.hsearch_matches.get(self.hsearch_selected) {
            if let Some(entry) = self.prompt.history.get(hist_idx) {
                self.prompt.buffer = entry.clone();
                self.prompt.cursor = self.prompt.buffer.len();
            }
        }
        self.exit_history_search_mode();
    }

    /// Return to Prompt mode and clear search state.
    fn exit_history_search_mode(&mut self) {
        self.prompt.mode = InputMode::Prompt;
        self.hsearch_query.clear();
        self.hsearch_matches.clear();
        self.hsearch_selected = 0;
    }

    /// Handle a key when [`InputMode::HistorySearch`] is active.
    pub fn handle_history_search_key(&mut self, key: KeyEvent) -> Option<UserAction> {
        match key.code {
            KeyCode::Esc => {
                self.exit_history_search_mode();
                None
            }
            KeyCode::Enter => {
                self.commit_history_selection();
                None
            }
            KeyCode::Up => {
                if !self.hsearch_matches.is_empty() && self.hsearch_selected > 0 {
                    self.hsearch_selected -= 1;
                }
                None
            }
            KeyCode::Down => {
                if !self.hsearch_matches.is_empty()
                    && self.hsearch_selected + 1 < self.hsearch_matches.len()
                {
                    self.hsearch_selected += 1;
                }
                None
            }
            KeyCode::Backspace => {
                if self.hsearch_query.is_empty() {
                    self.exit_history_search_mode();
                } else {
                    let last_len = self
                        .hsearch_query
                        .chars()
                        .last()
                        .map(|c| c.len_utf8())
                        .unwrap_or(0);
                    let new_len = self.hsearch_query.len() - last_len;
                    self.hsearch_query.truncate(new_len);
                    self.refresh_hsearch_matches();
                }
                None
            }
            KeyCode::Char(c) => {
                self.hsearch_query.push(c);
                self.refresh_hsearch_matches();
                None
            }
            _ => None,
        }
    }

    // ── Goal-161: permission modal ────────────────────────────────────

    /// Handle a key while a permission modal is active.
    /// - `y` / `Y` / `Enter` → allow once
    /// - `n` / `N` / `Esc`   → deny
    /// - `a` / `A`           → allow + add tool to auto-allow list
    pub fn handle_permission_key(&mut self, key: KeyEvent) -> Option<UserAction> {
        let (allow, auto_allow) = match key.code {
            KeyCode::Char('y') | KeyCode::Char('Y') | KeyCode::Enter => (true, false),
            KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => (false, false),
            KeyCode::Char('a') | KeyCode::Char('A') => (true, true),
            _ => return None,
        };
        if let Some(p) = self.pending_permission.take() {
            if auto_allow {
                self.auto_allowed_tools.insert(p.tool_name.clone());
            }
            let _ = p.reply.send(allow);
        }
        None
    }

    // ── Modal dispatch ────────────────────────────────────────────────

    /// Handle a key event when at least one modal is on the stack.
    /// Returns `Some(action)` if the modal layer wants to forward a
    /// [`UserAction`] to the backend (currently only the PlanReview
    /// modal does this). The outer key dispatcher should not also
    /// process this key against the chat layer.
    pub fn handle_modal_key_action(&mut self, key: KeyEvent) -> Option<UserAction> {
        use crate::tui::ui::modal::Modal;

        // Goal-147: PlanReview modal owns y / n / e / Enter / Esc and
        // *bypasses* the generic confirm logic.
        if let Some(Modal::PlanReview { .. }) = self.modals.last() {
            return self.handle_plan_review_key(key);
        }

        // Goal-171: ResumePicker owns ↑/↓/Enter/Esc and may return a UserAction.
        if let Some(Modal::ResumePicker { .. }) = self.modals.last() {
            return self.handle_resume_picker_key(key);
        }

        // Goal-173: McpServers owns ↑/↓/Esc.
        if let Some(Modal::McpServers { .. }) = self.modals.last() {
            return self.handle_mcp_servers_key(key);
        }

        // Generic modal dispatch (Goal 146).
        self.handle_modal_key(key);
        None
    }

    /// Goal-147: dispatch a key against an active `Modal::PlanReview`.
    ///
    /// * `y` / `Enter` → emit `UserAction::ConfirmPlan`. The modal is
    ///   **not** popped here — we wait for the runtime's
    ///   `PlanConfirmed` event so the visible state matches the
    ///   server-side decision.
    /// * `n` / `Esc` → pop the modal immediately and emit
    ///   `UserAction::RejectPlan("user rejected")`. Goal §8 forbids
    ///   collecting a free-form reason here.
    /// * `e` → copy the plan text into the prompt buffer (Prompt
    ///   mode), close the modal, and let the user edit/resend
    ///   normally.
    /// * Any other key is consumed but ignored, keeping plan-mode
    ///   focus.
    fn handle_plan_review_key(&mut self, key: KeyEvent) -> Option<UserAction> {
        use crate::tui::ui::modal::Modal;

        match key.code {
            KeyCode::Char('y') | KeyCode::Enter => {
                // Optimistic close: pop the modal immediately so the user
                // sees the dismissal without waiting for the PlanConfirmed
                // event to round-trip from the runtime.
                self.modals.pop();
                Some(UserAction::ConfirmPlan)
            }
            KeyCode::Char('n') | KeyCode::Esc => {
                self.modals.pop();
                Some(UserAction::RejectPlan("user rejected".into()))
            }
            KeyCode::Char('e') => {
                if let Some(Modal::PlanReview { plan_text, .. }) = self.modals.last().cloned() {
                    self.set_input(plan_text);
                }
                self.modals.pop();
                None
            }
            _ => None,
        }
    }

    /// Goal-202: dispatch a key when `plan_mode_request_pending` is set.
    ///
    /// * `y` / `Enter` → approve — optimistically clears the pending flag
    ///   and emits `UserAction::ApprovePlanMode`.
    /// * `n` / `Esc` → reject — clears the flag and emits
    ///   `UserAction::RejectPlanMode("user skipped")`.
    /// * Any other key is consumed (request focus kept).
    fn handle_plan_mode_request_key(&mut self, key: KeyEvent) -> Option<UserAction> {
        match key.code {
            KeyCode::Char('y') | KeyCode::Enter => {
                self.plan_mode_request_pending = false;
                Some(UserAction::ApprovePlanMode)
            }
            KeyCode::Char('n') | KeyCode::Esc => {
                self.plan_mode_request_pending = false;
                Some(UserAction::RejectPlanMode("user skipped".into()))
            }
            _ => None,
        }
    }

    /// Goal-171: dispatch a key against an active `Modal::ResumePicker`.
    fn handle_resume_picker_key(&mut self, key: KeyEvent) -> Option<UserAction> {
        use crate::tui::ui::modal::Modal;
        match key.code {
            KeyCode::Esc | KeyCode::Char('q') => {
                self.modals.pop();
                None
            }
            KeyCode::Up => {
                let mut new_sel: Option<usize> = None;
                if let Some(Modal::ResumePicker { selected, .. }) = self.modals.last_mut() {
                    if *selected > 0 {
                        *selected -= 1;
                    }
                    new_sel = Some(*selected);
                }
                if let Some(sel) = new_sel {
                    self.modal_scroll_follow_selection(sel);
                }
                None
            }
            KeyCode::Down => {
                let mut new_sel: Option<usize> = None;
                if let Some(Modal::ResumePicker { entries, selected }) = self.modals.last_mut() {
                    if *selected + 1 < entries.len() {
                        *selected += 1;
                    }
                    new_sel = Some(*selected);
                }
                if let Some(sel) = new_sel {
                    self.modal_scroll_follow_selection(sel);
                }
                None
            }
            KeyCode::Enter => {
                if let Some(Modal::ResumePicker { entries, selected }) = self.modals.last() {
                    if let Some(entry) = entries.get(*selected) {
                        let session_dir = entry.session_dir.clone();
                        self.modals.pop();
                        return Some(UserAction::ResumeSession { session_dir });
                    }
                }
                self.modals.pop();
                None
            }
            _ => None,
        }
    }

    /// Goal-173: dispatch a key against an active `Modal::McpServers`.
    fn handle_mcp_servers_key(&mut self, key: KeyEvent) -> Option<UserAction> {
        use crate::tui::ui::modal::Modal;
        match key.code {
            KeyCode::Esc | KeyCode::Char('q') => {
                self.modals.pop();
                None
            }
            KeyCode::Up => {
                let mut new_sel: Option<usize> = None;
                if let Some(Modal::McpServers { selected, .. }) = self.modals.last_mut() {
                    if *selected > 0 {
                        *selected -= 1;
                    }
                    new_sel = Some(*selected);
                }
                if let Some(sel) = new_sel {
                    self.modal_scroll_follow_selection(sel);
                }
                None
            }
            KeyCode::Down => {
                let mut new_sel: Option<usize> = None;
                if let Some(Modal::McpServers { entries, selected }) = self.modals.last_mut() {
                    if *selected + 1 < entries.len() {
                        *selected += 1;
                    }
                    new_sel = Some(*selected);
                }
                if let Some(sel) = new_sel {
                    self.modal_scroll_follow_selection(sel);
                }
                None
            }
            _ => None,
        }
    }

    /// Handle a key event when at least one modal is on the stack.
    /// Returns `true` if the key was consumed by the modal layer
    /// (so the caller should skip the chat key path).
    pub fn handle_modal_key(&mut self, key: KeyEvent) -> bool {
        use crate::tui::ui::modal::{ConfirmAction, Modal};
        if self.modals.is_empty() {
            return false;
        }
        match key.code {
            KeyCode::Esc | KeyCode::Char('q') => {
                self.modals.pop();
            }
            KeyCode::Char('y') => {
                if let Some(Modal::Confirm { on_yes, .. }) = self.modals.last().cloned() {
                    self.modals.pop();
                    match on_yes {
                        ConfirmAction::Exit => {
                            self.should_quit = true;
                        }
                        ConfirmAction::Clear => {
                            self.reset_transcript();
                        }
                    }
                }
            }
            KeyCode::Char('n') => {
                if matches!(self.modals.last(), Some(Modal::Confirm { .. })) {
                    self.modals.pop();
                }
            }
            KeyCode::Enter => {
                if let Some(Modal::Confirm { on_yes, .. }) = self.modals.last().cloned() {
                    self.modals.pop();
                    match on_yes {
                        ConfirmAction::Exit => self.should_quit = true,
                        ConfirmAction::Clear => self.reset_transcript(),
                    }
                } else {
                    // Enter on non-confirm modals just dismisses.
                    self.modals.pop();
                }
            }
            KeyCode::Up | KeyCode::PageUp => {
                let step: u16 = if key.code == KeyCode::PageUp { 10 } else { 1 };
                // Journal: move selection up and auto-scroll to keep it visible.
                let mut journal_new_sel: Option<usize> = None;
                if let Some(Modal::Journal { selected, .. }) = self.modals.last_mut() {
                    if *selected > 0 {
                        *selected -= 1;
                    }
                    journal_new_sel = Some(*selected);
                }
                if let Some(sel) = journal_new_sel {
                    self.modal_scroll_follow_selection(sel);
                } else {
                    // Generic text scroll (Help, ToolList, PlanReview, …).
                    self.modal_scroll = self.modal_scroll.saturating_sub(step);
                }
            }
            KeyCode::Down | KeyCode::PageDown => {
                let step: u16 = if key.code == KeyCode::PageDown { 10 } else { 1 };
                // Journal: move selection down and auto-scroll to keep it visible.
                let mut journal_new_sel: Option<usize> = None;
                if let Some(Modal::Journal { entries, selected }) = self.modals.last_mut() {
                    if *selected + 1 < entries.len() {
                        *selected += 1;
                    }
                    journal_new_sel = Some(*selected);
                }
                if let Some(sel) = journal_new_sel {
                    self.modal_scroll_follow_selection(sel);
                } else {
                    // Generic text scroll (Help, ToolList, PlanReview, …).
                    self.modal_scroll = self.modal_scroll.saturating_add(step);
                }
            }
            _ => {}
        }
        true
    }

    /// Approximate number of visible content rows inside the expanded modal
    /// (40-row viewport × 90% height − 2 border − 3 header lines).
    const MODAL_LIST_VISIBLE: u16 = 28;

    /// Auto-adjust `modal_scroll` so that the item at position `selected`
    /// (0-based) is always within the visible window of a list modal.
    /// Accounts for the 2-line header (title + blank) above the list.
    fn modal_scroll_follow_selection(&mut self, selected: usize) {
        let row = selected as u16 + 2; // +2 for header lines
        if row < self.modal_scroll {
            self.modal_scroll = row.saturating_sub(1);
        } else if row + 1 > self.modal_scroll + Self::MODAL_LIST_VISIBLE {
            self.modal_scroll = row + 1 - Self::MODAL_LIST_VISIBLE;
        }
    }
}

// ──────────────────────────────────────────────────────────────────────
// Tests
// ──────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use std::time::Duration;

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

    use crate::tui::app::{App, AppScreen, InputMode, ToolResultData, TranscriptBlock};
    use crate::tui::events::{UiEvent, UserAction};

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

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

    fn shift(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::SHIFT)
    }

    // ── Ctrl+E ─────────────────────────────────────────────────────

    #[test]
    fn ctrl_e_toggles_expanded_on_last_tool_result() {
        let mut app = App::new();
        app.screen = AppScreen::Chat;
        // No prior ToolCall — the ToolResult handler falls back to
        // synthesising a ToolCall block with Some(result). The test
        // still drives the toggle path.
        app.handle_ui_event(UiEvent::ToolResult {
            id: "1".into(),
            name: "read_file".into(),
            output: "long output".into(),
            success: true,
        });
        let _ = app.handle_key(ctrl('e'));
        match app.blocks.last() {
            Some(TranscriptBlock::ToolCall {
                result: Some(ToolResultData { expanded, .. }),
                ..
            }) => assert!(*expanded),
            other => panic!("expected ToolCall with Some(result), got {other:?}"),
        }
        let _ = app.handle_key(ctrl('e'));
        match app.blocks.last() {
            Some(TranscriptBlock::ToolCall {
                result: Some(ToolResultData { expanded, .. }),
                ..
            }) => assert!(!*expanded),
            other => panic!("expected ToolCall with Some(result), got {other:?}"),
        }
    }

    // ── chat key handling ──────────────────────────────────────────

    #[test]
    fn enter_moves_input_to_blocks() {
        let mut app = App::new();
        app.screen = AppScreen::Chat;
        app.set_input("hello");
        let action = app.handle_key(key(KeyCode::Enter));
        assert!(app.input().is_empty());
        assert!(app
            .blocks
            .iter()
            .any(|b| matches!(b, TranscriptBlock::User { text } if text == "hello")));
        assert!(matches!(action, Some(UserAction::SendMessage(s)) if s == "hello"));
    }

    #[test]
    fn enter_starts_a_turn() {
        let mut app = App::new();
        app.screen = AppScreen::Chat;
        app.set_input("hi");
        let _ = app.handle_key(key(KeyCode::Enter));
        assert!(app.turn.running);
        assert_eq!(app.turn_count, 1);
    }

    #[test]
    fn esc_clears_buffer_without_quitting() {
        let mut app = App::new();
        app.screen = AppScreen::Chat;
        app.set_input("partial");
        let _ = app.handle_key(key(KeyCode::Esc));
        assert!(!app.should_quit);
        assert!(app.input().is_empty());
    }

    #[test]
    fn char_appends_to_input() {
        let mut app = App::new();
        app.screen = AppScreen::Chat;
        let _ = app.handle_key(key(KeyCode::Char('h')));
        let _ = app.handle_key(key(KeyCode::Char('i')));
        assert_eq!(app.input(), "hi");
    }

    #[test]
    fn backspace_removes_last_char() {
        let mut app = App::new();
        app.screen = AppScreen::Chat;
        app.set_input("hello");
        let _ = app.handle_key(key(KeyCode::Backspace));
        assert_eq!(app.input(), "hell");
    }

    /// Plain ↑ never scrolls — even with empty buffer it walks
    /// history once any has been recorded; with no history it's a
    /// no-op. Transcript scrolling is reserved for Shift+↑/↓ and
    /// PgUp/PgDn (Goal 150 fix: history was always shadowing
    /// scroll, leaving the transcript stuck at bottom).
    #[test]
    fn plain_up_does_not_scroll_transcript() {
        let mut app = App::new();
        app.screen = AppScreen::Chat;
        for i in 0..30 {
            app.blocks.push(TranscriptBlock::System {
                text: format!("msg {i}"),
            });
        }
        let _ = app.handle_key(key(KeyCode::Up));
        assert_eq!(app.scroll_offset, 0);
        let _ = app.handle_key(key(KeyCode::Down));
        assert_eq!(app.scroll_offset, 0);
    }

    #[test]
    fn shift_up_increases_scroll_offset() {
        let mut app = App::new();
        app.screen = AppScreen::Chat;
        for i in 0..30 {
            app.blocks.push(TranscriptBlock::System {
                text: format!("msg {i}"),
            });
        }
        let _ = app.handle_key(shift(KeyCode::Up));
        assert_eq!(app.scroll_offset, 1);
        let _ = app.handle_key(shift(KeyCode::Up));
        assert_eq!(app.scroll_offset, 2);
    }

    #[test]
    fn shift_down_stops_at_zero() {
        let mut app = App::new();
        app.screen = AppScreen::Chat;
        app.scroll_offset = 2;
        let _ = app.handle_key(shift(KeyCode::Down));
        let _ = app.handle_key(shift(KeyCode::Down));
        let _ = app.handle_key(shift(KeyCode::Down));
        assert_eq!(app.scroll_offset, 0);
    }

    #[test]
    fn page_up_scrolls_by_ten() {
        let mut app = App::new();
        app.screen = AppScreen::Chat;
        let _ = app.handle_key(key(KeyCode::PageUp));
        assert_eq!(app.scroll_offset, 10);
    }

    #[test]
    fn page_down_scrolls_by_ten() {
        let mut app = App::new();
        app.screen = AppScreen::Chat;
        app.scroll_offset = 15;
        let _ = app.handle_key(key(KeyCode::PageDown));
        assert_eq!(app.scroll_offset, 5);
    }

    /// PgUp/PgDn now work regardless of buffer state.
    #[test]
    fn page_up_scrolls_even_when_buffer_not_empty() {
        let mut app = App::new();
        app.screen = AppScreen::Chat;
        app.set_input("typing");
        let _ = app.handle_key(key(KeyCode::PageUp));
        assert_eq!(app.scroll_offset, 10);
    }

    /// Goal 150 follow-up: terminal-independent scroll fallbacks
    /// were once provided by Ctrl+B / Ctrl+F. After switching to
    /// emacs-style cursor motion (the macOS Terminal crowd asked
    /// for B/F as left/right arrows, and modern terminals all
    /// deliver PageUp/PageDown reliably), the transcript scroll
    /// path now lives on `PageUp` / `PageDown` / `Shift+↑↓` /
    /// mouse wheel — covered by the tests in `keymap.rs` under
    /// `dispatch_ctrl_b_moves_cursor_left` and friends. The
    /// two tests that used to live here asserted the old scroll
    /// behaviour and are intentionally removed.

    // ── Plan Mode (Goal 147) ───────────────────────────────────────

    #[test]
    fn plan_review_y_dispatches_confirm_plan_action() {
        use crate::tui::ui::modal::Modal;
        let mut app = App::new();
        app.screen = AppScreen::Chat;
        app.modals.push(Modal::PlanReview {
            plan_text: "do".into(),
            tool_calls: vec![],
            edited_text: None,
        });
        let action = app.handle_key(key(KeyCode::Char('y')));
        assert!(matches!(action, Some(UserAction::ConfirmPlan)));
        // Fix-E: the modal is now optimistically closed on 'y'.
        assert!(app.modals.is_empty());
    }

    #[test]
    fn plan_review_n_dispatches_reject_plan_action() {
        use crate::tui::ui::modal::Modal;
        let mut app = App::new();
        app.screen = AppScreen::Chat;
        app.modals.push(Modal::PlanReview {
            plan_text: "do".into(),
            tool_calls: vec![],
            edited_text: None,
        });
        let action = app.handle_key(key(KeyCode::Char('n')));
        match action {
            Some(UserAction::RejectPlan(reason)) => assert_eq!(reason, "user rejected"),
            other => panic!("expected RejectPlan, got {other:?}"),
        }
        assert!(app.modals.is_empty());
    }

    #[test]
    fn plan_review_e_copies_text_to_input_and_closes_modal() {
        use crate::tui::ui::modal::Modal;
        let mut app = App::new();
        app.screen = AppScreen::Chat;
        app.modals.push(Modal::PlanReview {
            plan_text: "edit me please".into(),
            tool_calls: vec![],
            edited_text: None,
        });
        let action = app.handle_key(key(KeyCode::Char('e')));
        assert!(action.is_none());
        assert_eq!(app.input(), "edit me please");
        assert_eq!(app.prompt.mode, InputMode::Prompt);
        assert!(app.modals.is_empty());
    }

    /// Goal §5: Esc closes the topmost modal rather than quitting.
    #[test]
    fn esc_first_press_closes_modal_not_quits() {
        use crate::tui::ui::modal::Modal;
        let mut app = App::new();
        app.screen = AppScreen::Chat;
        app.modals.push(Modal::Help);
        let _ = app.handle_key(key(KeyCode::Esc));
        assert!(app.modals.is_empty());
        assert!(!app.should_quit);
    }

    /// Goal §5: with no modal but a non-empty buffer, Esc clears the
    /// buffer and does not quit, even on a single press.
    #[test]
    fn esc_first_press_clears_input_when_modal_empty_and_buffer_set() {
        let mut app = App::new();
        app.screen = AppScreen::Chat;
        app.set_input("partial");
        let _ = app.handle_key(key(KeyCode::Esc));
        assert!(!app.should_quit);
        assert!(app.input().is_empty());
    }

    /// Goal §5: Esc does **not** quit even on a second press inside
    /// the double-press window.
    #[test]
    fn esc_does_not_quit_after_double_press_when_idle() {
        let mut app = App::new();
        app.screen = AppScreen::Chat;
        let _ = app.handle_key(key(KeyCode::Esc));
        let _ = app.handle_key(key(KeyCode::Esc));
        assert!(!app.should_quit);
    }

    /// Goal §5: Ctrl+C during a running turn dispatches an Interrupt
    /// action and writes a System block.
    #[test]
    fn ctrl_c_first_press_during_turn_dispatches_interrupt() {
        let mut app = App::new();
        app.screen = AppScreen::Chat;
        app.turn.start();
        let action = app.handle_key(ctrl('c'));
        assert!(matches!(action, Some(UserAction::Interrupt)));
        assert!(app.blocks.iter().any(|b| matches!(b,
            TranscriptBlock::System { text } if text.contains("Interrupting"))));
        assert!(!app.should_quit);
    }

    /// Goal §5: Ctrl+C while idle pushes a "press again to exit"
    /// hint, then a second press inside the window quits.
    #[test]
    fn ctrl_c_first_press_idle_pushes_warning_then_exits_on_second() {
        let mut app = App::new();
        app.screen = AppScreen::Chat;
        let _ = app.handle_key(ctrl('c'));
        assert!(!app.should_quit);
        assert!(app.blocks.iter().any(|b| matches!(b,
            TranscriptBlock::System { text } if text.contains("Press Ctrl+C again"))));
        let _ = app.handle_key(ctrl('c'));
        assert!(app.should_quit);
    }

    /// Goal §5: Ctrl+C×2 inside the window quits regardless of the
    /// soft action the first press kicked off.
    #[test]
    fn ctrl_c_double_press_within_window_quits() {
        let mut app = App::new();
        app.screen = AppScreen::Chat;
        app.turn.start();
        let _ = app.handle_key(ctrl('c'));
        // Second press almost-instantly: must quit.
        let _ = app.handle_key(ctrl('c'));
        assert!(app.should_quit);
    }

    /// Goal §5: a Ctrl+C press outside the double-press window
    /// resets the counter.
    #[test]
    fn ctrl_c_outside_window_resets_counter() {
        use std::time::Instant;
        let mut app = App::new();
        app.screen = AppScreen::Chat;
        // Backdate last_ctrl_c_at so the next press is "outside".
        app.double_press.last_ctrl_c_at = Some(Instant::now() - Duration::from_secs(60));
        let action = app.handle_key(ctrl('c'));
        // First press fresh round: idle + empty → arms the warning.
        assert!(action.is_none());
        assert!(!app.should_quit);
        assert!(app.blocks.iter().any(|b| matches!(b,
            TranscriptBlock::System { text } if text.contains("Press Ctrl+C again"))));
    }
}

// ──────────────────────────────────────────────────────────────────────
// PromptInput tests (Goal 145)
// ──────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod prompt_input_tests {
    use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

    use crate::tui::app::{App, AppScreen, InputMode, HISTORY_CAPACITY};
    use crate::tui::input_state::strip_history_prefix;

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

    fn shift(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::SHIFT)
    }

    fn alt(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::ALT)
    }

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

    fn fresh_app() -> App {
        let mut app = App::new();
        app.screen = AppScreen::Chat;
        app
    }

    // ── prompt_input::shift_tab_cycles_modes ────────────────────────

    #[test]
    fn shift_tab_cycles_modes() {
        let mut app = fresh_app();
        assert_eq!(app.prompt.mode, InputMode::Prompt);
        let _ = app.handle_key(k(KeyCode::BackTab));
        assert_eq!(app.prompt.mode, InputMode::Bash);
        let _ = app.handle_key(k(KeyCode::BackTab));
        assert_eq!(app.prompt.mode, InputMode::Note);
        let _ = app.handle_key(k(KeyCode::BackTab));
        assert_eq!(app.prompt.mode, InputMode::Prompt);
    }

    // ── prompt_input::leading_<x>_enters_<mode>_when_buffer_empty ──

    #[test]
    fn leading_bang_enters_bash_mode_when_buffer_empty() {
        let mut app = fresh_app();
        let _ = app.handle_key(k(KeyCode::Char('!')));
        assert_eq!(app.prompt.mode, InputMode::Bash);
        // The `!` is consumed as the mode marker, not stored.
        assert!(app.prompt.buffer.is_empty());
    }

    #[test]
    fn leading_hash_enters_note_mode() {
        let mut app = fresh_app();
        let _ = app.handle_key(k(KeyCode::Char('#')));
        assert_eq!(app.prompt.mode, InputMode::Note);
        assert!(app.prompt.buffer.is_empty());
    }

    #[test]
    fn leading_slash_enters_command_mode() {
        let mut app = fresh_app();
        let _ = app.handle_key(k(KeyCode::Char('/')));
        assert_eq!(app.prompt.mode, InputMode::Command);
        assert!(app.prompt.buffer.is_empty());
    }

    #[test]
    fn leading_bang_after_existing_text_is_just_a_char() {
        let mut app = fresh_app();
        let _ = app.handle_key(k(KeyCode::Char('h')));
        let _ = app.handle_key(k(KeyCode::Char('!')));
        assert_eq!(app.prompt.mode, InputMode::Prompt);
        assert_eq!(app.prompt.buffer, "h!");
    }

    // ── prompt_input::backspace_on_empty_exits_to_prompt_mode ───────

    #[test]
    fn backspace_on_empty_exits_to_prompt_mode() {
        let mut app = fresh_app();
        let _ = app.handle_key(k(KeyCode::Char('!')));
        assert_eq!(app.prompt.mode, InputMode::Bash);
        let _ = app.handle_key(k(KeyCode::Backspace));
        assert_eq!(app.prompt.mode, InputMode::Prompt);
    }

    // ── prompt_input::cursor_left_right_moves_within_buffer ─────────

    #[test]
    fn cursor_left_right_moves_within_buffer() {
        let mut app = fresh_app();
        for c in "abc".chars() {
            let _ = app.handle_key(k(KeyCode::Char(c)));
        }
        assert_eq!(app.prompt.cursor, 3);
        let _ = app.handle_key(k(KeyCode::Left));
        assert_eq!(app.prompt.cursor, 2);
        let _ = app.handle_key(k(KeyCode::Left));
        assert_eq!(app.prompt.cursor, 1);
        let _ = app.handle_key(k(KeyCode::Right));
        assert_eq!(app.prompt.cursor, 2);
    }

    #[test]
    fn cursor_handles_multibyte_chars() {
        let mut app = fresh_app();
        for c in "你好".chars() {
            let _ = app.handle_key(k(KeyCode::Char(c)));
        }
        // Each Chinese char is 3 bytes in UTF-8.
        assert_eq!(app.prompt.cursor, 6);
        let _ = app.handle_key(k(KeyCode::Left));
        assert_eq!(app.prompt.cursor, 3);
        let _ = app.handle_key(k(KeyCode::Backspace));
        assert_eq!(app.prompt.buffer, "");
    }

    #[test]
    fn insert_at_cursor_not_just_end() {
        let mut app = fresh_app();
        for c in "ac".chars() {
            let _ = app.handle_key(k(KeyCode::Char(c)));
        }
        let _ = app.handle_key(k(KeyCode::Left));
        let _ = app.handle_key(k(KeyCode::Char('b')));
        assert_eq!(app.prompt.buffer, "abc");
    }

    // ── prompt_input::shift_enter_inserts_newline_at_cursor ─────────

    #[test]
    fn shift_enter_inserts_newline_at_cursor() {
        let mut app = fresh_app();
        let _ = app.handle_key(k(KeyCode::Char('a')));
        let _ = app.handle_key(shift(KeyCode::Enter));
        let _ = app.handle_key(k(KeyCode::Char('b')));
        assert_eq!(app.prompt.buffer, "a\nb");
    }

    #[test]
    fn alt_enter_also_inserts_newline() {
        let mut app = fresh_app();
        let _ = app.handle_key(k(KeyCode::Char('a')));
        let _ = app.handle_key(alt(KeyCode::Enter));
        let _ = app.handle_key(k(KeyCode::Char('b')));
        assert_eq!(app.prompt.buffer, "a\nb");
    }

    // ── prompt_input::history_up_down_navigates_records ─────────────

    #[test]
    fn history_up_down_navigates_records() {
        let mut app = fresh_app();
        // Submit two messages.
        app.set_input("first");
        let _ = app.handle_key(k(KeyCode::Enter));
        app.set_input("second");
        let _ = app.handle_key(k(KeyCode::Enter));
        assert_eq!(app.prompt.history.len(), 2);

        let _ = app.handle_key(k(KeyCode::Up));
        assert_eq!(app.prompt.buffer, "second");
        let _ = app.handle_key(k(KeyCode::Up));
        assert_eq!(app.prompt.buffer, "first");
        let _ = app.handle_key(k(KeyCode::Down));
        assert_eq!(app.prompt.buffer, "second");
        let _ = app.handle_key(k(KeyCode::Down));
        // Past newest → restored draft (empty here).
        assert!(app.prompt.buffer.is_empty());
    }

    // ── prompt_input::history_up_saves_draft_and_restores_on_overflow ─

    #[test]
    fn history_up_saves_draft_and_restores_on_overflow() {
        let mut app = fresh_app();
        app.set_input("alpha");
        let _ = app.handle_key(k(KeyCode::Enter));
        // Walk history: only triggers when buffer is empty.
        let _ = app.handle_key(k(KeyCode::Up));
        assert_eq!(app.prompt.buffer, "alpha");
        let _ = app.handle_key(k(KeyCode::Down));
        assert!(app.prompt.buffer.is_empty());
    }

    #[test]
    fn history_preserves_mode_prefix() {
        let mut app = fresh_app();
        // Submit a bash command.
        let _ = app.handle_key(k(KeyCode::Char('!')));
        for c in "echo hi".chars() {
            let _ = app.handle_key(k(KeyCode::Char(c)));
        }
        let _ = app.handle_key(k(KeyCode::Enter));
        assert_eq!(app.prompt.mode, InputMode::Prompt);
        // Walk back: should restore Bash mode.
        let _ = app.handle_key(k(KeyCode::Up));
        assert_eq!(app.prompt.mode, InputMode::Bash);
        assert_eq!(app.prompt.buffer, "echo hi");
    }

    #[test]
    fn history_capacity_truncates_oldest() {
        let mut app = fresh_app();
        for i in 0..(HISTORY_CAPACITY + 5) {
            app.set_input(format!("msg{i}"));
            let _ = app.handle_key(k(KeyCode::Enter));
        }
        assert_eq!(app.prompt.history.len(), HISTORY_CAPACITY);
        // The earliest entries should have been dropped.
        assert!(!app.prompt.history.iter().any(|h| h == "msg0"));
    }

    // ── prompt_input::submit_in_bash_mode_dispatches_run_shell ──────

    #[test]
    fn submit_in_bash_mode_dispatches_run_shell() {
        use crate::tui::events::UserAction;
        let mut app = fresh_app();
        let _ = app.handle_key(k(KeyCode::Char('!')));
        for c in "ls".chars() {
            let _ = app.handle_key(k(KeyCode::Char(c)));
        }
        let action = app.handle_key(k(KeyCode::Enter));
        assert!(matches!(action, Some(UserAction::RunShell(s)) if s == "ls"));
        assert!(app.prompt.buffer.is_empty());
        assert_eq!(app.prompt.mode, InputMode::Prompt);
    }

    // ── prompt_input::submit_in_note_mode_appends_system_block ──────

    #[test]
    fn submit_in_note_mode_appends_system_block() {
        use crate::tui::app::TranscriptBlock;
        let mut app = fresh_app();
        let _ = app.handle_key(k(KeyCode::Char('#')));
        for c in "remember this".chars() {
            let _ = app.handle_key(k(KeyCode::Char(c)));
        }
        let action = app.handle_key(k(KeyCode::Enter));
        // No backend action: notes are local-only.
        assert!(action.is_none());
        assert!(app
            .blocks
            .iter()
            .any(|b| matches!(b, TranscriptBlock::System { text }
                if text.contains("remember this"))));
    }

    #[test]
    fn submit_in_command_mode_dispatches_to_registry() {
        // Goal-146 replaces the old placeholder System block with the
        // actual command dispatcher. /help opens the Help modal.
        let mut app = fresh_app();
        let _ = app.handle_key(k(KeyCode::Char('/')));
        for c in "help".chars() {
            let _ = app.handle_key(k(KeyCode::Char(c)));
        }
        let action = app.handle_key(k(KeyCode::Enter));
        assert!(action.is_none());
        // /help pushed a Help modal onto the stack.
        assert_eq!(app.modals.last(), Some(&crate::tui::ui::modal::Modal::Help));
        // Buffer was reset.
        assert!(app.prompt.buffer.is_empty());
        assert_eq!(app.prompt.mode, InputMode::Prompt);
    }

    // ── prompt_input::submit_clears_buffer_and_resets_mode ──────────

    #[test]
    fn submit_clears_buffer_and_resets_mode() {
        let mut app = fresh_app();
        let _ = app.handle_key(k(KeyCode::Char('!')));
        let _ = app.handle_key(k(KeyCode::Char('x')));
        let _ = app.handle_key(k(KeyCode::Enter));
        assert!(app.prompt.buffer.is_empty());
        assert_eq!(app.prompt.cursor, 0);
        assert_eq!(app.prompt.mode, InputMode::Prompt);
        assert!(app.prompt.history_idx.is_none());
    }

    // ── home / end on multi-line ────────────────────────────────────

    #[test]
    fn home_end_target_current_line_only() {
        let mut app = fresh_app();
        app.set_input("ab\ncd");
        // cursor is at end (5).
        app.prompt.cursor = 4; // between c and d
        let _ = app.handle_key(k(KeyCode::Home));
        assert_eq!(app.prompt.cursor, 3); // start of "cd"
        let _ = app.handle_key(k(KeyCode::End));
        assert_eq!(app.prompt.cursor, 5); // end of buffer
    }

    // ── ctrl+e disambiguation (goal §10) ────────────────────────────

    #[test]
    fn ctrl_e_with_empty_buffer_toggles_tool_result() {
        use crate::tui::app::{ToolResultData, TranscriptBlock};
        use crate::tui::events::UiEvent;
        let mut app = fresh_app();
        app.handle_ui_event(UiEvent::ToolResult {
            id: "1".into(),
            name: "read_file".into(),
            output: "ok".into(),
            success: true,
        });
        let _ = app.handle_key(ctrl('e'));
        match app.blocks.last() {
            Some(TranscriptBlock::ToolCall {
                result: Some(ToolResultData { expanded, .. }),
                ..
            }) => assert!(*expanded),
            other => panic!("expected ToolCall with Some(result), got {other:?}"),
        }
    }

    #[test]
    fn ctrl_e_with_text_moves_to_end_of_line() {
        let mut app = fresh_app();
        app.set_input("hello");
        app.prompt.cursor = 1;
        let _ = app.handle_key(ctrl('e'));
        assert_eq!(app.prompt.cursor, 5);
    }

    #[test]
    fn ctrl_a_moves_to_line_start() {
        let mut app = fresh_app();
        app.set_input("hello");
        let _ = app.handle_key(ctrl('a'));
        assert_eq!(app.prompt.cursor, 0);
    }

    // ── exhaustively cover history's empty-on-down case ─────────────

    #[test]
    fn history_down_with_no_walk_in_progress_is_noop() {
        let mut app = fresh_app();
        // Down on empty, no history → falls through to scroll path.
        let _ = app.handle_key(k(KeyCode::Down));
        assert!(app.prompt.history_idx.is_none());
    }

    // ── strip_history_prefix utility ────────────────────────────────

    #[test]
    fn strip_history_prefix_recognises_all_modes() {
        assert_eq!(strip_history_prefix("!ls").0, InputMode::Bash);
        assert_eq!(strip_history_prefix("#note").0, InputMode::Note);
        assert_eq!(strip_history_prefix("/cmd").0, InputMode::Command);
        assert_eq!(strip_history_prefix("hello").0, InputMode::Prompt);
        assert_eq!(strip_history_prefix("!ls").1, "ls");
    }
}

// ── Goal-158: @file autocomplete tests ───────────────────────────────────────

#[cfg(test)]
mod atfile_tests {
    use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

    use crate::tui::app::{App, InputMode, MAX_ATFILE_SUGGESTIONS};
    use crate::tui::completion::glob_workspace_files;

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

    #[test]
    fn atfile_mode_triggered_by_at_in_prompt_mode() {
        let mut app = App::new();
        assert_eq!(app.prompt.mode, InputMode::Prompt);
        app.handle_char_input('@');
        assert_eq!(app.prompt.mode, InputMode::AtFile);
        assert!(app.prompt.buffer.ends_with('@'));
    }

    #[test]
    fn atfile_mode_not_triggered_in_bash_mode() {
        let mut app = App::new();
        app.prompt.mode = InputMode::Bash;
        app.handle_char_input('@');
        assert_eq!(app.prompt.mode, InputMode::Bash);
    }

    #[test]
    fn atfile_mode_not_triggered_in_command_mode() {
        let mut app = App::new();
        app.prompt.mode = InputMode::Command;
        app.handle_char_input('@');
        assert_eq!(app.prompt.mode, InputMode::Command);
    }

    #[test]
    fn glob_workspace_files_filters_by_query_prefix() {
        // We can only test that the function returns a Vec and doesn't panic;
        // actual path results are environment-dependent.
        let results = glob_workspace_files("Cargo");
        // Should be ≤ MAX_ATFILE_SUGGESTIONS
        assert!(results.len() <= MAX_ATFILE_SUGGESTIONS);
        // All returned paths should contain "cargo" (case-insensitive)
        for r in &results {
            assert!(r.to_lowercase().contains("cargo"), "unexpected result: {r}");
        }
    }

    #[test]
    fn glob_workspace_files_returns_at_most_12() {
        let results = glob_workspace_files("");
        assert!(results.len() <= MAX_ATFILE_SUGGESTIONS);
    }

    #[test]
    fn atfile_backspace_on_empty_query_exits_mode_and_deletes_at() {
        let mut app = App::new();
        // Type some text, then '@'
        app.handle_char_input('h');
        app.handle_char_input('i');
        app.handle_char_input('@');
        assert_eq!(app.prompt.mode, InputMode::AtFile);
        assert_eq!(app.prompt.buffer, "hi@");

        // Backspace with empty query should exit mode and remove '@'
        app.handle_atfile_key(k(KeyCode::Backspace));
        assert_eq!(app.prompt.mode, InputMode::Prompt);
        assert_eq!(app.prompt.buffer, "hi");
    }

    #[test]
    fn atfile_enter_inserts_selected_path_and_exits() {
        let mut app = App::new();
        app.handle_char_input('@');
        assert_eq!(app.prompt.mode, InputMode::AtFile);

        // Manually inject a suggestion so the test is deterministic.
        app.atfile_suggestions = vec!["src/lib.rs".to_string(), "src/main.rs".to_string()];
        app.atfile_selected = Some(0);

        // Press Enter to commit.
        app.handle_atfile_key(k(KeyCode::Enter));
        assert_eq!(app.prompt.mode, InputMode::Prompt);
        assert!(
            app.prompt.buffer.ends_with("@src/lib.rs"),
            "buffer was: {}",
            app.prompt.buffer
        );
    }

    #[test]
    fn atfile_esc_cancels_and_preserves_at_query() {
        let mut app = App::new();
        app.handle_char_input('t');
        app.handle_char_input('e');
        app.handle_char_input('s');
        app.handle_char_input('t');
        app.handle_char_input(' ');
        app.handle_char_input('@');
        // Type a query.
        app.handle_atfile_key(k(KeyCode::Char('s')));
        app.handle_atfile_key(k(KeyCode::Char('r')));
        app.handle_atfile_key(k(KeyCode::Char('c')));

        assert_eq!(app.prompt.mode, InputMode::AtFile);
        let buf_before = app.prompt.buffer.clone();

        // Press Esc — mode should exit but buffer kept.
        app.handle_atfile_key(k(KeyCode::Esc));
        assert_eq!(app.prompt.mode, InputMode::Prompt);
        assert_eq!(app.prompt.buffer, buf_before);
        // Suggestion list is cleared.
        assert!(app.atfile_suggestions.is_empty());
    }

    #[test]
    fn atfile_up_down_navigation() {
        let mut app = App::new();
        app.handle_char_input('@');
        app.atfile_suggestions = vec!["a.rs".to_string(), "b.rs".to_string(), "c.rs".to_string()];
        app.atfile_selected = None;

        // Down selects first item.
        app.handle_atfile_key(k(KeyCode::Down));
        assert_eq!(app.atfile_selected, Some(0));

        // Down again — second.
        app.handle_atfile_key(k(KeyCode::Down));
        assert_eq!(app.atfile_selected, Some(1));

        // Up — back to first.
        app.handle_atfile_key(k(KeyCode::Up));
        assert_eq!(app.atfile_selected, Some(0));

        // Up again — deselects (None).
        app.handle_atfile_key(k(KeyCode::Up));
        assert_eq!(app.atfile_selected, None);
    }
}

// ── Goal-160: Ctrl+R history search tests ────────────────────────────────────

#[cfg(test)]
mod hsearch_tests {
    use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

    use crate::tui::app::{App, InputMode, MAX_HSEARCH_RESULTS};
    use crate::tui::completion::search_history;

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

    fn ctrl(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::CONTROL)
    }

    fn history_app(entries: &[&str]) -> App {
        let mut app = App::new();
        for e in entries {
            app.prompt.history.push(e.to_string());
        }
        app
    }

    // ── search_history unit tests ──────────────────────────────────────

    #[test]
    fn history_search_empty_query_returns_all_reversed() {
        let h = vec!["a".to_string(), "b".to_string(), "c".to_string()];
        let r = search_history(&h, "");
        // Most recent first: indices 2,1,0.
        assert_eq!(r, vec![2, 1, 0]);
    }

    #[test]
    fn history_search_prefix_match_ranked_first() {
        let h = vec![
            "foo bar".to_string(),
            "zz foo".to_string(),
            "foobar".to_string(),
        ];
        let r = search_history(&h, "foo");
        // Entries 0 and 2 start with "foo"; entry 1 is a substring match.
        // Prefix matches come first; within prefix group, reversed = 2 then 0.
        assert!(r.iter().position(|&x| x == 2) < r.iter().position(|&x| x == 1));
        assert!(r.iter().position(|&x| x == 0) < r.iter().position(|&x| x == 1));
    }

    #[test]
    fn history_search_case_insensitive() {
        let h = vec!["Hello World".to_string(), "goodbye".to_string()];
        let r = search_history(&h, "hello");
        assert!(r.contains(&0));
        assert!(!r.contains(&1));
    }

    #[test]
    fn history_search_returns_at_most_12() {
        let h: Vec<String> = (0..20).map(|i| format!("entry {i}")).collect();
        let r = search_history(&h, "entry");
        assert!(r.len() <= MAX_HSEARCH_RESULTS);
    }

    // ── App integration tests ──────────────────────────────────────────

    #[test]
    fn ctrl_r_in_prompt_mode_enters_history_search() {
        let mut app = history_app(&["hello", "world"]);
        assert_eq!(app.prompt.mode, InputMode::Prompt);
        app.handle_key(ctrl(KeyCode::Char('r')));
        assert_eq!(app.prompt.mode, InputMode::HistorySearch);
        // All entries pre-loaded.
        assert_eq!(app.hsearch_matches.len(), 2);
    }

    #[test]
    fn ctrl_r_in_bash_mode_no_op() {
        let mut app = history_app(&["hello"]);
        app.prompt.mode = InputMode::Bash;
        app.handle_key(ctrl(KeyCode::Char('r')));
        // Should stay in Bash mode, not HistorySearch.
        assert_eq!(app.prompt.mode, InputMode::Bash);
    }

    #[test]
    fn history_search_enter_fills_buffer() {
        let mut app = history_app(&["cargo build", "cargo test"]);
        app.handle_key(ctrl(KeyCode::Char('r')));
        assert_eq!(app.prompt.mode, InputMode::HistorySearch);
        // With empty query, most recent first: index 1 ("cargo test") selected.
        assert_eq!(app.hsearch_selected, 0);
        // Press Enter → fill buffer with the selected entry.
        app.handle_history_search_key(k(KeyCode::Enter));
        assert_eq!(app.prompt.mode, InputMode::Prompt);
        assert_eq!(app.prompt.buffer, "cargo test");
    }

    #[test]
    fn history_search_esc_cancels() {
        let mut app = history_app(&["hello"]);
        app.handle_key(ctrl(KeyCode::Char('r')));
        assert_eq!(app.prompt.mode, InputMode::HistorySearch);
        app.handle_history_search_key(k(KeyCode::Esc));
        assert_eq!(app.prompt.mode, InputMode::Prompt);
        // Buffer should be unchanged.
        assert!(app.prompt.buffer.is_empty());
    }

    #[test]
    fn history_search_backspace_on_empty_exits_mode() {
        let mut app = history_app(&["hello"]);
        app.handle_key(ctrl(KeyCode::Char('r')));
        assert_eq!(app.prompt.mode, InputMode::HistorySearch);
        assert!(app.hsearch_query.is_empty());
        // Backspace on empty query exits HistorySearch.
        app.handle_history_search_key(k(KeyCode::Backspace));
        assert_eq!(app.prompt.mode, InputMode::Prompt);
    }
}

// ── Goal-161: Permission Modal tests ─────────────────────────────────────────

#[cfg(test)]
mod perm_tests {
    use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

    use crate::tui::app::{App, PendingPermission};
    use crate::tui::events::UiEvent;

    fn make_perm(tool: &str, args: &str) -> (App, tokio::sync::oneshot::Receiver<bool>) {
        let mut app = App::new();
        let (tx, rx) = tokio::sync::oneshot::channel::<bool>();
        let req = crate::tui::events::PermissionRequest {
            tool_name: tool.to_string(),
            args_preview: args.to_string(),
            reply: tx,
        };
        app.set_pending_permission(req);
        (app, rx)
    }

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

    #[test]
    fn pending_permission_set_and_stored() {
        let (app, _rx) = make_perm("run_shell", "ls -la");
        assert!(app.pending_permission.is_some());
        let p = app.pending_permission.as_ref().unwrap();
        assert_eq!(p.tool_name, "run_shell");
        assert_eq!(p.args_preview, "ls -la");
    }

    #[tokio::test]
    async fn y_key_sends_true_and_clears_modal() {
        let (mut app, rx) = make_perm("run_shell", "ls");
        app.handle_permission_key(k(KeyCode::Char('y')));
        assert!(app.pending_permission.is_none());
        assert!(rx.await.unwrap());
    }

    #[tokio::test]
    async fn n_key_sends_false_and_clears_modal() {
        let (mut app, rx) = make_perm("run_shell", "rm -rf /");
        app.handle_permission_key(k(KeyCode::Char('n')));
        assert!(app.pending_permission.is_none());
        assert!(!rx.await.unwrap());
    }

    #[tokio::test]
    async fn esc_key_sends_false() {
        let (mut app, rx) = make_perm("write_file", "path=foo.txt");
        app.handle_permission_key(k(KeyCode::Esc));
        assert!(app.pending_permission.is_none());
        assert!(!rx.await.unwrap());
    }

    #[tokio::test]
    async fn enter_key_sends_true() {
        let (mut app, rx) = make_perm("read_file", "path=foo.txt");
        app.handle_permission_key(k(KeyCode::Enter));
        assert!(app.pending_permission.is_none());
        assert!(rx.await.unwrap());
    }

    #[tokio::test]
    async fn a_key_sends_true_and_adds_to_auto_allowed() {
        let (mut app, rx) = make_perm("run_shell", "cargo test");
        app.handle_permission_key(k(KeyCode::Char('a')));
        assert!(app.pending_permission.is_none());
        assert!(rx.await.unwrap());
        assert!(app.auto_allowed_tools.contains("run_shell"));
    }

    #[tokio::test]
    async fn auto_allowed_tool_skips_modal() {
        let mut app = App::new();
        app.auto_allowed_tools.insert("run_shell".to_string());
        let (tx, rx) = tokio::sync::oneshot::channel::<bool>();
        let req = crate::tui::events::PermissionRequest {
            tool_name: "run_shell".to_string(),
            args_preview: "cargo build".to_string(),
            reply: tx,
        };
        // Should auto-allow without storing to pending_permission.
        app.set_pending_permission(req);
        assert!(app.pending_permission.is_none());
        assert!(rx.await.unwrap());
    }

    #[test]
    fn handle_key_routes_to_permission_when_pending() {
        // When pending_permission is set, handle_key routes to permission handler.
        let (tx, _rx) = tokio::sync::oneshot::channel::<bool>();
        let mut app = App::new();
        let req = crate::tui::events::PermissionRequest {
            tool_name: "write_file".to_string(),
            args_preview: "path=foo.rs".to_string(),
            reply: tx,
        };
        app.pending_permission = Some(PendingPermission {
            tool_name: req.tool_name,
            args_preview: req.args_preview,
            reply: req.reply,
        });
        assert!(app.pending_permission.is_some());
        // N key via handle_key should route to permission handler.
        app.handle_key(k(KeyCode::Char('n')));
        assert!(app.pending_permission.is_none());
    }

    // ── Goal-202: plan-mode pre-confirmation ───────────────────────────

    #[test]
    fn plan_mode_requested_event_sets_pending_flag() {
        use crate::tui::app::TranscriptBlock;
        let mut app = App::new();
        app.handle_ui_event(UiEvent::PlanModeRequested {
            reason: "This task is complex".into(),
        });
        assert!(app.plan_mode_request_pending);
        assert!(app.blocks.iter().any(|b| matches!(b,
            TranscriptBlock::PlanModeRequest { reason, approved: None }
                if reason.contains("complex"))));
    }

    #[test]
    fn plan_mode_request_y_dispatches_approve_action() {
        use crate::tui::events::UserAction;
        let mut app = App::new();
        app.handle_ui_event(UiEvent::PlanModeRequested {
            reason: "need to plan".into(),
        });
        assert!(app.plan_mode_request_pending);
        let action = app.handle_key(k(KeyCode::Char('y')));
        assert!(!app.plan_mode_request_pending, "flag should be cleared");
        assert!(matches!(action, Some(UserAction::ApprovePlanMode)));
    }

    #[test]
    fn plan_mode_request_n_dispatches_reject_action() {
        use crate::tui::events::UserAction;
        let mut app = App::new();
        app.handle_ui_event(UiEvent::PlanModeRequested {
            reason: "need to plan".into(),
        });
        let action = app.handle_key(k(KeyCode::Char('n')));
        assert!(!app.plan_mode_request_pending, "flag should be cleared");
        assert!(matches!(action, Some(UserAction::RejectPlanMode(r)) if r == "user skipped"));
    }

    #[test]
    fn plan_mode_approved_event_marks_block() {
        use crate::tui::app::TranscriptBlock;
        let mut app = App::new();
        app.handle_ui_event(UiEvent::PlanModeRequested {
            reason: "complex".into(),
        });
        app.handle_ui_event(UiEvent::PlanModeApproved);
        assert!(!app.plan_mode_request_pending);
        assert!(app.blocks.iter().any(|b| matches!(
            b,
            TranscriptBlock::PlanModeRequest {
                approved: Some(true),
                ..
            }
        )));
    }

    #[test]
    fn plan_mode_rejected_event_marks_block() {
        use crate::tui::app::TranscriptBlock;
        let mut app = App::new();
        app.handle_ui_event(UiEvent::PlanModeRequested {
            reason: "complex".into(),
        });
        app.handle_ui_event(UiEvent::PlanModeRejected {
            reason: "user skipped".into(),
        });
        assert!(!app.plan_mode_request_pending);
        assert!(app.blocks.iter().any(|b| matches!(
            b,
            TranscriptBlock::PlanModeRequest {
                approved: Some(false),
                ..
            }
        )));
    }
}