konoma 0.23.1

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

mod app;
mod bookmarks;
mod config;
#[cfg(test)]
mod e2e_tests;
mod fileops;
mod git;
mod i18n;
mod keymap;
#[cfg(test)]
mod mem_tests;
mod preview;
mod session;
#[cfg(test)]
mod speed_tests;
mod ui;

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

use anyhow::{Context, Result};
use crossterm::event::{
    self, DisableBracketedPaste, EnableBracketedPaste, Event, KeyCode, KeyEvent, KeyEventKind,
    KeyModifiers,
};
use ratatui_image::errors::Errors;
use ratatui_image::picker::Picker;
use ratatui_image::thread::{ResizeRequest, ResizeResponse};
use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender};

use app::{
    App, FileOpResult, IgnoredResult, KittyResult, MdEncodeRequest, MdEncodeResult, MdImageResult,
    MediaResult, RemoteFetch, SortKey, StatusResult,
};
use keymap::{Action, KeyPress, Motion, Resolution, Surface};

/// Re-encode result sent from the worker to the UI.
type ResizeResult = Result<ResizeResponse, Errors>;

fn main() -> Result<()> {
    // Argument: konoma [DIR]. Falls back to the current directory. On cwd-lookup failure, don't
    // panic — return gracefully via ?.
    let dir = match std::env::args().nth(1) {
        Some(arg) => PathBuf::from(arg),
        None => std::env::current_dir().context("could not get the current directory")?,
    };
    // Normalize so path-copy still produces a correct absolute path even for a relative argument
    // (e.g. `konoma samples`).
    // On canonicalize failure, fall back by joining it with cwd.
    let dir = std::fs::canonicalize(&dir).unwrap_or_else(|_| {
        std::env::current_dir()
            .map(|cwd| cwd.join(&dir))
            .unwrap_or(dir)
    });

    let (cfg, cfg_err) = config::Config::load_reporting();

    // Loading syntect's assets + compiling a grammar's regexes (once per language, a few seconds
    // in debug) is heavy. On startup, warm it up on a separate thread — going through the current
    // root's extensions **in order of most files first** — to eliminate the freeze on the first
    // code preview (if it doesn't finish in time, just wait normally for the first one only). A
    // single thread + yield so it doesn't get in the way of other work.
    // With highlighting off (ui.syntax_highlight=false), syntect is never used at all, so no
    // warm-up is needed.
    if cfg.ui.syntax_highlight {
        let root = dir.clone();
        std::thread::spawn(move || preview::code::warm_dir(root));
    }

    let mut terminal = ratatui::init();
    // Enable bracketed paste: so a file drag & drop (the terminal delivers the path as a paste) is
    // received as `Event::Paste` and wired into the copy/move dialog. Ignored harmlessly on
    // unsupported terminals.
    let _ = crossterm::execute!(std::io::stdout(), EnableBracketedPaste);

    // Image backend: query the terminal (detects kitty, etc.). Once, after entering the alt
    // screen and before reading events.
    // Held as an Option so that on failure (unsupported terminal, etc.) everything but the
    // preview still works.
    let picker = Picker::from_query_stdio().ok();

    // On a terminal that can show images, warm up SVG's system-font enumeration (~tens of ms the
    // first time) in the background at startup ahead of time
    // (hides the UI freeze on the first SVG display — the same policy as syntax highlighting's warm_dir).
    // In mermaid image mode, likewise warm up the renderer's lazy font measurement (hides the
    // tens-of-ms freeze on the first diagram display).
    if picker.is_some() {
        std::thread::spawn(preview::svg::warm_fontdb);
        if cfg.ui.mermaid != "text" {
            std::thread::spawn(preview::markdown::warm_mermaid);
        }
    }

    // Channel and worker thread for offloading resize/encode.
    let (req_tx, req_rx) = unbounded_channel::<ResizeRequest>();
    let (resp_tx, resp_rx) = unbounded_channel::<ResizeResult>();
    let worker = std::thread::spawn(move || resize_worker(req_rx, resp_tx));

    // Read heavy media (SVG rasterization / full-frame GIF decode) on a separate thread, and send
    // the result to the run loop.
    let (media_tx, media_rx) = std::sync::mpsc::channel::<MediaResult>();
    // Do a kitty image's resize+compress (zoom/pan) on a separate thread, and send the result to
    // the run loop (the first one is synchronous).
    let (kitty_tx, kitty_rx) = std::sync::mpsc::channel::<KittyResult>();
    // Decode inline Markdown images on a separate thread, and send the result to the run loop.
    let (md_img_tx, md_img_rx) = std::sync::mpsc::channel::<MdImageResult>();
    // Notify the run loop when a remote (http(s)) Markdown image's curl download completes.
    let (md_remote_tx, md_remote_rx) = std::sync::mpsc::channel::<RemoteFetch>();
    // Offload inline Markdown image encoding (resize + protocol) to a dedicated worker (doesn't
    // block the UI).
    let (md_enc_tx, md_enc_worker_rx) = std::sync::mpsc::channel::<MdEncodeRequest>();
    let (md_enc_res_tx, md_enc_res_rx) = std::sync::mpsc::channel::<MdEncodeResult>();
    // Compute the heavy git ignored (the ignore set — ~800ms on a large repo) on a separate
    // thread, and send the result to the run loop.
    let (ignored_tx, ignored_rx) = std::sync::mpsc::channel::<IgnoredResult>();
    // A full `git status` (a whole-worktree scan) also goes to a separate thread. Even on a small
    // repo it's ~5ms, and on a large repo it can take hundreds of ms, stalling the UI on every tab
    // switch/directory move.
    let (status_tx, status_rx) = std::sync::mpsc::channel::<StatusResult>();
    // Long-running file operations (copy/move/duplicate/delete) also go to a separate thread.
    // Pasting/deleting a large directory used to freeze input/rendering (design principle #4).
    let (fileop_tx, fileop_rx) = std::sync::mpsc::channel::<FileOpResult>();

    let start_dir = dir.clone();
    let mut app = App::new(dir, cfg)?;
    app.attach_media_loader(media_tx);
    app.attach_kitty_loader(kitty_tx);
    app.attach_md_image_loader(md_img_tx);
    app.attach_remote_md_loader(md_remote_tx);
    app.attach_git_loader(ignored_tx);
    app.attach_status_loader(status_tx);
    app.attach_fileop_runner(fileop_tx);
    // Report a config load error + keymap conflicts/ignored settings via a startup message
    // (silently falling back to the default would go unnoticed). If both are present, combine
    // them into one line.
    let km_report = app.keymap_report();
    app.flash = match (cfg_err, km_report) {
        (Some(a), Some(b)) => Some(format!("{a} / {b}")),
        (Some(a), None) => Some(a),
        (None, b) => b,
    };
    // Inline image encode worker: launched only when there is a backend (clones the Picker to pass in).
    // Dropping App makes md_enc_tx disappear, and the worker's recv returns Err, terminating it cleanly.
    if let Some(pk) = picker.clone() {
        std::thread::spawn(move || app::md_encode_worker(pk, md_enc_worker_rx, md_enc_res_tx));
        app.attach_md_encoder(md_enc_tx);
    }
    if let Some(picker) = picker {
        // Pass tx to App (each image's ThreadProtocol clones and uses it).
        app.attach_image_backend(picker, req_tx);
    }
    // Note: don't keep a clone of req_tx on the main side. Dropping App makes every Sender
    // disappear, so the worker's recv returns None and can terminate cleanly.

    // Tab session ([ui] restore_tabs): restore the tab layout that was open in this start
    // directory last time.
    // Done after wiring up each loader/image backend (restoring re-opens previews, which fires
    // media jobs).
    app.attach_session_store(session::SessionStore::load(&start_dir));
    app.restore_session();

    let result = run(
        &mut terminal,
        &mut app,
        resp_rx,
        WorkerRx {
            media: media_rx,
            kitty: kitty_rx,
            md_img: md_img_rx,
            md_remote: md_remote_rx,
            md_enc: md_enc_res_rx,
            ignored: ignored_rx,
            status: status_rx,
            fileop: fileop_rx,
        },
    );

    // Save the tab session on exit (the state at exit time is the final form. no-op when restore_tabs=false).
    app.save_session();

    let _ = crossterm::execute!(std::io::stdout(), DisableBracketedPaste);
    ratatui::restore();

    // Fold up App, dropping every Sender, so the workers terminate.
    app.detach_image_backend();
    drop(app);
    let _ = worker.join();

    result
}

/// Handle resize requests on a current-thread tokio runtime on a dedicated thread.
/// `resize_encode()` is CPU-heavy, but running it on this dedicated thread keeps the UI thread unblocked.
fn resize_worker(mut rx: UnboundedReceiver<ResizeRequest>, tx: UnboundedSender<ResizeResult>) {
    let Ok(rt) = tokio::runtime::Builder::new_current_thread().build() else {
        return;
    };
    rt.block_on(async move {
        while let Some(req) = rx.recv().await {
            // 1 request = 1 encode. Return completion to the UI (the UI applies it via try_recv).
            if tx.send(req.resize_encode()).is_err() {
                break; // the UI side has terminated
            }
        }
    });
}

/// Classify the paths from an fs event. Returns `(meaningful, ignore_rules_changed)`:
/// - `meaningful`: whether reloading is worthwhile. Any non-empty event is meaningful — **including
///   `.git/*.lock` churn from an external git operation**. konoma's own git reads take no locks (CLI
///   reads pass `--no-optional-locks`; git2 diffs never set `update_index`), so a `.git` lock event can
///   only come from an *external* git op (a commit/amend/reset by the user or an AI agent) whose result
///   we must reflect. (Historically we swallowed lock-only events to break a self-feedback loop in which
///   konoma's own `git status` created `.git/index.lock` → the watcher picked it up → git ran again.
///   `--no-optional-locks` (2026-07-07) removed that loop at the source, so swallowing now only *hides*
///   external commits — e.g. the stale change marker seen after an agent commits while you preview a file.)
/// - `ignore_rules_changed`: whether `.gitignore` or `.git/info/exclude` changed (= the heavy
///   ignore set must be rebuilt). For other changes, `ignored` is left alone and only the cheap `statuses` is updated.
fn classify_fs_paths(paths: &[PathBuf]) -> (bool, bool) {
    if paths.is_empty() {
        return (true, false); // An event with an unknown path errs safe (reload, don't touch ignored)
    }
    // Any path change is worth reloading (the run loop coalesces a burst into one). Only request
    // rebuilding the heavy ignored set when an event that changed the ignore rules is included.
    let ignore_rules = paths.iter().any(|p| is_ignore_rule_file(p));
    (true, ignore_rules)
}

/// Whether a raw notify `EventKind` reflects an actual content change and is worth reacting to at
/// all — checked **before** `classify_fs_paths` even looks at the paths. notify's inotify backend
/// (Linux) subscribes to `IN_OPEN`/`IN_ACCESS`, so merely *opening or reading* a file emits
/// `EventKind::Access(..)` — no write happened. Left unfiltered this breaks two things on Linux:
/// follow mode (`F`) jumping to files that were only `cat`, and a self-feeding loop where konoma's
/// own `git status` opens tracked files, the reads get reported back as "changes", and that refresh
/// runs `git status` again forever (the busy "git scan" spinner never stops). macOS's FSEvents
/// backend never reports reads at all, so this predicate is a no-op there — `Access` events simply
/// don't occur, and every branch below `Access` (`Any`/`Create`/`Modify`/`Remove`/`Other`) still
/// returns `true`, keeping macOS behaviour byte-identical.
///
/// The one `Access` case that *is* a real change: `Close(Write)` (inotify's `IN_CLOSE_WRITE`) fires
/// after a file that was opened for writing is closed — i.e. a write actually happened and is now
/// flushed. Every other `Access` variant (opens, plain reads, close-without-write) is a no-op read.
fn is_content_event(kind: &notify::EventKind) -> bool {
    use notify::event::{AccessKind, AccessMode};
    match kind {
        notify::EventKind::Access(AccessKind::Close(AccessMode::Write)) => true,
        notify::EventKind::Access(_) => false,
        _ => true,
    }
}

/// Hard cap on how many changed paths one filesystem burst reports individually.
/// Beyond this the burst is treated as "paths unknown", which the caller handles conservatively
/// (a full refresh). A burst that large is a build or a bulk copy, where per-path information is
/// worthless anyway — and collecting it used to cost O(N²).
const MAX_BURST_PATHS: usize = 1024;

/// Accumulates the distinct paths of one filesystem-event burst, in arrival order, with a hard cap.
///
/// De-duplication is a hash lookup, not a linear scan: an agent creating tens of thousands of files
/// produced one burst that took minutes of 100% CPU to de-duplicate with `Vec::contains`, freezing
/// the UI. Once the cap is passed the collected list is discarded and `finish` reports `None`,
/// meaning "something changed but we don't know what" — the caller's safe path.
#[derive(Default)]
struct BurstPaths {
    seen: std::collections::HashSet<PathBuf>,
    paths: Vec<PathBuf>,
    overflowed: bool,
}

impl BurstPaths {
    /// Record one path. Returns true when it is newly seen (the caller uses that to avoid repeating
    /// per-path work). Returns false once the cap is reached (whether or not `p` was already seen).
    fn push(&mut self, p: &Path) -> bool {
        if self.overflowed {
            return false;
        }
        if self.seen.contains(p) {
            return false;
        }
        if self.paths.len() >= MAX_BURST_PATHS {
            self.overflowed = true;
            self.seen.clear();
            self.paths.clear();
            return false;
        }
        let owned = p.to_path_buf();
        self.seen.insert(owned.clone());
        self.paths.push(owned);
        true
    }

    /// The distinct paths in arrival order, or `None` when the burst overflowed the cap.
    fn finish(self) -> Option<Vec<PathBuf>> {
        if self.overflowed {
            None
        } else {
            Some(self.paths)
        }
    }
}

/// Paths from an fs event that follow mode may jump to: anything not under a `.git` directory
/// (repository internals — index/refs/lock churn — are never review targets). Existence/kind/root
/// checks happen later in `App::follow_jump` (the event may be a deletion, or outside the tree).
fn follow_candidates(paths: &[PathBuf]) -> Vec<PathBuf> {
    paths
        .iter()
        .filter(|p| !p.components().any(|c| c.as_os_str() == ".git"))
        .cloned()
        .collect()
}

/// Whether `p` is a file that holds ignore rules (a change requires recomputing the ignore set):
/// the `.gitignore` itself, or `.git/info/exclude`. A `.gitignore` under `node_modules` is excluded
/// because it sits inside a wholly-ignored tree and does not affect git's decision (avoiding a wasteful recompute).
fn is_ignore_rule_file(p: &Path) -> bool {
    let name = p.file_name().and_then(|n| n.to_str()).unwrap_or("");
    match name {
        ".gitignore" => !p.components().any(|c| c.as_os_str() == "node_modules"),
        "exclude" => {
            // .git/info/exclude (parent=info, grandparent=.git)
            p.parent()
                .and_then(|pp| pp.file_name())
                .and_then(|n| n.to_str())
                == Some("info")
                && p.parent()
                    .and_then(|pp| pp.parent())
                    .and_then(|g| g.file_name())
                    .and_then(|n| n.to_str())
                    == Some(".git")
        }
        _ => false,
    }
}

/// Background-worker result receivers drained each iteration of the run loop.
struct WorkerRx {
    media: std::sync::mpsc::Receiver<MediaResult>,
    kitty: std::sync::mpsc::Receiver<KittyResult>,
    md_img: std::sync::mpsc::Receiver<MdImageResult>,
    md_remote: std::sync::mpsc::Receiver<RemoteFetch>,
    md_enc: std::sync::mpsc::Receiver<MdEncodeResult>,
    ignored: std::sync::mpsc::Receiver<IgnoredResult>,
    status: std::sync::mpsc::Receiver<StatusResult>,
    fileop: std::sync::mpsc::Receiver<FileOpResult>,
}

fn run(
    terminal: &mut ratatui::DefaultTerminal,
    app: &mut App,
    mut resp_rx: UnboundedReceiver<ResizeResult>,
    rx: WorkerRx,
) -> Result<()> {
    // File watching: auto-update the tree/git status on a change under the current root.
    // notify's callback is called from a separate thread, so send changes to the run loop over a
    // std channel.
    // The channel's bool = "whether an ignore rule (.gitignore / .git/info/exclude) changed."
    // `.git/*.lock` churn from an external git operation is also a reload target
    // (classify_fs_paths — konoma is lock-free, so no self-feedback loop occurs).
    // The channel's Vec<PathBuf> = candidate changed paths for follow mode (excluding under .git).
    let (fs_tx, fs_rx) = std::sync::mpsc::channel::<(bool, Vec<PathBuf>)>();
    let mut watcher = notify::recommended_watcher(move |res: notify::Result<notify::Event>| {
        if let Ok(ev) = res {
            // Events that aren't a content change (Linux inotify's open/read notifications) are
            // filtered out right here (is_content_event). Both watches (recursive root + the
            // non-recursive extra/`.git` watch) share this one callback, so filtering here covers
            // every path.
            if !is_content_event(&ev.kind) {
                return;
            }
            let (meaningful, ignore_rules) = classify_fs_paths(&ev.paths);
            if meaningful {
                let _ = fs_tx.send((ignore_rules, follow_candidates(&ev.paths)));
            }
        }
    })
    .ok();
    let mut watched_root: Option<PathBuf> = None;
    rewatch(watcher.as_mut(), &mut watched_root, &app.tab.root);
    // Secondary watch: a file shown outside the tree root (a global-bookmark preview, or the repo-wide
    // git view when the root is a repo subdirectory) is not covered by the recursive root watch, so its
    // external/agent edits would never refresh. Watch its directory too (see `App::out_of_root_watch_dir`).
    let mut watched_extra: Option<PathBuf> = None;
    // When root is a subdirectory of a repo — or root is a *linked worktree* (`git worktree add`),
    // whose own `HEAD`/`index` live under the main repo's `.git/worktrees/<name>/`, entirely outside
    // the worktree's own checkout — the git directory falls outside the recursive watch. Watch it
    // non-recursively so external git operations (a commit that doesn't touch working files / an
    // external checkout) are picked up (`App::git_dir_watch`). When root *is* the repo root, this is
    // already covered by the recursive watch, so it's None.
    let mut watched_git: Option<PathBuf> = None;

    // Loading: warm the code grammar in the background and notify the run loop of completion over
    // this channel.
    // Both indicator/progressive keep the UI unblocked (the spinner keeps spinning), and swap in
    // the colored version on completion.
    let (hl_tx, hl_rx) = std::sync::mpsc::channel::<()>();

    // Follow mode's switch debounce: even when an agent rewrites several files fast, view
    // switching (jumping across files) is at least this interval apart = the screen doesn't
    // bounce around and stays glanceable.
    // The most recent pending target (latest-wins) is picked up once the dwell period ends.
    // Reloading the same file is unlimited (a separate path).
    const FOLLOW_MIN_DWELL: Duration = Duration::from_millis(1000);
    let mut pending_follow: Option<PathBuf> = None;
    let mut last_follow_jump: Option<std::time::Instant> = None;

    // fs events produced by an in-progress file operation (a bulk write we caused ourselves)
    // aren't processed on the spot — they're accumulated and applied only once after the
    // operation finishes (should_defer_fs_events below).
    let mut deferred_fs = false;
    let mut deferred_ignore_rules = false;

    let mut needs_redraw = true;
    loop {
        if needs_redraw {
            terminal.draw(|frame| ui::render(frame, app))?;
            needs_redraw = false;
            // On a frame where an inline image's (kitty unicode placeholder) display position
            // moved, do a full redraw of the terminal to clean up the leftover debris at the old
            // position. A placeholder row is a "string that encodes the image ID into the
            // foreground color" printed directly onto the terminal grid, but since ratatui's
            // diff-based rendering doesn't resend blank→blank, when the image moves (via scroll,
            // etc.) the old ID row is left behind as a colored bar (reported on real Ghostty as a
            // blue/pink bar — the color changes each time the ID changes).
            if app.take_md_overlay_moved() {
                terminal.clear()?;
                terminal.draw(|frame| ui::render(frame, app))?;
            }
        }

        // Waiting on heavy code highlighting (the first time for a cold language): offload the
        // grammar compile to a separate thread so the UI isn't blocked.
        // indicator spins a centered spinner, progressive keeps showing plain text, and either
        // swaps in the coloring on completion.
        if let Some((ext, path)) = app.take_warm_job() {
            let tx = hl_tx.clone();
            std::thread::spawn(move || {
                preview::code::warm_file(&ext, &path);
                let _ = tx.send(());
            });
        }

        // Wait for input (with a timeout). Even during the timeout, keep picking up worker results
        // and file changes.
        // A guard against holding a key down: with 1 event = 1 draw, if drawing is heavy, input
        // piles up and "it keeps scrolling even after you release the key." **Process all pending
        // events in a batch, then draw exactly once** (converge to the final state).
        // While a GIF is playing, wake up by the next frame's deadline (≤100ms) and advance the
        // frame smoothly (whichever is sooner between the full-screen and Markdown-inline next
        // frame deadlines).
        // While waiting on a separate thread's media load too, wake up frequently so the result
        // can be applied right away.
        let poll_timeout =
            if app.is_media_loading() || app.md_images_loading() || app.kitty_build_pending() {
                // While waiting on a separate thread (media/kitty build), wake up frequently and
                // apply the result right away.
                Duration::from_millis(16)
            } else {
                app.gif_poll_timeout()
                    .into_iter()
                    .chain(app.md_gif_poll_timeout())
                    .min()
                    .unwrap_or(Duration::from_millis(100))
            };
        if event::poll(poll_timeout)? {
            let mut quit = false;
            loop {
                let ev = event::read()?;
                match ev {
                    Event::Key(key) if key.kind == KeyEventKind::Press => {
                        // Don't bring down the TUI on a recoverable failure during key handling
                        // (fs/git operations: refresh/rebuild_tree/paste/delete/rename etc.) —
                        // design principle #3, "never crash."
                        // handle_key touches neither terminal control nor drawing nor
                        // initialization, only App state, so every Err returned here is
                        // recoverable. Don't end run() outright with `?`, and don't swallow it
                        // either — show it to the user via flash and keep going (the truly fatal
                        // `?`s for drawing/terminal control stay in the body of run()).
                        let res = handle_key(app, key);
                        if resolve_key_result(app, res) {
                            quit = true;
                            break;
                        }
                        needs_redraw = true;
                    }
                    Event::Resize(_, _) => needs_redraw = true,
                    // A file drag & drop: the terminal delivers the path as a paste → receive it
                    // and route it into copy/move.
                    // But ignore it (don't let it interrupt) while a dialog/modal/overlay is shown (#13).
                    Event::Paste(s) if paste_accepted(app.surface()) => {
                        app.handle_paste(s);
                        needs_redraw = true;
                    }
                    _ => {}
                }
                // Keep processing if another event can be taken immediately (otherwise break out to draw).
                if !event::poll(Duration::from_millis(0))? {
                    break;
                }
            }
            if quit {
                break;
            }
        }

        // External editor request (`e`): suspend the TUI and launch synchronously, then restore +
        // reload the preview when it exits.
        // When opened from the preview, open the editor at the currently displayed line (line).
        if let Some((path, line)) = app.take_pending_edit() {
            run_editor(terminal, app, &path, line)?;
            needs_redraw = true;
        }

        // External git tool request (`O`): launch the configured git.tool (default lazygit)
        // synchronously in the repo workdir.
        if app.take_launch_git_tool() {
            run_git_tool(terminal, app)?;
            // The external tool may have changed the working tree/git state → re-fetch the listing,
            // git status, and derived views
            // (symmetric with run_editor's restore calling reload_preview. Prevents the Git view's
            // git_view_entries from going stale — #4).
            let _ = app.refresh();
            needs_redraw = true;
        }

        // Warm-up complete: re-render to swap in the colored version (the grammar is already warm,
        // so it's instant).
        while hl_rx.try_recv().is_ok() {
            app.clear_highlight_pending();
            needs_redraw = true;
        }

        // While the centered spinner is shown (waiting on code highlighting / a separate thread
        // loading SVG or GIF), advance it a frame on every waiting tick. While loading, poll is
        // 16ms, so it spins smoothly.
        if (app.is_highlight_pending() && app.loading_is_indicator())
            || app.is_media_loading()
            || app.busy_indicator_active()
        {
            app.tick_spinner();
            needs_redraw = true;
        }

        // Apply the re-encode result(s) from the worker (all of them, if there are several).
        while let Ok(resp) = resp_rx.try_recv() {
            if app.apply_image_resize(resp) {
                needs_redraw = true;
            }
        }

        // Apply the separate thread's media load (SVG/GIF) completion(s) (all of them, if there
        // are several; discard stale generations).
        while let Ok(result) = rx.media.try_recv() {
            if app.apply_media(result) {
                needs_redraw = true;
            }
        }

        // Apply the separate thread's kitty image build (zoom/pan resize+compress) completion
        // (only the latest generation is applied).
        while let Ok(result) = rx.kitty.try_recv() {
            if app.apply_kitty(result) {
                needs_redraw = true;
            }
        }

        // Apply the inline Markdown image decode completion(s) (all of them, if there are several).
        while let Ok(result) = rx.md_img.try_recv() {
            if app.apply_md_image(result) {
                needs_redraw = true;
            }
        }

        // Apply a remote Markdown image's download completion (invalidate md_cache and re-layout).
        while let Ok(result) = rx.md_remote.try_recv() {
            if app.apply_remote_fetch(result) {
                needs_redraw = true;
            }
        }

        // Apply the inline Markdown image encode completion(s) (a separate worker; all of them, if
        // there are several).
        while let Ok(result) = rx.md_enc.try_recv() {
            if app.apply_md_encode(result) {
                needs_redraw = true;
            }
        }

        // Apply the separate thread's git ignored (ignore set) computation completion(s) (all of
        // them, if there are several; discard stale generations).
        // Re-render since applying it makes the dimmed display (dim for gitignore-excluded
        // entries) appear.
        while let Ok(result) = rx.ignored.try_recv() {
            if app.apply_ignored(result) {
                needs_redraw = true;
            }
        }

        // Apply the separate thread's `git status` completion(s) (all of them, if there are
        // several; discard stale generations).
        // Re-render since applying it updates the tree's change marker/branch name.
        while let Ok(result) = rx.status.try_recv() {
            if app.apply_statuses(result) {
                needs_redraw = true;
            }
        }

        // Apply the separate thread's file operation (copy/move/duplicate/delete) completion.
        while let Ok(result) = rx.fileop.try_recv() {
            if app.apply_file_op(result) {
                needs_redraw = true;
            }
        }

        // GIF animation: once the current frame's display time has elapsed, advance to the next
        // frame (swap image_src → the next render's prepare_image rebuilds → worker re-encodes →
        // applied by the branch above).
        if app.advance_gif_if_due() {
            needs_redraw = true;
        }
        // Inline Markdown GIF: likewise advance each entry independently (swap decoded → the next
        // render's ensure_md_image sees the key mismatch and requests a re-encode → applied by the
        // md_enc branch).
        if app.advance_md_gifs_if_due() {
            needs_redraw = true;
        }

        // Pick up file changes and auto-update (a burst is coalesced into one).
        // If even one event changed an ignore rule (.gitignore / .git/info/exclude), also rebuild
        // the heavy ignored set. Otherwise just update the cheap statuses+branch.
        let mut fs_changed = false;
        let mut ignore_rules_changed = false;
        // The paths that changed in this burst (the watcher side sends them excluding under
        // `.git`). Empty = either `.git` only or unknown (including exceeding the cap), in which
        // case `refresh_fs_changed` errs safe = also reloads the preview.
        // De-duplication is a hash lookup (O(1)) + capped (BurstPaths) = the fix for a bug where
        // Vec::contains's linear scan (O(N²)) froze the UI for minutes when an agent generated a
        // huge number of files (see MAX_BURST_PATHS).
        let mut burst = BurstPaths::default();
        // While one of konoma's own background file operations (copy/move/duplicate/delete) is in
        // progress, don't react to the huge number of watcher events that operation produces
        // (running refresh_fs_changed on every burst for a copy of ~10,000 entries would occupy
        // the run loop, so key input never gets processed and the app looks frozen to the user).
        // Accumulate them and apply only once after the operation finishes
        // (App::should_defer_fs_events — apply_file_op already calls refresh() on completion, so
        // nothing is missed).
        let defer_fs = app.should_defer_fs_events();
        while let Ok((b, paths)) = fs_rx.try_recv() {
            if defer_fs {
                deferred_fs = true;
                deferred_ignore_rules |= b;
                continue;
            }
            fs_changed = true;
            ignore_rules_changed |= b;
            // Follow mode: record a valid target into the session list (the population n/N reviews)
            // while also setting the last one as the pending target (latest-wins). An invalid path
            // doesn't consume a dwell slot.
            // On a burst that exceeds the cap (overflowed), push always returns false, so from
            // then on this just drains the channel without doing any per-path work (follow bookkeeping).
            for p in paths {
                if burst.push(&p) && app.follow_enabled() && app.follow_note_change(&p) {
                    pending_follow = Some(p);
                }
            }
        }
        let changed_paths = burst.finish().unwrap_or_default();
        // Apply the accumulated burst exactly once, on the first loop after the operation finishes
        // (defer is lifted).
        // changed_paths stays empty = "which paths changed is unknown" = err safe (also reload the preview).
        if !defer_fs && deferred_fs {
            deferred_fs = false;
            fs_changed = true;
            ignore_rules_changed |= deferred_ignore_rules;
            deferred_ignore_rules = false;
        }
        // Build-churn guard: when every path in the burst is gitignored (and the ignore rules
        // themselves haven't changed), skip the whole tree rebuild that a write to target/ or
        // node_modules/ alone would otherwise trigger (wasted work).
        if fs_changed && !app.fs_burst_is_build_churn(&changed_paths, ignore_rules_changed) {
            // In addition to the listing + git status, refresh_fs() also uniformly re-fetches the
            // active derived view
            // (in Preview mode, reload the current preview → fixes the known bug where the preview
            //  stayed stale after an external-editor edit. In the Git view, update the change listing).
            let _ = app.refresh_fs_changed(ignore_rules_changed, &changed_paths);
            needs_redraw = true;
        }
        // Follow's switch judgment (outside the drain = every loop). A target arriving during
        // dwell is held pending, and it jumps once, to the latest at the moment dwell ends. A
        // change to the file already shown doesn't need a switch (the refresh_fs reload above
        // already keeps up).
        if pending_follow.is_some() && !app.follow_enabled() {
            pending_follow = None; // once disabled, discard the pending target too
        }
        if let Some(p) = pending_follow.clone() {
            if app.tab.preview_path.as_deref() == Some(p.as_path()) {
                pending_follow = None;
            } else if last_follow_jump.is_none_or(|t| t.elapsed() >= FOLLOW_MIN_DWELL) {
                pending_follow = None;
                app.follow_jump(&p);
                last_follow_jump = Some(std::time::Instant::now());
                needs_redraw = true;
            }
        }

        // Re-point the watch target when root changes (h/l, tab switching, etc.).
        if watched_root.as_deref() != Some(app.tab.root.as_path()) {
            rewatch(watcher.as_mut(), &mut watched_root, &app.tab.root);
        }
        // For a file shown outside root (a bookmark target / the repo-wide git view), also watch
        // its parent directory.
        // Becomes None — and the watch is dropped — once the displayed file changes / it returns
        // inside root / it returns to the tree.
        let want_extra = app.out_of_root_watch_dir();
        if watched_extra.as_deref() != want_extra.as_deref() {
            set_extra_watch(watcher.as_mut(), &mut watched_extra, want_extra.as_deref());
        }
        // When root is a subdirectory of a repo, or is a linked worktree whose own `HEAD`/`index`
        // live under the main repo's `.git/worktrees/<name>/`, watch that git directory
        // non-recursively to catch external git operations.
        let want_git = app.git_dir_watch();
        if watched_git.as_deref() != want_git.as_deref() {
            set_extra_watch(watcher.as_mut(), &mut watched_git, want_git.as_deref());
        }
    }
    Ok(())
}

/// Re-point the watcher at `root`. Failure is not fatal (auto-refresh just stops working).
fn rewatch(
    watcher: Option<&mut notify::RecommendedWatcher>,
    watched: &mut Option<PathBuf>,
    root: &std::path::Path,
) {
    use notify::{RecursiveMode, Watcher};
    let Some(w) = watcher else {
        return;
    };
    if let Some(old) = watched.take() {
        let _ = w.unwatch(&old);
    }
    if w.watch(root, RecursiveMode::Recursive).is_ok() {
        *watched = Some(root.to_path_buf());
    }
}

/// Add/replace/remove the **secondary, non-recursive** watch for a file shown outside the tree root
/// (`App::out_of_root_watch_dir`). `want=None` removes it. Non-recursive so it never overlaps the
/// recursive root watch (no duplicate events). Failure is non-fatal (that file just won't auto-refresh).
fn set_extra_watch(
    watcher: Option<&mut notify::RecommendedWatcher>,
    watched: &mut Option<PathBuf>,
    want: Option<&std::path::Path>,
) {
    use notify::{RecursiveMode, Watcher};
    let Some(w) = watcher else {
        return;
    };
    if let Some(old) = watched.take() {
        let _ = w.unwatch(&old);
    }
    if let Some(dir) = want {
        if w.watch(dir, RecursiveMode::NonRecursive).is_ok() {
            *watched = Some(dir.to_path_buf());
        }
    }
}

/// Edit `path` in an external editor. Temporarily suspends the TUI (drops raw/alt screen), runs the
/// editor **synchronously**, then restores the screen on return. The command is resolved from the
/// `[editor]` config (per-extension → default → $VISUAL$EDITOR → vim). Both terminal-grabbing TUI
/// editors (vim etc.) and GUI editors (`code -w`) take the same path (both block and wait).
///
/// On return, it **explicitly resets the terminal input modes an editor (especially vim) may leave
/// enabled** (kitty keyboard protocol / bracketed paste / mouse reporting), and further **drains and
/// discards leftover input bytes (terminal-query responses, etc.)** to recover input-decoder sync.
/// Without this, keys can become garbled or stop working after return (ratatui::init assumes legacy
/// input, so we realign the state).
fn run_editor(
    terminal: &mut ratatui::DefaultTerminal,
    app: &mut App,
    path: &std::path::Path,
    line: Option<usize>,
) -> Result<()> {
    let argv = app.cfg.editor.resolve(path, line);
    let Some((prog, args)) = argv.split_first() else {
        return Ok(());
    };
    let cwd = path.parent().unwrap_or(path).to_path_buf();
    let status = run_external(terminal, app, prog, args, &cwd)?;
    match status {
        Ok(_) => app.reload_preview(), // apply the rewritten result (drop the cache + re-open the window)
        Err(e) => {
            app.flash = Some(format!(
                "{}{e}",
                i18n::tr(app.lang, crate::i18n::Msg::EditorFailed)
            ))
        }
    }
    Ok(())
}

/// Launch the configured `git.tool` (default lazygit) synchronously in the repo workdir. The command
/// is split on whitespace into prog + args. The cwd is the workdir discovered from app.tab.root via git
/// (or root if none). A launch failure (not installed, etc.) is reported as an error via flash.
fn run_git_tool(terminal: &mut ratatui::DefaultTerminal, app: &mut App) -> Result<()> {
    let tmpl = app.cfg.git.tool.trim();
    let tmpl = if tmpl.is_empty() { "lazygit" } else { tmpl };
    let mut parts = tmpl.split_whitespace().map(|s| s.to_string());
    let Some(prog) = parts.next() else {
        return Ok(());
    };
    let args: Vec<String> = parts.collect();
    let cwd = git_workdir(&app.tab.root);
    let status = run_external(terminal, app, &prog, &args, &cwd)?;
    if let Err(e) = status {
        app.flash = Some(format!(
            "{}{prog}: {e}",
            i18n::tr(app.lang, crate::i18n::Msg::GitToolFailed)
        ));
    }
    Ok(())
}

/// Return the workdir of the repo containing `root` (when the git feature is enabled). Returns root itself if none is found.
#[cfg(feature = "git")]
fn git_workdir(root: &std::path::Path) -> PathBuf {
    git2::Repository::discover(root)
        .ok()
        .and_then(|r| r.workdir().map(|w| w.to_path_buf()))
        .unwrap_or_else(|| root.to_path_buf())
}

#[cfg(not(feature = "git"))]
fn git_workdir(root: &std::path::Path) -> PathBuf {
    root.to_path_buf()
}

/// Generic helper that launches an arbitrary external command **synchronously** in `cwd`. Suspends the
/// TUI → launches → restores, returning the process exit status (an io::Error on launch failure). Shared
/// by the editor and git tool. See `run_editor` for suspend/restore details (alternate screen, input-mode reset, draining leftover bytes).
fn run_external(
    terminal: &mut ratatui::DefaultTerminal,
    app: &mut App,
    prog: &str,
    args: &[String],
    cwd: &std::path::Path,
) -> Result<std::io::Result<std::process::ExitStatus>> {
    use crossterm::event::{DisableMouseCapture, PopKeyboardEnhancementFlags};
    use crossterm::execute;
    use crossterm::terminal::{
        disable_raw_mode, enable_raw_mode, BeginSynchronizedUpdate, EndSynchronizedUpdate,
        EnterAlternateScreen,
    };

    // --- Suspend the TUI ---
    // **Don't leave** the alternate screen (only disable raw mode). vim etc. enter the alternate
    // screen themselves (smcup), but since the terminal is already alt, no screen switch occurs,
    // preventing the plain terminal screen from flashing briefly at launch
    // (a common Ratatui-forum idiom). Since vim always returns to the primary screen with rmcup on
    // exit, re-enter via EnterAlternateScreen on the restore side.
    disable_raw_mode()?;

    // --- Run the external command synchronously (inherit stdio and block) ---
    let status = std::process::Command::new(prog)
        .args(args)
        .current_dir(cwd)
        .status();

    // --- Restore the TUI ---
    // Redraw immediately right after returning to the alternate screen, and further make the
    // "switch + redraw" appear atomically via synchronized output (DEC 2026).
    // This eliminates the plain-terminal/blank-screen flash between the external tool exiting and
    // konoma restoring (supported terminals only.
    // On unsupported terminals, ?2026 is ignored and only the immediate redraw takes effect =
    // harmless). Treat clear/draw as best-effort since they're cosmetic,
    // and always send EndSynchronizedUpdate even on error (so the terminal doesn't get stuck
    // waiting for the sync to end).
    enable_raw_mode()?;
    let _ = execute!(std::io::stdout(), BeginSynchronizedUpdate);
    execute!(std::io::stdout(), EnterAlternateScreen)?;
    let _ = terminal.clear(); // discard ratatui's previous buffer to force a full redraw (clears the external tool's leftovers)
    let _ = terminal.draw(|frame| ui::render(frame, app)); // draw immediately right after restoring (don't delay it until the next loop)
    let _ = execute!(std::io::stdout(), EndSynchronizedUpdate);

    // Legacy-izing the input mode + draining leftover bytes can happen after the screen is
    // restored (invisible).
    // Pop the kitty keyboard protocol and disable mouse reporting (left by the external tool).
    // konoma itself uses bracketed paste (to receive D&D), so **re-enable it** after cleaning up.
    let _ = execute!(
        std::io::stdout(),
        PopKeyboardEnhancementFlags,
        DisableMouseCapture,
        crossterm::event::EnableBracketedPaste,
    );
    // Drain and discard leftover input (terminal-query responses, extra keys) for a short time to
    // recover the decoder's sync.
    while event::poll(Duration::from_millis(10)).unwrap_or(false) {
        let _ = event::read();
    }
    Ok(status)
}

/// File operations from the Visual surface (Space→d/r/c/x …) first commit the range to the selection before running.
/// This absorbs, via the keymap, the old direct keys' (D/R/Y/X) behavior of calling `exit_visual_commit()` before acting.
fn commit_visual_if_needed(app: &mut App, sfc: Surface) {
    if sfc == Surface::Visual {
        app.exit_visual_commit();
    }
}

/// Whether the surface may accept a D&D paste (a file path the terminal delivers via Event::Paste).
/// While a dialog / confirm modal / any overlay (Help/Sort/Bookmarks/Info/Git/Visual …) is shown it returns
/// `false` to prevent interference. Text-input surfaces pass it through to capture as text, and only the basic
/// full-screen surfaces (Tree / Preview), where a drop is meaningful, accept it (actual drop handling is Tree-only inside `App::handle_paste`).
fn paste_accepted(sfc: Surface) -> bool {
    sfc.is_text_input()
        || matches!(
            sfc,
            Surface::Tree | Surface::PreviewText | Surface::PreviewImage
        )
}

/// Map `SortSet(key)` to the key char used to apply it through the existing `sort_menu_key`.
fn sort_key_char(k: SortKey) -> char {
    match k {
        SortKey::Name => 'n',
        SortKey::Size => 's',
        SortKey::Modified => 'm',
        SortKey::Ext => 'e',
    }
}

/// Map `Navigate(Motion)` to a concrete move/scroll **per surface** (§1.1).
/// A missing arm means j/k do nothing on that surface, so this interpretation table is pinned in tandem with the keymap tests.
fn dispatch_navigate(app: &mut App, sfc: Surface, m: Motion) {
    match sfc {
        Surface::Tree | Surface::Visual => match m {
            Motion::Up => app.tree_prev(),
            Motion::Down => app.tree_next(),
            Motion::Top => app.tree_first(),
            Motion::Bottom => app.tree_last(),
            Motion::PageUp => app.tree_page(-1),
            Motion::PageDown => app.tree_page(1),
            Motion::HalfUp => app.tree_half_page(-1),
            Motion::HalfDown => app.tree_half_page(1),
            Motion::Left | Motion::Right | Motion::LineHome | Motion::LineEnd => {}
        },
        // The normal text/code preview, and its line-selection (visual) submode.
        // When windowed, preview_scroll/to_top etc. move the line cursor (the range grows while
        // visually selecting).
        // While the focused inline mermaid diagram is **zoomed**, assign hjkl/arrows to panning
        // the diagram instead
        // (returning to 1x restores normal scrolling — the feel of an embedded map).
        Surface::PreviewText | Surface::PreviewTextVisual if app.fence_pan_motion(m) => {}
        Surface::PreviewText | Surface::PreviewTextVisual => match m {
            Motion::Up => app.preview_scroll(-1),
            Motion::Down => app.preview_scroll(1),
            Motion::Top => app.preview_to_top(),
            Motion::Bottom => app.preview_to_bottom(),
            Motion::PageUp => app.preview_page(-1),
            Motion::PageDown => app.preview_page(1),
            Motion::HalfUp => app.preview_half_page(-1),
            Motion::HalfDown => app.preview_half_page(1),
            Motion::Left => app.preview_col_move(-1),
            Motion::Right => app.preview_col_move(1),
            Motion::LineHome => app.preview_col_home(),
            Motion::LineEnd => app.preview_col_end(),
        },
        Surface::PreviewImage => match m {
            Motion::Up => app.image_pan(0.0, -1.0),
            Motion::Down => app.image_pan(0.0, 1.0),
            Motion::Left => app.image_pan(-1.0, 0.0),
            Motion::Right => app.image_pan(1.0, 0.0),
            _ => {}
        },
        // Table (csv/tsv): hjkl = move the cell cursor / g·G = first/last row / 0·$ = first/last
        // column / paging.
        Surface::PreviewTable => match m {
            Motion::Up => app.table_cursor_move(-1, 0),
            Motion::Down => app.table_cursor_move(1, 0),
            Motion::Left => app.table_cursor_move(0, -1),
            Motion::Right => app.table_cursor_move(0, 1),
            Motion::Top => app.table_row_to(false),
            Motion::Bottom => app.table_row_to(true),
            Motion::PageUp => app.table_page(-1),
            Motion::PageDown => app.table_page(1),
            Motion::HalfUp => app.table_half_page(-1),
            Motion::HalfDown => app.table_half_page(1),
            Motion::LineHome => app.table_col_to(false),
            Motion::LineEnd => app.table_col_to(true),
        },
        #[cfg(feature = "git")]
        Surface::PreviewGitDiff => match m {
            Motion::Up => app.preview_scroll(-1),
            Motion::Down => app.preview_scroll(1),
            Motion::Top => app.preview_to_top(),
            Motion::Bottom => app.preview_to_bottom(),
            Motion::PageUp => app.preview_page(-1),
            Motion::PageDown => app.preview_page(1),
            Motion::HalfUp => app.preview_half_page(-1),
            Motion::HalfDown => app.preview_half_page(1),
            Motion::Left => app.preview_hscroll(-4),
            Motion::Right => app.preview_hscroll(4),
            Motion::LineHome => app.preview_hscroll_home(),
            Motion::LineEnd => app.preview_hscroll_end(),
        },
        #[cfg(feature = "git")]
        Surface::GitDetail => match m {
            Motion::Up => app.git_detail_scroll_by(-1),
            Motion::Down => app.git_detail_scroll_by(1),
            Motion::Top => app.git_detail_scroll_to(false),
            Motion::Bottom => app.git_detail_scroll_to(true),
            Motion::PageUp => app.git_detail_scroll_by(-20),
            Motion::PageDown => app.git_detail_scroll_by(20),
            Motion::HalfUp => app.git_detail_scroll_by(-10),
            Motion::HalfDown => app.git_detail_scroll_by(10),
            Motion::Left => app.git_detail_hscroll_by(-4),
            Motion::Right => app.git_detail_hscroll_by(4),
            Motion::LineHome => app.git_detail_hscroll_home(),
            Motion::LineEnd => app.git_detail_hscroll_end(),
        },
        #[cfg(feature = "git")]
        Surface::GitChanges => match m {
            Motion::Up => app.git_view_move(-1),
            Motion::Down => app.git_view_move(1),
            Motion::Top => app.git_view_move(i32::MIN),
            Motion::Bottom => app.git_view_move(i32::MAX),
            _ => {}
        },
        #[cfg(feature = "git")]
        Surface::GitLog => match m {
            Motion::Up => app.git_log_move(-1),
            Motion::Down => app.git_log_move(1),
            Motion::Top => app.git_log_move(i32::MIN),
            Motion::Bottom => app.git_log_move(i32::MAX),
            _ => {}
        },
        #[cfg(feature = "git")]
        Surface::GitGraph => match m {
            Motion::Up => app.git_graph_move(-1),
            Motion::Down => app.git_graph_move(1),
            Motion::Top => app.git_graph_move(i32::MIN),
            Motion::Bottom => app.git_graph_move(i32::MAX),
            _ => {}
        },
        #[cfg(feature = "git")]
        Surface::GitGraphPicker => match m {
            Motion::Up => app.git_graph_picker_move(-1),
            Motion::Down => app.git_graph_picker_move(1),
            Motion::Top => app.git_graph_picker_jump(true),
            Motion::Bottom => app.git_graph_picker_jump(false),
            _ => {}
        },
        #[cfg(feature = "git")]
        Surface::GitBranches => match m {
            Motion::Up => app.git_branch_move(-1),
            Motion::Down => app.git_branch_move(1),
            Motion::Top => app.git_branch_move(i32::MIN),
            Motion::Bottom => app.git_branch_move(i32::MAX),
            _ => {}
        },
        #[cfg(feature = "git")]
        Surface::GitWorktrees => match m {
            Motion::Up => app.git_worktree_move(-1),
            Motion::Down => app.git_worktree_move(1),
            Motion::Top => app.git_worktree_move(i32::MIN),
            Motion::Bottom => app.git_worktree_move(i32::MAX),
            _ => {}
        },
        Surface::Bookmarks => match m {
            // j/k only, matching legacy behavior (g/G/Home/End are unassigned).
            Motion::Up => app.bookmark_list_move(-1),
            Motion::Down => app.bookmark_list_move(1),
            _ => {}
        },
        Surface::Tabs => match m {
            Motion::Up => app.tab_list_move(-1),
            Motion::Down => app.tab_list_move(1),
            _ => {}
        },
        Surface::Outline => match m {
            Motion::Up => app.outline_move(-1),
            Motion::Down => app.outline_move(1),
            Motion::Top => {
                let d = -(app.outline_sel() as i32);
                app.outline_move(d);
            }
            Motion::Bottom => {
                let d = (app.md_outline().len() as i32 - 1) - app.outline_sel() as i32;
                app.outline_move(d);
            }
            _ => {}
        },
        // Table-cell full-text popup: it's likely wrapped long text, so up/down scroll + paging.
        Surface::TableCell => match m {
            Motion::Up => app.table_cell_scroll_by(-1),
            Motion::Down => app.table_cell_scroll_by(1),
            Motion::Top => app.table_cell_scroll_to(false),
            Motion::Bottom => app.table_cell_scroll_to(true),
            Motion::PageUp => app.table_cell_page(-1),
            Motion::PageDown => app.table_cell_page(1),
            _ => {}
        },
        Surface::Help => match m {
            Motion::Up => app.help_scroll_by(-1),
            Motion::Down => app.help_scroll_by(1),
            Motion::Top => app.help_scroll = 0,
            Motion::Bottom => app.help_scroll = u16::MAX,
            _ => {}
        },
        // Sort / Info / fixed text-input surfaces, etc.: Navigate never arrives here (j/k mean
        // something else, or aren't keymap-driven).
        _ => {}
    }
}

/// Central dispatch that runs a resolved `Action`. Only `Quit` requests exit, returning `Ok(true)`.
/// Surface-dependent behavior (motion amount, the q/Esc return target) branches on `sfc` (§5).
fn dispatch_action(app: &mut App, action: Action, sfc: Surface) -> Result<bool> {
    match action {
        Action::Noop => {}
        Action::Navigate(m) => dispatch_navigate(app, sfc, m),
        Action::TabNew => app.tab_new()?,
        Action::TabClose => app.tab_close(),
        Action::TabPrev => app.tab_cycle(-1),
        Action::TabNext => app.tab_cycle(1),
        Action::TabGoto(i) => app.tab_goto(i as usize),
        Action::ToggleHelp => app.toggle_help(),
        Action::CopyPath(kind) => app.copy_path(kind),
        Action::CopyCodeBlock => app.md_copy_focused_code(),
        Action::PasteJump => {
            // `P` is global (inherited on every surface), so it also arrives from Visual. Like the
            // other seven Visual-originated actions
            // (the commit_visual_if_needed call sites in main.rs), commit the in-progress range
            // selection first before acting. Skipping this means is_visual() doesn't look at
            // tab.mode, so even after paste_jump transitions to the full-screen preview, surface()
            // stays Visual, and while looking at the preview, keys keep flowing into the tree's
            // Visual map — an accident.
            commit_visual_if_needed(app, sfc);
            app.paste_jump();
        }
        Action::Quit => {
            // When confirm_quit is ON, open the confirmation dialog and don't quit yet. When OFF,
            // quit immediately.
            if app.request_quit() {
                return Ok(false);
            }
            return Ok(true);
        }
        Action::CloseTabOrQuit => {
            // If there are multiple tabs, close the current one. If it's the last one, the normal
            // quit flow (same as Q).
            if app.tab_count() > 1 {
                app.tab_close();
            } else if app.request_quit() {
                return Ok(false);
            } else {
                return Ok(true);
            }
        }
        Action::FilterStart => app.start_filter(),
        Action::TreeDescend => app.tree_descend()?,
        Action::TreeActivate => app.tree_activate()?,
        Action::TreeLeave => app.tree_leave()?,
        Action::ToggleHidden => app.toggle_hidden()?,
        Action::ToggleInfo => app.toggle_info(),
        Action::RequestEdit => app.request_edit(),
        Action::OpenGitView => app.open_git_view(),
        Action::Refresh => app.refresh()?,
        Action::CyclePathStyle => app.cycle_path_style(),
        Action::OpenSortMenu => app.open_sort_menu(),
        Action::MarkSet => app.start_mark_set(),
        // `'`: instead of the old invisible "waiting to jump" state, open the bookmark list
        // immediately (which-key style).
        Action::MarkJump => app.open_bookmark_list(),
        Action::SetAnchor => app.reanchor_root(),
        Action::ResetAnchor => app.reset_anchor(),
        Action::OpenGitDiffCursor => app.tree_open_git_diff(),
        Action::EnterVisual => app.enter_visual(),
        Action::ToggleSelect => app.toggle_select(),
        Action::ToggleChangedFilter => app.toggle_changed_filter(),
        Action::JumpNextChange => app.jump_changed(1),
        Action::JumpPrevChange => app.jump_changed(-1),
        Action::ToggleFollow => app.toggle_follow(),
        Action::FileCreate => {
            commit_visual_if_needed(app, sfc);
            app.start_create();
        }
        Action::FileRename => {
            // Via Visual, commit the range first. With a selection, batch (numbered template);
            // without one, a single item.
            commit_visual_if_needed(app, sfc);
            if app.has_selection() {
                app.start_batch_rename();
            } else {
                app.start_rename();
            }
        }
        Action::FileDelete => {
            commit_visual_if_needed(app, sfc);
            app.start_delete();
        }
        Action::FileCopy => {
            commit_visual_if_needed(app, sfc);
            app.copy_selection();
        }
        Action::FileCut => {
            commit_visual_if_needed(app, sfc);
            app.cut_selection();
        }
        Action::FilePaste => {
            commit_visual_if_needed(app, sfc);
            app.paste()?;
        }
        Action::FileDuplicate => {
            commit_visual_if_needed(app, sfc);
            app.duplicate_selection()?;
        }
        Action::VisualCommit => app.exit_visual_commit(),
        Action::VisualSelectSiblings => app.visual_select_scope(false),
        Action::VisualSelectAll => app.visual_select_scope(true),
        Action::PreviewBack => {
            // A git diff preview returns to the Git view. Everything else returns to the tree.
            if app.is_git_diff_preview() {
                app.close_git_diff();
            } else {
                app.back_to_tree();
            }
        }
        Action::SearchStart => app.start_search(),
        Action::SearchNext => app.search_next(1),
        Action::SearchPrev => app.search_next(-1),
        Action::PreviewEnterVisual => app.preview_enter_visual(false),
        Action::PreviewEnterVisualLine => app.preview_enter_visual(true),
        Action::PreviewCopySelection => app.preview_copy_selection(),
        Action::PreviewCopySelectionRef => app.preview_copy_selection_ref(),
        Action::PreviewExitVisual => app.preview_exit_visual(),
        Action::ToggleMarkdownRaw => app.toggle_md_raw(),
        Action::LinkFocusNext => app.md_focus_move(1),
        Action::LinkFocusPrev => app.md_focus_move(-1),
        Action::LinkOpen => app.md_activate_focused()?,
        Action::OpenLinkNewTab => app.md_open_focused_link_new_tab()?,
        Action::OpenInNewTab => app.tab_new_from_selection()?,
        Action::ImageZoomIn => app.image_zoom_by(1.25),
        Action::ImageZoomOut => app.image_zoom_by(1.0 / 1.25),
        Action::ImageZoomReset => app.image_zoom_reset(),
        Action::PdfNextPage => app.pdf_next_page(),
        Action::PdfPrevPage => app.pdf_prev_page(),
        Action::PreviewFileNext => app.preview_jump_file(1),
        Action::PreviewFilePrev => app.preview_jump_file(-1),
        Action::TableCopy(kind) => app.table_copy(kind),
        Action::SortSet(k) => app.sort_menu_key(sort_key_char(k))?,
        Action::SortToggleReverse => app.sort_menu_key('r')?,
        Action::SortToggleDirsFirst => app.sort_menu_key('.')?,
        Action::ToggleTabList => app.toggle_tab_list(),
        Action::TabListClose => app.tab_list_close_selected(),
        Action::ToggleOutline => app.toggle_outline(),
        Action::BookmarkJump => app.bookmark_list_jump(),
        Action::BookmarkEdit => app.bookmark_list_edit(),
        Action::BookmarkDelete => app.bookmark_list_delete(),
        Action::BookmarkClose => app.close_bookmark_list(),
        Action::InfoClose => app.toggle_info(),
        Action::ToggleTableCell => app.toggle_table_cell_view(),
        #[cfg(feature = "git")]
        Action::GitDiffDiscard => app.git_diff_start_discard(),
        #[cfg(feature = "git")]
        Action::CycleDiffLayout => app.cycle_diff_layout(),
        #[cfg(feature = "git")]
        Action::ToggleFollowDiffScope => app.toggle_follow_diff_scope(),
        #[cfg(feature = "git")]
        Action::GitStage => app.git_view_stage(),
        #[cfg(feature = "git")]
        Action::GitUnstage => app.git_view_unstage(),
        #[cfg(feature = "git")]
        Action::GitStageAll => app.git_view_stage_all(),
        #[cfg(feature = "git")]
        Action::GitUnstageAll => app.git_view_unstage_all(),
        #[cfg(feature = "git")]
        Action::GitDiscard => app.git_view_start_discard(),
        #[cfg(feature = "git")]
        Action::GitCommit => app.start_git_commit(),
        #[cfg(feature = "git")]
        Action::GitWorktreeDiff => app.open_worktree_detail(),
        #[cfg(feature = "git")]
        Action::GitOpenLog => app.open_git_log(),
        #[cfg(feature = "git")]
        Action::GitOpenGraph => app.open_git_graph(),
        #[cfg(feature = "git")]
        Action::GitOpenBranches => app.open_git_branches(),
        #[cfg(feature = "git")]
        Action::GitOpenWorktrees => app.open_git_worktrees(),
        #[cfg(feature = "git")]
        Action::GitLaunchTool => app.launch_git_tool(),
        #[cfg(feature = "git")]
        Action::GitOpenSelectedDiff => {
            if let Some(p) = app.git_view_selected() {
                app.open_git_diff(&p);
            }
        }
        #[cfg(feature = "git")]
        Action::GitOpenDetail => match sfc {
            Surface::GitLog => app.open_git_commit_detail(),
            Surface::GitGraph => app.open_git_graph_detail(),
            _ => {}
        },
        #[cfg(feature = "git")]
        Action::GitGraphSetBase => app.git_graph_set_base(),
        #[cfg(feature = "git")]
        Action::GitGraphClearBase => app.git_graph_clear_base(),
        #[cfg(feature = "git")]
        Action::GitGraphOpenPicker => app.git_graph_open_picker(),
        #[cfg(feature = "git")]
        Action::GitGraphPickerToggle => app.git_graph_picker_toggle(),
        #[cfg(feature = "git")]
        Action::GitGraphPickerAll => app.git_graph_picker_all(),
        #[cfg(feature = "git")]
        Action::GitGraphPickerCurrentOnly => app.git_graph_picker_current_only(),
        #[cfg(feature = "git")]
        Action::GitGraphPickerMoveUp => app.git_graph_picker_reorder(-1),
        #[cfg(feature = "git")]
        Action::GitGraphPickerMoveDown => app.git_graph_picker_reorder(1),
        #[cfg(feature = "git")]
        Action::BranchFilterStart => app.git_branch_start_filter(),
        #[cfg(feature = "git")]
        Action::BranchCheckout => app.checkout_selected_branch()?,
        #[cfg(feature = "git")]
        Action::BranchCreate => app.start_create_branch(),
        #[cfg(feature = "git")]
        Action::BranchDelete => app.start_delete_branch(),
        #[cfg(feature = "git")]
        Action::WorktreeFilterStart => app.git_worktree_start_filter(),
        #[cfg(feature = "git")]
        Action::WorktreeGoto => app.worktree_goto(),
        #[cfg(feature = "git")]
        Action::WorktreeGotoNewTab => app.worktree_goto_new_tab()?,
        #[cfg(feature = "git")]
        Action::WorktreeClose => app.close_git_worktrees(),
        #[cfg(feature = "git")]
        Action::WorktreeShowChanges => app.worktree_show_changes(),
        #[cfg(feature = "git")]
        Action::WorktreeCreate => app.start_create_worktree(),
        #[cfg(feature = "git")]
        Action::GitCopy(kind) => app.git_copy(kind),
        #[cfg(feature = "git")]
        Action::CopyBranchName => app.git_copy_branch_name(),
        #[cfg(feature = "git")]
        Action::GitClose => match sfc {
            Surface::GitDetail => app.close_git_detail(),
            Surface::GitLog => app.close_git_log(),
            Surface::GitGraphPicker => app.git_graph_picker_cancel(),
            Surface::GitGraph => app.close_git_graph(),
            Surface::GitBranches => app.close_git_branches(),
            Surface::GitChanges => app.close_git_view(),
            _ => {}
        },
    }
    Ok(false)
}

/// Key handling for text-input surfaces (filter / search / mark / branch filter / dialog input).
/// Intercepts character and editing keys and does not apply the keymap (requirement 4).
fn handle_text_input(app: &mut App, sfc: Surface, key: KeyEvent) -> Result<bool> {
    let code = key.code;
    let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
    match sfc {
        Surface::DialogInput => match (code, ctrl) {
            (KeyCode::Esc, _) => app.dialog_cancel(),
            (KeyCode::Enter, _) => app.dialog_submit()?,
            (KeyCode::Backspace, _) => app.dialog_input_backspace(),
            (KeyCode::Delete, _) => app.dialog_input_delete(),
            (KeyCode::Left, _) => app.dialog_cursor_left(),
            (KeyCode::Right, _) => app.dialog_cursor_right(),
            (KeyCode::Home, _) => app.dialog_cursor_home(),
            (KeyCode::End, _) => app.dialog_cursor_end(),
            (KeyCode::Char(c), false) => app.dialog_input_push(c),
            _ => {}
        },
        Surface::Filter => match (code, ctrl) {
            (KeyCode::Esc, _) => app.filter_clear(),
            (KeyCode::Enter, _) => app.filter_commit(),
            (KeyCode::Backspace, _) => app.filter_input_backspace(),
            (KeyCode::Down, _) => app.tree_next(),
            (KeyCode::Up, _) => app.tree_prev(),
            (KeyCode::Char(c), false) => app.filter_input_push(c),
            _ => {}
        },
        Surface::Search => match (code, ctrl) {
            (KeyCode::Esc, _) => app.search_clear(),
            (KeyCode::Enter, _) => app.search_commit(),
            (KeyCode::Backspace, _) => app.search_input_backspace(),
            (KeyCode::Char(c), false) => app.search_input_push(c),
            _ => {}
        },
        Surface::Mark => match (code, ctrl) {
            (KeyCode::Esc, _) => app.cancel_mark(),
            (KeyCode::Char(c), false) => app.mark_input(c),
            _ => app.cancel_mark(),
        },
        #[cfg(feature = "git")]
        Surface::BranchFilter => match (code, ctrl) {
            (KeyCode::Esc, _) => app.git_branch_filter_clear(),
            (KeyCode::Enter, _) => app.git_branch_filter_commit(),
            (KeyCode::Backspace, _) => app.git_branch_filter_backspace(),
            (KeyCode::Down, _) => app.git_branch_move(1),
            (KeyCode::Up, _) => app.git_branch_move(-1),
            (KeyCode::Char(c), false) => app.git_branch_filter_push(c),
            _ => {}
        },
        #[cfg(feature = "git")]
        Surface::WorktreeFilter => match (code, ctrl) {
            (KeyCode::Esc, _) => app.git_worktree_filter_clear(),
            (KeyCode::Enter, _) => app.git_worktree_filter_commit(),
            (KeyCode::Backspace, _) => app.git_worktree_filter_backspace(),
            (KeyCode::Down, _) => app.git_worktree_move(1),
            (KeyCode::Up, _) => app.git_worktree_move(-1),
            (KeyCode::Char(c), false) => app.git_worktree_filter_push(c),
            _ => {}
        },
        _ => {}
    }
    Ok(false)
}

/// Key handling for confirm-modal surfaces (delete confirm / drop confirm / rename preview) (requirement 4).
fn handle_modal_confirm(app: &mut App, sfc: Surface, key: KeyEvent) -> Result<bool> {
    match sfc {
        Surface::DialogRenamePreview => match key.code {
            KeyCode::Char('y') | KeyCode::Char('Y') => app.dialog_preview_apply()?,
            KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => app.dialog_cancel(),
            KeyCode::Char('j') | KeyCode::Down => app.dialog_preview_scroll(1),
            KeyCode::Char('k') | KeyCode::Up => app.dialog_preview_scroll(-1),
            _ => {}
        },
        Surface::DialogConfirmDrop => match key.code {
            KeyCode::Char('c') | KeyCode::Char('C') => app.drop_apply(false)?,
            KeyCode::Char('m') | KeyCode::Char('M') => app.drop_apply(true)?,
            KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => app.dialog_cancel(),
            _ => {}
        },
        Surface::DialogConfirmDelete => match key.code {
            KeyCode::Char('y') | KeyCode::Char('Y') => app.dialog_confirm(true)?,
            // `!` = permanent delete (not recoverable). Accepted only during a delete confirmation
            // (allow_permanent).
            KeyCode::Char('!') if app.dialog_allow_permanent() => app.dialog_delete_permanent()?,
            KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => app.dialog_confirm(false)?,
            _ => {}
        },
        // App quit confirmation: y/q/Enter = quit (qq lets you exit quickly) / n/Esc = cancel.
        Surface::DialogConfirmQuit => match key.code {
            KeyCode::Char('y')
            | KeyCode::Char('Y')
            | KeyCode::Char('q')
            | KeyCode::Char('Q')
            | KeyCode::Enter => return Ok(true),
            KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => app.dialog_cancel(),
            _ => {}
        },
        // Bookmark overwrite confirmation: y/Enter = overwrite / n/Esc = cancel.
        Surface::DialogConfirmBookmark => match key.code {
            KeyCode::Char('y') | KeyCode::Char('Y') | KeyCode::Enter => app.dialog_confirm(true)?,
            KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => app.dialog_confirm(false)?,
            _ => {}
        },
        _ => {}
    }
    Ok(false)
}

/// Per-surface fixed handling of Esc (clear search/filter, close overlays, cancel visual …). Always quit=false.
fn handle_esc(app: &mut App, sfc: Surface) -> bool {
    match sfc {
        Surface::Help => app.show_help = false,
        Surface::Visual => app.exit_visual_cancel(),
        Surface::Sort => app.close_sort_menu(),
        Surface::Info => app.toggle_info(),
        Surface::TableCell => app.toggle_table_cell_view(),
        Surface::Bookmarks => app.close_bookmark_list(),
        Surface::Tabs => app.toggle_tab_list(),
        Surface::Outline => app.toggle_outline(),
        Surface::Tree => {
            // Esc with a query clears the filter; without one, clears the selection (legacy tree behavior).
            if app.filter_query().is_some() {
                app.filter_clear();
            } else if app.has_selection() {
                app.clear_selection();
            }
        }
        // Tables also have search, so use the same convention as text/image (previously Esc did
        // nothing here = the search highlight couldn't be cleared, and you couldn't return to the
        // tree either).
        Surface::PreviewText | Surface::PreviewImage | Surface::PreviewTable => {
            // If a search is active, clear it; otherwise return to the tree.
            if app.preview_search_query().is_some() {
                app.search_clear();
            } else {
                app.back_to_tree();
            }
        }
        // Esc while a line is selected clears the selection (doesn't return to the tree).
        Surface::PreviewTextVisual => app.preview_exit_visual(),
        #[cfg(feature = "git")]
        Surface::GitDetail => app.close_git_detail(),
        #[cfg(feature = "git")]
        Surface::GitLog => app.close_git_log(),
        #[cfg(feature = "git")]
        Surface::GitGraph => app.close_git_graph(),
        #[cfg(feature = "git")]
        Surface::GitGraphPicker => app.git_graph_picker_cancel(),
        #[cfg(feature = "git")]
        Surface::GitBranches => {
            // Esc with a query clears the filter; without one, closes it (the same convention as
            // the tree filter).
            if app.git_branch_query().is_empty() {
                app.close_git_branches();
            } else {
                app.git_branch_filter_clear();
            }
        }
        #[cfg(feature = "git")]
        Surface::GitWorktrees => {
            // Esc with a query clears the filter; without one, closes it (same convention as
            // the branches list / tree filter).
            if app.git_worktree_query().is_empty() {
                app.close_git_worktrees();
            } else {
                app.git_worktree_filter_clear();
            }
        }
        #[cfg(feature = "git")]
        Surface::GitChanges => app.close_git_view(),
        #[cfg(feature = "git")]
        Surface::PreviewGitDiff => app.close_git_diff(),
        _ => {}
    }
    false
}

/// Per-surface fixed handling of Enter (tree activate / preview link / confirm in each list).
fn handle_enter(app: &mut App, sfc: Surface) -> Result<bool> {
    match sfc {
        Surface::Tree => app.tree_activate()?,
        Surface::PreviewText => app.md_activate_focused()?,
        Surface::Bookmarks => app.bookmark_list_jump(),
        Surface::Tabs => app.tab_list_activate(),
        Surface::Outline => app.outline_jump(),
        // `Enter` opens the full-cell popup from the table grid, and (the same toggle) closes it
        // again from inside the popup — mirrors `MermaidCaption`'s "Enter: full screen" idiom.
        Surface::PreviewTable | Surface::TableCell => app.toggle_table_cell_view(),
        #[cfg(feature = "git")]
        Surface::GitChanges => {
            if let Some(p) = app.git_view_selected() {
                app.open_git_diff(&p);
            }
        }
        #[cfg(feature = "git")]
        Surface::GitLog => app.open_git_commit_detail(),
        #[cfg(feature = "git")]
        Surface::GitGraph => app.open_git_graph_detail(),
        #[cfg(feature = "git")]
        Surface::GitGraphPicker => app.git_graph_picker_apply(),
        #[cfg(feature = "git")]
        Surface::GitBranches => app.checkout_selected_branch()?,
        #[cfg(feature = "git")]
        Surface::GitWorktrees => app.worktree_goto(),
        _ => {}
    }
    Ok(false)
}

/// Keys with a fixed meaning regardless of surface (arrows = Navigate alias / Esc / Enter / Tab/BackTab = link ops).
/// Returns `Some(quit)` when handled, or `None` if not a fixed key (falls through to keymap resolution). Requirements 3/4.
fn handle_fixed_key(app: &mut App, sfc: Surface, key: KeyEvent) -> Result<Option<bool>> {
    let done = match key.code {
        KeyCode::Up => {
            dispatch_navigate(app, sfc, Motion::Up);
            false
        }
        KeyCode::Down => {
            dispatch_navigate(app, sfc, Motion::Down);
            false
        }
        KeyCode::Left => {
            dispatch_navigate(app, sfc, Motion::Left);
            false
        }
        KeyCode::Right => {
            dispatch_navigate(app, sfc, Motion::Right);
            false
        }
        KeyCode::Home => {
            dispatch_navigate(app, sfc, Motion::Top);
            false
        }
        KeyCode::End => {
            dispatch_navigate(app, sfc, Motion::Bottom);
            false
        }
        KeyCode::Esc => handle_esc(app, sfc),
        KeyCode::Enter => handle_enter(app, sfc)?,
        // Markdown link/checkbox: Tab = next / ⇧Tab = previous (decorated text preview only —
        // while showing the raw source (R), the decorated view's items are stale, so don't move;
        // on other surfaces, swallowed with no effect).
        KeyCode::Tab => {
            if sfc == Surface::PreviewText && !app.is_raw_source() {
                app.md_focus_move(1);
            }
            false
        }
        KeyCode::BackTab => {
            if sfc == Surface::PreviewText && !app.is_raw_source() {
                app.md_focus_move(-1);
            }
            false
        }
        // Markdown checkbox: Space toggles only while focused. With no focus, fall through to
        // the keymap (doesn't steal less's convention of Space = PageDown).
        KeyCode::Char(' ') if sfc == Surface::PreviewText && app.md_focused_task() => {
            app.md_toggle_focused_task();
            false
        }
        // While focused on a <details> summary, Space toggles the collapse (same as Enter).
        KeyCode::Char(' ') if sfc == Surface::PreviewText && app.md_focused_details().is_some() => {
            if let Some(ord) = app.md_focused_details() {
                app.toggle_details(ord);
            }
            false
        }
        _ => return Ok(None),
    };
    Ok(Some(done))
}

/// Key handling (Run2: keymap-driven). Returns `Ok(true)` to request exit. Kept thin, following the §5 flow:
/// fixed text input → confirm modal → which-key leader resolution → per-surface fixed keys → keymap resolution.
/// Mode-specific keys are owned by the keymap (`App::keymaps`) and `dispatch_action`.
fn handle_key(app: &mut App, key: KeyEvent) -> Result<bool> {
    // The previous transient message (flash) is cleared on the next key input.
    app.flash = None;
    let sfc = app.surface();

    if app.follow_enabled() {
        // User's choice (2026-07-23): follow is maximally sticky = within the follow diff, every
        // key except q (which leaves the diff) — scroll/move/n/N/f/layout — keeps follow active.
        // It's released only by "entering a text-input surface / a confirm modal" or "q leaving
        // the follow view." F (ToggleFollow) already turns it off explicitly via dispatch's
        // toggle_follow, so follow_break isn't needed there (= treated as kept here).
        let leaves_follow_view = app.pending_leader.is_none()
            && matches!(
                app.keymaps.resolve(sfc, None, KeyPress::norm(&key)),
                Resolution::Action(Action::PreviewBack)
            );
        if sfc.is_text_input() || sfc.is_modal_confirm() || leaves_follow_view {
            app.follow_break();
        }
    }

    // 1) Fixed surfaces (text input / confirm modal) go to their dedicated handler (no keymap applied — requirement 4).
    if sfc.is_text_input() {
        return handle_text_input(app, sfc, key);
    }
    if sfc.is_modal_confirm() {
        return handle_modal_confirm(app, sfc, key);
    }

    let kp = KeyPress::norm(&key);

    // 2) Waiting on a which-key leader: resolve from leaders (an unknown suffix cancels and does
    // not fall through — §5).
    if let Some(lead) = app.pending_leader.take() {
        return match app.keymaps.resolve(sfc, Some(lead), kp) {
            Resolution::Action(a) => dispatch_action(app, a, sfc),
            _ => Ok(false),
        };
    }

    // 3) Pre-empt surface-independent fixed keys (arrows = Navigate / Esc / Enter / Tab·BackTab) (requirements 3/4).
    if let Some(done) = handle_fixed_key(app, sfc, key)? {
        return Ok(done);
    }

    // 4) Keymap resolution (1 input = 1-2 HashMap lookups — requirement 5).
    match app.keymaps.resolve(sfc, None, kp) {
        Resolution::EnterLeader(id) => {
            // The copy leader (default `y`) always opens the which-key menu. While focused on a
            // code block in decorated Markdown, `c:code block` appears in that menu and is
            // selectable
            // (whichkey_spans switches it in based on surface/focus). Coexists with the existing
            // path-copy n/r/f/p/@.
            app.pending_leader = Some(id);
            Ok(false)
        }
        Resolution::Action(a) => dispatch_action(app, a, sfc),
        Resolution::Unbound => {
            // Bookmark list: a plain letter unbound in the keymap jumps directly as a bookmark name
            // (a-z = local / A-Z = global). q/j/k and global's t/T/F/Q etc. are already resolved
            // above = excluded here.
            if sfc == Surface::Bookmarks && !kp.ctrl {
                if let KeyCode::Char(c) = kp.code {
                    if c.is_ascii_alphabetic() {
                        app.bookmark_jump_letter(c);
                    }
                }
            }
            Ok(false)
        }
    }
}

/// Interpret `handle_key`'s result for the run loop. Returns `true` only when exit is requested.
///
/// Key handling only mutates app state (and does fs/git operations); it never touches terminal control,
/// drawing, or initialization, so every `Err` that reaches here is **recoverable** (e.g. a delete/paste
/// while another terminal removes the cwd makes the internal `refresh()?`/`rebuild_tree()?` fail). Rather
/// than crashing the whole run() or swallowing it, we show it to the user via flash and continue.
/// Unrecoverable failures (terminal control, drawing, initialization) are propagated with `?` in run()
/// itself (they never reach here).
fn resolve_key_result(app: &mut App, result: Result<bool>) -> bool {
    match result {
        Ok(quit) => quit,
        Err(e) => {
            app.flash = Some(format!(
                "{}{e:#}",
                i18n::tr(app.lang, crate::i18n::Msg::OperationFailed)
            ));
            false // recoverable → keep the loop going
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use app::Mode;
    use config::Config;

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

    #[test]
    fn fs_event_classification_reacts_to_git_locks_and_detects_ignore_rules() {
        let pb = |s: &str| vec![PathBuf::from(s)];
        // Also reacts to `.git/*.lock` (meaningful=true). Since konoma is lock-free
        // (--no-optional-locks), this is a signal of an external git operation (a commit, etc.),
        // and swallowing it would let the change marker go stale.
        assert_eq!(
            classify_fs_paths(&pb("/repo/.git/index.lock")),
            (true, false)
        );
        assert_eq!(classify_fs_paths(&pb("/r/.git/HEAD.lock")), (true, false));
        // The `.git` internals themselves (HEAD/refs/index) do react (following an external git
        // operation), but ignored is left alone.
        assert_eq!(classify_fs_paths(&pb("/repo/.git/HEAD")), (true, false));
        assert_eq!(classify_fs_paths(&pb("/repo/.git/index")), (true, false));
        // A normal file change: reacts, and ignored is left alone.
        assert_eq!(classify_fs_paths(&pb("/repo/src/main.rs")), (true, false));
        // A user's own *.lock (outside .git) is a target (meaningful).
        assert_eq!(classify_fs_paths(&pb("/repo/Cargo.lock")), (true, false));
        // .gitignore / .git/info/exclude needs an ignored recompute (true, true).
        assert_eq!(classify_fs_paths(&pb("/repo/.gitignore")), (true, true));
        assert_eq!(classify_fs_paths(&pb("/repo/sub/.gitignore")), (true, true));
        assert_eq!(
            classify_fs_paths(&pb("/repo/.git/info/exclude")),
            (true, true)
        );
        // A .gitignore inside node_modules is excluded (it's wholly ignored anyway, so no recompute is needed).
        assert_eq!(
            classify_fs_paths(&pb("/repo/node_modules/x/.gitignore")),
            (true, false)
        );
        // True if even one ignore-rule change is in the burst.
        assert_eq!(
            classify_fs_paths(&[
                PathBuf::from("/repo/.git/index.lock"),
                PathBuf::from("/repo/.gitignore"),
            ]),
            (true, true)
        );
        // An event with an unknown path errs safe (reload, don't touch ignored).
        assert_eq!(classify_fs_paths(&[]), (true, false));
    }

    #[test]
    fn follow_candidates_exclude_git_internals() {
        // Follow targets are anything outside `.git` (index/refs/lock churn isn't a review target).
        let got = follow_candidates(&[
            PathBuf::from("/repo/.git/index"),
            PathBuf::from("/repo/.git/refs/heads/main"),
            PathBuf::from("/repo/src/main.rs"),
            PathBuf::from("/repo/README.md"),
        ]);
        assert_eq!(
            got,
            vec![
                PathBuf::from("/repo/src/main.rs"),
                PathBuf::from("/repo/README.md"),
            ]
        );
    }

    #[test]
    fn burst_paths_dedupes_and_preserves_order() {
        let mut burst = BurstPaths::default();
        let a = PathBuf::from("/repo/a");
        let b = PathBuf::from("/repo/b");
        let c = PathBuf::from("/repo/c");
        assert!(burst.push(&a));
        assert!(burst.push(&b));
        assert!(!burst.push(&a), "重複は false(既にカウント済み)");
        assert!(burst.push(&c));
        assert_eq!(burst.finish(), Some(vec![a, b, c]));
    }

    #[test]
    fn burst_paths_overflow_reports_unknown() {
        let mut burst = BurstPaths::default();
        for i in 0..MAX_BURST_PATHS {
            assert!(burst.push(&PathBuf::from(format!("/repo/f{i}"))));
        }
        // Everything up to exactly the cap passes as distinct. The next one exceeds the cap = false.
        assert!(
            !burst.push(&PathBuf::from("/repo/overflow")),
            "上限を超えたら push は false"
        );
        assert_eq!(
            burst.finish(),
            None,
            "上限超過バーストは「パス不明」として扱われる"
        );
    }

    #[test]
    fn is_content_event_ignores_reads_reacts_to_writes() {
        use notify::event::{
            AccessKind, AccessMode, CreateKind, DataChange, ModifyKind, RemoveKind, RenameMode,
        };
        use notify::EventKind;

        // Read-family events (open/read/close-without-write) don't react (a countermeasure for
        // inotify's IN_OPEN/IN_ACCESS).
        assert!(!is_content_event(&EventKind::Access(AccessKind::Open(
            AccessMode::Any
        ))));
        assert!(!is_content_event(&EventKind::Access(AccessKind::Open(
            AccessMode::Read
        ))));
        assert!(!is_content_event(&EventKind::Access(AccessKind::Read)));
        assert!(!is_content_event(&EventKind::Access(AccessKind::Close(
            AccessMode::Read
        ))));
        assert!(!is_content_event(&EventKind::Access(AccessKind::Any)));

        // A confirmed write (IN_CLOSE_WRITE) reacts. Every kind other than Access reacts (err safe).
        assert!(is_content_event(&EventKind::Access(AccessKind::Close(
            AccessMode::Write
        ))));
        assert!(is_content_event(&EventKind::Any));
        assert!(is_content_event(&EventKind::Create(CreateKind::File)));
        assert!(is_content_event(&EventKind::Modify(ModifyKind::Data(
            DataChange::Any
        ))));
        assert!(is_content_event(&EventKind::Modify(ModifyKind::Name(
            RenameMode::Any
        ))));
        assert!(is_content_event(&EventKind::Remove(RemoveKind::File)));
        assert!(is_content_event(&EventKind::Other));
    }

    /// A unique temp directory per call (pid + a process-global counter), matching
    /// `app::tests::unique_tmp` — a real filesystem watcher below must not share a fixed path with
    /// a parallel test run or the two watchers cross-contaminate each other's events.
    fn watch_test_unique_tmp(prefix: &str) -> PathBuf {
        use std::sync::atomic::{AtomicU64, Ordering};
        static N: AtomicU64 = AtomicU64::new(0);
        let n = N.fetch_add(1, Ordering::Relaxed);
        std::env::temp_dir().join(format!("{prefix}_{}_{n}", std::process::id()))
    }

    #[test]
    fn watcher_ignores_reads_but_reports_writes() {
        // An integration test that runs is_content_event through a real notify watcher in the same
        // order as run()'s callback (is_content_event → classify_fs_paths).
        //
        // The read-side assertion **fails on Linux without the is_content_event filter**
        // (inotify also subscribes to WatchMask::OPEN, so even a plain open/read fires
        // EventKind::Access(..) — without the filter this is misdetected as "there was a change").
        // macOS's FSEvents never reports reads at all, so on the read side **regardless of whether
        // the filter is present**, no event ever arrives = vacuous (it merely goes green without
        // any actual detection power), but it's harmless.
        // The write-side assertion holds on both OSes, and acts as a guardrail that the "filter
        // out reads" fix hasn't become an over-filter that swallows real content changes too.
        use notify::{RecursiveMode, Watcher};
        use std::sync::mpsc;
        use std::time::{Duration, Instant};

        let dir = watch_test_unique_tmp("konoma_watch_filter_test");
        std::fs::create_dir_all(&dir).unwrap();
        let file = dir.join("f.txt");
        std::fs::write(&file, b"hello").unwrap();

        let (tx, rx) = mpsc::channel::<()>();
        let mut watcher = notify::recommended_watcher(move |res: notify::Result<notify::Event>| {
            if let Ok(ev) = res {
                // The same-order filter as run()'s watcher callback.
                if !is_content_event(&ev.kind) {
                    return;
                }
                let (meaningful, _) = classify_fs_paths(&ev.paths);
                if meaningful {
                    let _ = tx.send(());
                }
            }
        })
        .expect("recommended_watcher");
        watcher
            .watch(&dir, RecursiveMode::Recursive)
            .expect("watch");

        // settle: discard the directory/file creation's own events over ~500ms.
        let settle_until = Instant::now() + Duration::from_millis(500);
        while Instant::now() < settle_until {
            let _ = rx.recv_timeout(Duration::from_millis(50));
        }

        // A read alone (with the filter working) produces no event.
        for _ in 0..5 {
            let _ = std::fs::read(&file);
        }
        assert!(
            rx.recv_timeout(Duration::from_secs(1)).is_err(),
            "reading a file must not be reported as a change \
             (fails on Linux without the is_content_event filter; vacuous on macOS)"
        );

        // A write still produces an event (confirms we haven't over-filtered).
        std::fs::write(&file, b"changed").unwrap();
        assert!(
            rx.recv_timeout(Duration::from_secs(10)).is_ok(),
            "writing a file must still be reported as a change"
        );

        drop(watcher);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn follow_is_sticky_and_breaks_only_on_toggle_or_text_input() {
        // User's choice (2026-07-23, maximally sticky): while following, a normal key (movement,
        // etc.) does not disable follow. It's released only by F (the toggle itself, via
        // toggle_follow) / a key while inside a text-input surface / a confirm modal / q
        // (PreviewBack leaves the follow view) (q/PreviewBack are verified in
        // e2e_follow_survives_scroll_and_cycle_breaks_only_on_q).
        let dir = std::env::temp_dir().join("konoma_follow_break_test");
        std::fs::create_dir_all(&dir).unwrap();
        let mut app = App::new(dir.clone(), Config::default()).unwrap();
        handle_key(
            &mut app,
            KeyEvent::new(KeyCode::Char('F'), KeyModifiers::NONE),
        )
        .unwrap();
        assert!(app.follow_enabled(), "F で ON");
        // F once more: OFF via the toggle, not follow_break (indistinguishable from outside, but
        // it does turn OFF).
        handle_key(
            &mut app,
            KeyEvent::new(KeyCode::Char('F'), KeyModifiers::NONE),
        )
        .unwrap();
        assert!(!app.follow_enabled(), "F 再押下で OFF");
        // Turn ON again and press j (a movement key — doesn't resolve to PreviewBack on the tree
        // surface) → kept via maximal stickiness.
        handle_key(
            &mut app,
            KeyEvent::new(KeyCode::Char('F'), KeyModifiers::NONE),
        )
        .unwrap();
        assert!(app.follow_enabled());
        handle_key(&mut app, key('j')).unwrap();
        assert!(
            app.follow_enabled(),
            "j のような通常キーでは最大粘着によりフォロー維持"
        );
        // '/' enters the text-input surface (Filter). The very keypress that enters it is still
        // judged on the Tree surface, so it's kept, but once inside the text-input surface, the
        // next key releases it (treated as manual operation).
        handle_key(&mut app, key('/')).unwrap();
        assert!(app.is_filtering());
        assert!(
            app.follow_enabled(),
            "テキスト入力面へ入る瞬間のキーでは未解除"
        );
        handle_key(&mut app, key('x')).unwrap();
        assert!(
            !app.follow_enabled(),
            "テキスト入力面に居る間のキーでフォロー解除"
        );
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn quote_opens_bookmark_list_and_letters_jump() {
        // `'` alone opens the list (the invisible waiting state is gone), and a plain letter in the
        // list jumps directly as a bookmark name. The old e/d (edit/delete) moved to Ctrl
        // modifiers, so a plain e can also be used to jump.
        let root = std::env::temp_dir().join("konoma_quote_list_test");
        let _ = std::fs::remove_dir_all(&root);
        let proj = root.join("proj");
        std::fs::create_dir_all(proj.join("sub")).unwrap();
        std::fs::write(proj.join("f.txt"), b"x").unwrap();
        let proj = proj.canonicalize().unwrap();
        let mut app = App::new(proj.clone(), Config::default()).unwrap();
        app.bookmarks = bookmarks::Bookmarks::with_base(root.join("cfgbase"), &proj);
        app.bookmarks.set('a', proj.join("sub")).unwrap();
        app.bookmarks.set('e', proj.join("f.txt")).unwrap();

        handle_key(&mut app, key('\'')).unwrap();
        assert!(app.is_bookmark_list(), "' 一発で一覧が開く");
        assert!(!app.is_marking(), "ジャンプの待ち受け状態は無い");
        // An unregistered letter: flash, and the list stays open.
        handle_key(&mut app, key('z')).unwrap();
        assert!(app.is_bookmark_list());
        assert!(app.flash.is_some(), "未登録は flash");
        // e jumps as a bookmark name (a file → preview).
        handle_key(&mut app, key('e')).unwrap();
        assert!(!app.is_bookmark_list(), "ジャンプで一覧が閉じる");
        assert_eq!(app.tab.mode, Mode::Preview);
        assert!(app
            .tab
            .preview_path
            .as_deref()
            .is_some_and(|p| p.ends_with("f.txt")));
        // Go back and press `'` a second time = closes it (feels like a toggle).
        handle_key(&mut app, key('q')).unwrap(); // preview → tree
        handle_key(&mut app, key('\'')).unwrap();
        assert!(app.is_bookmark_list());
        handle_key(&mut app, key('\'')).unwrap();
        assert!(!app.is_bookmark_list(), "' 再押下で閉じる");
        // Ctrl+D = delete the selected row (a plain d is reserved for jumping). Move down to e's
        // row with j, then delete it.
        handle_key(&mut app, key('\'')).unwrap();
        let before = app.bookmark_list_items().len();
        handle_key(&mut app, key('j')).unwrap();
        handle_key(
            &mut app,
            KeyEvent::new(KeyCode::Char('d'), KeyModifiers::CONTROL),
        )
        .unwrap();
        assert_eq!(app.bookmark_list_items().len(), before - 1, "Ctrl+D で削除");
        assert!(app.bookmarks.get('e').is_none(), "消えたのは選択行の e");
        // A directory bookmark moves root.
        handle_key(&mut app, key('a')).unwrap();
        assert_eq!(app.tab.root, proj.join("sub"));
        assert!(!app.is_bookmark_list());
        std::fs::remove_dir_all(&root).ok();
    }

    #[test]
    fn filter_input_captures_literal_keys() {
        // While filter input is active, `?`/`c`/digits are also captured as plain "characters,"
        // not help/copy/tab.
        let dir = std::env::temp_dir().join("konoma_filter_input_test");
        std::fs::create_dir_all(&dir).unwrap();
        let mut app = App::new(dir.clone(), Config::default()).unwrap();
        handle_key(&mut app, key('/')).unwrap(); // start filtering
        assert!(app.is_filtering());
        // `c` (normally copy-code) and `?` (normally help) are captured as characters.
        handle_key(&mut app, key('c')).unwrap();
        handle_key(&mut app, key('?')).unwrap();
        assert_eq!(app.filter_query(), Some("c?"));
        assert_eq!(app.pending_leader, None, "コピーリーダーは始まらない");
        assert!(!app.show_help, "ヘルプは開かない");
        // Cleared by Esc.
        handle_key(&mut app, KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)).unwrap();
        assert!(!app.is_filtering() && app.filter_query().is_none());
        std::fs::remove_dir_all(&dir).ok();
    }

    #[cfg(feature = "git")]
    #[test]
    fn help_opens_in_git_view_and_shows_git_keys() {
        let dir = std::env::temp_dir().join("konoma_git_help_test");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        git2::Repository::init(&dir).unwrap();
        std::fs::write(dir.join("a.txt"), b"x").unwrap();
        let mut app = App::new(dir.canonicalize().unwrap(), Config::default()).unwrap();
        app.open_git_view();
        assert!(app.is_git_view());

        // `?` in the git view → help opens (previously it got swallowed by the git intercept and
        // never opened).
        handle_key(&mut app, key('?')).unwrap();
        assert!(app.show_help, "git モードで ? がヘルプを開く");

        // The help content is the git-specific one (the changes-hub section, stage-family keys).
        let lines = ui::help::help_lines(&app);
        let text: String = lines
            .iter()
            .flat_map(|l| l.spans.iter().map(|s| s.content.as_ref().to_string()))
            .collect();
        assert!(
            text.contains("Git changes") || text.contains("変更ハブ"),
            "git 節が出る: {text}"
        );
        assert!(
            text.contains("stage") || text.contains("ステージ"),
            "ステージ系キーが出る"
        );

        // `?` while help is shown closes it.
        handle_key(&mut app, key('?')).unwrap();
        assert!(!app.show_help, "? で閉じる");
        std::fs::remove_dir_all(&dir).ok();
    }

    #[cfg(feature = "git")]
    #[test]
    fn tab_keys_per_tab_git_mode_and_literal_in_filter() {
        let dir = std::env::temp_dir().join("konoma_tab_gitview_test");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        git2::Repository::init(&dir).unwrap();
        std::fs::write(dir.join("a.txt"), b"x").unwrap();
        let mut app = App::new(dir.canonicalize().unwrap(), Config::default()).unwrap();

        // While filter input is active, t is captured as a plain "character," not a new tab.
        handle_key(&mut app, key('/')).unwrap();
        let tc = app.tab_count();
        handle_key(&mut app, key('t')).unwrap();
        assert_eq!(app.tab_count(), tc, "絞り込み中は t で新タブにしない");
        assert_eq!(app.filter_query(), Some("t"));
        handle_key(&mut app, KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)).unwrap();

        // Even while in the git view, t can open a new tab. The new tab is a plain Tree (git mode
        // is per-tab).
        app.open_git_view();
        assert!(app.is_git_view());
        handle_key(&mut app, key('t')).unwrap();
        assert_eq!(app.tab_count(), tc + 1, "git ビュー中でも t で新タブ");
        assert!(!app.is_git_view(), "新タブは git ビュー無しで始まる");
        // Returning to the original tab **restores git mode** (you can view a document in another
        // tab and come back).
        handle_key(&mut app, key('1')).unwrap(); // to tab 0
        assert!(app.is_git_view(), "タブを戻ると git モードのまま");

        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn copy_leader_sets_then_clears_pending() {
        use keymap::LeaderId;
        let dir = std::env::temp_dir().join("konoma_chord_test");
        std::fs::create_dir_all(&dir).unwrap();
        let mut app = App::new(dir, Config::default()).unwrap();
        // `y` starts the copy leader → pending_leader.
        handle_key(&mut app, key('y')).unwrap();
        assert_eq!(app.pending_leader, Some(LeaderId::Copy));
        // A key not in the leader is discarded and pending is cleared (the clipboard is untouched).
        handle_key(&mut app, key('x')).unwrap();
        assert_eq!(app.pending_leader, None);
    }

    #[test]
    fn file_leader_opens_on_space() {
        use keymap::LeaderId;
        let dir = std::env::temp_dir().join("konoma_fileleader_test");
        std::fs::create_dir_all(&dir).unwrap();
        let mut app = App::new(dir, Config::default()).unwrap();
        // The default `c` is no longer a leader (the old copy prefix is gone).
        handle_key(&mut app, key('c')).unwrap();
        assert_eq!(app.pending_leader, None);
        // `Space` starts the file-management leader.
        handle_key(&mut app, key(' ')).unwrap();
        assert_eq!(app.pending_leader, Some(LeaderId::File));
    }

    #[test]
    fn space_leader_n_opens_create_dialog() {
        // Space→n = create a file (the destination the old Tree `a` moved to).
        let dir = std::env::temp_dir().join("konoma_space_create_test");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let mut app = App::new(dir.clone(), Config::default()).unwrap();
        handle_key(&mut app, key(' ')).unwrap();
        handle_key(&mut app, key('n')).unwrap();
        assert_eq!(app.pending_leader, None, "リーダーは確定で消える");
        assert!(app.is_dialog(), "Space→n で作成ダイアログが開く");
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn anchor_keys_a_and_shift_a_dispatch() {
        // `a` = SetAnchor (the old `:`), `A` = ResetAnchor (new). Right after startup, both flash "already the anchor."
        let dir = std::env::temp_dir().join("konoma_anchor_dispatch_test");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let mut app = App::new(dir.canonicalize().unwrap(), Config::default()).unwrap();
        handle_key(&mut app, key('a')).unwrap();
        let fa = app.flash.clone().unwrap_or_default();
        assert!(
            fa.contains("root") || fa.contains("ルート"),
            "a の flash: {fa}"
        );
        handle_key(
            &mut app,
            KeyEvent::new(KeyCode::Char('A'), KeyModifiers::SHIFT),
        )
        .unwrap();
        let fa2 = app.flash.clone().unwrap_or_default();
        assert!(
            fa2.contains("start") || fa2.contains("起動"),
            "A の flash: {fa2}"
        );
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn shift_q_opens_quit_confirm_then_qq_quits() {
        // Default (confirm_quit=ON): Q opens the confirmation dialog → doesn't quit yet. Confirmed
        // by q once more (qq).
        let dir = std::env::temp_dir().join("konoma_quit_confirm_test");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let mut app = App::new(dir.clone(), Config::default()).unwrap();
        let exit = handle_key(
            &mut app,
            KeyEvent::new(KeyCode::Char('Q'), KeyModifiers::SHIFT),
        )
        .unwrap();
        assert!(!exit, "確認段階ではまだ終了しない");
        assert!(
            app.is_dialog() && app.confirm_is_quit(),
            "終了確認ダイアログが開く"
        );
        assert_eq!(app.surface(), Surface::DialogConfirmQuit);
        let exit2 = handle_key(&mut app, key('q')).unwrap();
        assert!(exit2, "qq の2打鍵目で終了");
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn quit_confirm_cancel_with_esc_keeps_running() {
        let dir = std::env::temp_dir().join("konoma_quit_cancel_test");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let mut app = App::new(dir.clone(), Config::default()).unwrap();
        handle_key(&mut app, key('q')).unwrap(); // Tree's q = Quit → the confirmation dialog
        assert!(app.is_dialog() && app.confirm_is_quit());
        let exit = handle_key(&mut app, KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)).unwrap();
        assert!(!exit, "Esc では終了しない");
        assert!(!app.is_dialog(), "Esc で確認ダイアログが閉じる");
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn quit_without_confirm_quits_immediately() {
        // confirm_quit=false: Q quits immediately (no dialog).
        let dir = std::env::temp_dir().join("konoma_quit_immediate_test");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let mut cfg = Config::default();
        cfg.ui.confirm_quit = false;
        let mut app = App::new(dir.clone(), cfg).unwrap();
        let exit = handle_key(
            &mut app,
            KeyEvent::new(KeyCode::Char('Q'), KeyModifiers::SHIFT),
        )
        .unwrap();
        assert!(exit, "confirm_quit=false なら Q で即終了");
        assert!(!app.is_dialog(), "ダイアログは開かない");
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn shift_q_is_literal_while_filtering() {
        // While input (filtering) is active, Q is captured as a plain "character." Doesn't quit,
        // doesn't show the confirmation either.
        let dir = std::env::temp_dir().join("konoma_quit_filter_literal_test");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let mut app = App::new(dir.clone(), Config::default()).unwrap();
        handle_key(&mut app, key('/')).unwrap();
        let exit = handle_key(
            &mut app,
            KeyEvent::new(KeyCode::Char('Q'), KeyModifiers::SHIFT),
        )
        .unwrap();
        assert!(!exit, "絞り込み中の Q では終了しない");
        assert!(!app.is_dialog(), "終了確認も出ない");
        assert_eq!(app.filter_query(), Some("Q"), "Q は文字として入力される");
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn visual_space_d_commits_range_and_confirms_delete() {
        // The old direct `D` is gone → in Visual it's Space→d. Commit the range first, then go to
        // the delete confirmation.
        let dir = std::env::temp_dir().join("konoma_visual_spaced_test");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("a.txt"), b"x").unwrap();
        std::fs::write(dir.join("b.txt"), b"y").unwrap();
        let mut app = App::new(dir.canonicalize().unwrap(), Config::default()).unwrap();
        app.rebuild_tree().unwrap();
        app.tab.selected = 0;
        handle_key(&mut app, key('v')).unwrap();
        assert!(app.is_visual(), "v でビジュアル");
        handle_key(&mut app, key(' ')).unwrap();
        handle_key(&mut app, key('d')).unwrap();
        assert!(!app.is_visual(), "Space→d で範囲を確定しビジュアルを抜ける");
        assert!(app.is_dialog(), "削除確認ダイアログが開く");
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn dnd_paste_ignored_while_dialog_or_overlay_open() {
        // #13: don't let a D&D paste interrupt while a dialog/modal/overlay is shown.
        // Only the basic full-screen surfaces (Tree/Preview) and text-input surfaces accept it.
        let dir = std::env::temp_dir().join("konoma_dnd_guard_test");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let mut app = App::new(dir.canonicalize().unwrap(), Config::default()).unwrap();
        // The normal Tree surface accepts it.
        assert_eq!(app.surface(), Surface::Tree);
        assert!(paste_accepted(app.surface()), "Tree ではドロップを受ける");
        // Open the file-creation dialog (input) → it's a text-input surface, so it's received as characters.
        handle_key(&mut app, key(' ')).unwrap();
        handle_key(&mut app, key('n')).unwrap();
        assert!(app.is_dialog());
        assert!(
            paste_accepted(app.surface()),
            "入力ダイアログは文字として取り込むため通す"
        );
        // Don't let it interrupt while help (an overlay) is shown.
        let mut app2 = App::new(dir.clone(), Config::default()).unwrap();
        handle_key(&mut app2, key('?')).unwrap();
        assert!(app2.show_help);
        assert!(
            !paste_accepted(app2.surface()),
            "ヘルプ表示中はドロップを無視する"
        );
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn help_toggles_and_swallows_keys() {
        let dir = std::env::temp_dir().join("konoma_help_key_test");
        std::fs::create_dir_all(&dir).unwrap();
        let mut app = App::new(dir, Config::default()).unwrap();
        assert!(!app.show_help);
        // Opens with ?.
        handle_key(&mut app, key('?')).unwrap();
        assert!(app.show_help);
        // While it's open, j scrolls (doesn't flow into mode operations).
        handle_key(&mut app, key('j')).unwrap();
        assert_eq!(app.help_scroll, 1);
        // Closes with q (the app doesn't quit).
        assert!(!handle_key(&mut app, key('q')).unwrap());
        assert!(!app.show_help);
    }

    #[test]
    fn tab_keys_work_in_preview_and_preserve_mode() {
        // Bug fix: tab operations (t/w/[/]/1-9) also work while previewing, and each tab's mode
        // (Tree/Preview) is preserved. Switching doesn't drop it to Tree, and returning restores Preview.
        let dir = std::env::temp_dir().join("konoma_tab_in_preview_test");
        std::fs::create_dir_all(&dir).unwrap();
        let mut app = App::new(dir, Config::default()).unwrap();
        // Put tab 0 into previewing.
        app.tab.mode = Mode::Preview;
        // t opens a new tab (works even while previewing). The new tab starts from Tree.
        handle_key(&mut app, key('t')).unwrap();
        assert_eq!(app.tab_count(), 2, "Preview 中でも新規タブが作れる");
        assert_eq!(app.tab.mode, Mode::Tree, "新規タブは Tree から");
        let new_tab = app.active_tab_index();
        // [ returns to the original tab 0 → Preview is restored without dropping to Tree.
        handle_key(&mut app, key('[')).unwrap();
        assert_ne!(app.active_tab_index(), new_tab, "タブが切り替わる");
        assert_eq!(
            app.tab.mode,
            Mode::Preview,
            "戻ったタブの Preview が復元される"
        );
    }

    #[test]
    fn flash_is_cleared_on_next_key() {
        let dir = std::env::temp_dir().join("konoma_flash_test");
        std::fs::create_dir_all(&dir).unwrap();
        let mut app = App::new(dir, Config::default()).unwrap();
        app.flash = Some("x".into());
        handle_key(&mut app, key('j')).unwrap();
        assert_eq!(app.flash, None, "次のキーで flash が消える");
    }

    #[test]
    fn recoverable_key_error_flashes_and_does_not_quit() {
        // Design principle #3: don't bring down the TUI on a recoverable fs/git failure during key handling.
        // Even if handle_key returns Err, the run loop doesn't terminate (quit=false), and the
        // error is shown to the user via flash rather than swallowed.
        let dir = std::env::temp_dir().join("konoma_recoverable_err_test");
        std::fs::create_dir_all(&dir).unwrap();
        let mut app = App::new(dir.clone(), Config::default()).unwrap();
        let quit = resolve_key_result(&mut app, Err(anyhow::anyhow!("boom: refresh 失敗")));
        assert!(!quit, "回復可能な Err でループは終了しない");
        let flash = app
            .flash
            .as_deref()
            .expect("Err は握り潰さず flash で見せる");
        assert!(
            flash.contains("boom"),
            "原因メッセージが flash に出る: {flash}"
        );
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn close_tab_or_quit_closes_tab_when_multiple_else_quits() {
        // Tree's q: with multiple tabs, closes the current one (doesn't quit); with the last one, requests quitting.
        let dir = std::env::temp_dir().join("konoma_close_tab_or_quit_test");
        std::fs::create_dir_all(&dir).unwrap();
        let mut cfg = Config::default();
        cfg.ui.confirm_quit = false; // judge the last tab by quitting immediately (no dialog in between)
        let mut app = App::new(dir.clone(), cfg).unwrap();

        // 2 tabs → q just closes the tab (quit=false).
        app.tab_new().unwrap();
        assert_eq!(app.tab_count(), 2);
        let quit = dispatch_action(&mut app, Action::CloseTabOrQuit, Surface::Tree).unwrap();
        assert!(!quit, "複数タブでは終了しない");
        assert_eq!(app.tab_count(), 1, "現在タブが閉じて1枚に戻る");

        // The last tab → q requests quitting (confirm_quit=false, so immediately Ok(true)).
        let quit = dispatch_action(&mut app, Action::CloseTabOrQuit, Surface::Tree).unwrap();
        assert!(quit, "最後の1枚では終了する");
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn resolve_key_result_passes_through_quit_and_continue() {
        // Ok(true) = a quit request passes straight through / Ok(false) = continuing passes
        // straight through, and doesn't touch flash either.
        let dir = std::env::temp_dir().join("konoma_resolve_passthrough_test");
        std::fs::create_dir_all(&dir).unwrap();
        let mut app = App::new(dir.clone(), Config::default()).unwrap();
        assert!(
            resolve_key_result(&mut app, Ok(true)),
            "Ok(true) は終了要求を通す"
        );
        assert_eq!(app.flash, None, "終了要求では flash を立てない");
        assert!(!resolve_key_result(&mut app, Ok(false)), "Ok(false) は継続");
        assert_eq!(app.flash, None, "継続では flash を立てない");
        std::fs::remove_dir_all(&dir).ok();
    }
}