bmrk 0.4.0

A fast TUI for directory navigation and bookmark management
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
use anyhow::Result;
use crossbeam_channel::Receiver;
use crossterm::event::{KeyEvent, MouseEvent};
use ratatui::Frame;
use std::collections::HashSet;
use std::path::PathBuf;
use std::thread::JoinHandle;

use crate::bookmarks::Bookmarks;
use crate::config::Config;
use crate::dir_index::DirIndex;
use crate::disks::Disks;
use crate::event_handler::EventHandler;
use crate::navigation::Navigation;
use crate::quick_jump::QuickJump;
use crate::search::Search;
use crate::ui::UI;

/// Main application state
pub struct App {
    nav: Navigation,
    search: Search,
    quick_jump: QuickJump,
    ui: UI,
    event_handler: EventHandler,
    config: Config,
    pub bookmarks: Bookmarks,
    pub disks: Disks,
    dir_index: DirIndex,
    index_build_thread: Option<JoinHandle<()>>,
    index_build_receiver: Option<Receiver<DirIndex>>,
    needs_redraw: bool,
}

impl App {
    pub fn new(start_path: PathBuf) -> Result<Self> {
        let config = Config::load()?;

        let nav = Navigation::new(
            start_path,
            false,
            config.behavior.show_hidden,
            config.behavior.follow_symlinks,
        )?;
        let search = Search::new();
        let quick_jump = QuickJump::new();
        let ui = UI::new();
        let event_handler = EventHandler::new();
        let bookmarks = Bookmarks::new()?;
        let disks = Disks::new();
        // Starts empty unconditionally — even loading an already-fresh cache from disk used to
        // run synchronously here, blocking startup on the full size of the persisted index file
        // (`.debug/BDP.md` Part 5, Finding #7). The real index (loaded or freshly built) arrives
        // via `start_background_index`/`poll_dir_index_build`, same as the build path always has.
        let dir_index = DirIndex::empty();

        Ok(App {
            nav,
            search,
            quick_jump,
            ui,
            event_handler,
            config,
            bookmarks,
            disks,
            dir_index,
            index_build_thread: None,
            index_build_receiver: None,
            needs_redraw: true,
        })
    }

    /// Kicks off the background directory-index load-or-build (`.debug/BDP.md` Parts 3 and 5) if
    /// `index.enabled`. Whether the on-disk cache is missing/stale (build) or already fresh
    /// (load) is now decided *inside* the spawned thread, not here — both used to matter to the
    /// caller, but Finding #7 moved the "just load it" branch off the main thread too, so from
    /// `App`'s perspective there's only one outcome to wait for either way. Deliberately kept out
    /// of `App::new` — spawning a real `$HOME` walk during construction would make every
    /// `App::new`-based test race a filesystem scan and write to the user's real config
    /// directory. Call once, after construction, outside of tests.
    pub fn start_background_index(&mut self) {
        if !self.config.index.enabled {
            return;
        }
        let Some(index_path) = DirIndex::dir_index_path() else {
            return;
        };

        let roots = self.config.index.roots.clone();
        let ignore_dirs: HashSet<String> = self.config.index.ignore_dirs.iter().cloned().collect();
        let (handle, receiver) = DirIndex::spawn_load_or_build(
            index_path,
            self.config.index.refresh_hours,
            roots,
            ignore_dirs,
        );
        self.index_build_thread = Some(handle);
        self.index_build_receiver = Some(receiver);
    }

    /// Poll the background index load-or-build for a finished result. Returns true if the
    /// in-memory index was just replaced (kept for signature consistency with the sibling
    /// `poll_*` methods, though nothing on screen reflects the index today, so no redraw is
    /// needed).
    pub fn poll_dir_index_build(&mut self) -> bool {
        let Some(rx) = self.index_build_receiver.as_ref() else {
            return false;
        };
        match rx.try_recv() {
            Ok(index) => {
                self.dir_index = index;
                self.index_build_thread = None;
                self.index_build_receiver = None;
                true
            }
            Err(_) => false,
        }
    }

    pub fn handle_key(&mut self, key: KeyEvent) -> Result<Option<PathBuf>> {
        let result = self.event_handler.handle_key(
            key,
            &mut self.nav,
            &mut self.search,
            &mut self.quick_jump,
            &mut self.bookmarks,
            &mut self.disks,
            &self.ui,
            &self.config,
            &self.dir_index,
        );
        self.mark_dirty();
        result
    }

    pub fn handle_mouse(&mut self, mouse: MouseEvent) -> Result<()> {
        let result = self.event_handler.handle_mouse(
            mouse,
            &mut self.nav,
            &mut self.search,
            &mut self.bookmarks,
            &mut self.disks,
            &mut self.ui,
            &self.config,
        );
        self.mark_dirty();
        result
    }

    pub fn render(&mut self, frame: &mut Frame) {
        self.ui.render_compact(
            frame,
            &self.nav,
            &self.search,
            &self.quick_jump,
            &self.bookmarks,
            &self.disks,
            &self.config,
        );
    }

    /// Poll the background disk-enumeration thread started by `Disks::enter_selection_mode`.
    /// Returns true if there were updates requiring a redraw.
    pub fn poll_disks(&mut self) -> bool {
        let updated = self.disks.poll_load();
        if updated {
            self.mark_dirty();
        }
        updated
    }

    /// Poll search results from background thread.
    /// Returns true if there were updates requiring a redraw.
    pub fn poll_search(&mut self) -> bool {
        let updated = self.search.poll_results();
        if updated {
            self.mark_dirty();
        }
        updated
    }

    /// Poll quick-jump: starts the debounced Phase-2 disk scan if due, and applies a jump the
    /// moment a background match arrives. Returns true if there were updates requiring a
    /// redraw.
    pub fn poll_quick_jump(&mut self) -> bool {
        if !self.quick_jump.active {
            return false;
        }

        let nav_root = self.nav.root.borrow().path.clone();
        let (has_updates, jump_to) =
            self.quick_jump
                .tick(&nav_root, self.nav.show_hidden, self.nav.follow_symlinks);

        if let Some(path) = jump_to {
            let _ = self.nav.expand_path_to_node(&path, false);
        }

        if has_updates {
            self.mark_dirty();
        }
        has_updates
    }

    /// Mark app as needing redraw
    pub fn mark_dirty(&mut self) {
        self.needs_redraw = true;
    }

    /// Clear dirty flag after rendering
    pub fn clear_dirty(&mut self) {
        self.needs_redraw = false;
    }

    /// Check if app needs to be redrawn
    pub fn needs_redraw(&self) -> bool {
        self.needs_redraw
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crossterm::event::{
        KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind,
    };
    use ratatui::{backend::TestBackend, Terminal};
    use std::time::{Duration, Instant};

    #[test]
    fn test_bookmark_create_enters_creation_mode() {
        let temp_dir = std::env::temp_dir().join("bmrk_test_bm_create");
        std::fs::create_dir_all(&temp_dir).unwrap();

        let mut app = App::new(temp_dir.clone()).unwrap();

        // Press 'm' to enter bookmark creation mode
        let key_m = KeyEvent::new(KeyCode::Char('m'), KeyModifiers::NONE);
        let result = app.handle_key(key_m).unwrap();

        // Must NOT return None (exit signal) - returns Some(empty) to stay in app
        assert!(result.is_some(), "pressing 'm' should not exit the app");

        // Bookmark creation mode must be active
        assert!(app.bookmarks.is_creating);

        // Press Esc to cancel
        let key_esc = KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE);
        let _ = app.handle_key(key_esc);
        assert!(!app.bookmarks.is_creating);

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

    #[test]
    fn test_bookmark_creation_ctrl_jk_scrolls_bookmark_list() {
        // Regression test: Ctrl+j/k in bookmark creation mode must scroll the on-screen list of
        // existing bookmarks (like the mouse wheel already does), not move the underlying tree
        // selection — the tree isn't even rendered while this mode is active, so moving it had
        // no visible effect and silently changed which folder Enter would bookmark.
        let temp_dir = std::env::temp_dir().join("bmrk_test_bm_create_ctrl_jk");
        std::fs::create_dir_all(&temp_dir).unwrap();

        let mut app = App::new(temp_dir.clone()).unwrap();
        for i in 0..5 {
            app.bookmarks
                .add(format!("mark{i}"), temp_dir.clone(), None)
                .unwrap();
        }

        let selected_before = app
            .nav
            .get_selected_node()
            .expect("a node should be selected")
            .borrow()
            .path
            .clone();

        let key_m = KeyEvent::new(KeyCode::Char('m'), KeyModifiers::NONE);
        let _ = app.handle_key(key_m).unwrap();
        assert!(app.bookmarks.is_creating);
        assert_eq!(app.bookmarks.scroll_offset, 0);

        let key_ctrl_j = KeyEvent::new(KeyCode::Char('j'), KeyModifiers::CONTROL);
        let _ = app.handle_key(key_ctrl_j).unwrap();
        assert_eq!(
            app.bookmarks.scroll_offset, 1,
            "Ctrl+j should scroll the bookmark list down"
        );

        let selected_after = app
            .nav
            .get_selected_node()
            .expect("a node should be selected")
            .borrow()
            .path
            .clone();
        assert_eq!(
            selected_after, selected_before,
            "Ctrl+j must not move the underlying tree selection"
        );

        let key_ctrl_k = KeyEvent::new(KeyCode::Char('k'), KeyModifiers::CONTROL);
        let _ = app.handle_key(key_ctrl_k).unwrap();
        assert_eq!(
            app.bookmarks.scroll_offset, 0,
            "Ctrl+k should scroll the bookmark list back up"
        );

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

    #[test]
    fn test_search_mode_activation() {
        let temp_dir = std::env::temp_dir().join("bmrk_test_search");
        std::fs::create_dir_all(&temp_dir).unwrap();

        let mut app = App::new(temp_dir.clone()).unwrap();

        // Press '/' to enter search mode
        let key_slash = KeyEvent::new(KeyCode::Char('/'), KeyModifiers::NONE);
        let result = app.handle_key(key_slash).unwrap();
        assert!(result.is_some(), "entering search should not exit the app");
        assert!(app.search.mode, "search mode should be active");

        // Type a character
        let key_r = KeyEvent::new(KeyCode::Char('r'), KeyModifiers::NONE);
        let _ = app.handle_key(key_r);

        // Press Enter to execute search
        let key_enter = KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE);
        let result = app.handle_key(key_enter).unwrap();
        assert!(result.is_some(), "search execution should not exit the app");
        assert!(app.search.show_results, "search results should be shown");

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

    #[test]
    fn test_quick_jump_activation_and_jump() {
        let temp_dir = std::env::temp_dir().join("bmrk_test_quick_jump");
        std::fs::create_dir_all(&temp_dir).unwrap();
        let target = temp_dir.join("target_folder");
        std::fs::create_dir_all(&target).unwrap();

        let mut app = App::new(temp_dir.clone()).unwrap();

        let original_selected = app
            .nav
            .get_selected_node()
            .expect("a node should be selected")
            .borrow()
            .path
            .clone();

        // Press Tab to activate quick jump
        let key_tab = KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE);
        let result = app.handle_key(key_tab).unwrap();
        assert!(
            result.is_some(),
            "activating quick jump should not exit the app"
        );
        assert!(app.quick_jump.active, "quick jump should be active");

        // Type "tar" — enough to uniquely match "target_folder" among root's loaded children
        for c in ['t', 'a', 'r'] {
            let key = KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE);
            let _ = app.handle_key(key).unwrap();
        }
        assert_eq!(app.quick_jump.buffer, "tar");
        assert!(app.quick_jump.has_match, "buffer should have a match");

        let selected = app
            .nav
            .get_selected_node()
            .expect("a node should be selected");
        assert_eq!(
            selected.borrow().path,
            target,
            "cursor should jump to the matched folder"
        );

        // Press Esc to exit quick jump; the tree must revert to its pre-Tab state, not stay at
        // wherever quick jump landed.
        let key_esc = KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE);
        let _ = app.handle_key(key_esc).unwrap();
        assert!(
            !app.quick_jump.active,
            "quick jump should be inactive after Esc"
        );
        assert_eq!(
            app.quick_jump.buffer, "",
            "buffer should be cleared after Esc"
        );
        let selected_after_esc = app
            .nav
            .get_selected_node()
            .expect("a node should be selected");
        assert_eq!(
            selected_after_esc.borrow().path,
            original_selected,
            "Esc must restore the original selection from before Tab was pressed"
        );

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

    #[test]
    fn test_quick_jump_esc_collapses_folders_expanded_during_the_session() {
        let temp_dir = std::env::temp_dir().join("bmrk_test_quick_jump_esc_collapse");
        std::fs::create_dir_all(&temp_dir).unwrap();
        let sub = temp_dir.join("sub");
        let target = sub.join("target_leaf");
        std::fs::create_dir_all(&target).unwrap();

        let mut app = App::new(temp_dir.clone()).unwrap();
        // Hand-populate the index so the nested target resolves synchronously via Phase 1.5,
        // without depending on polling a live Phase-2 scan mid-test.
        app.dir_index = crate::dir_index::DirIndex::from_paths(vec![target.clone()]);
        assert!(
            !app.nav.root.borrow().children[0].borrow().is_expanded,
            "`sub` must not be expanded before quick jump runs"
        );

        let key_tab = KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE);
        let _ = app.handle_key(key_tab).unwrap();
        for c in "target_leaf".chars() {
            let key = KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE);
            let _ = app.handle_key(key).unwrap();
        }
        let selected = app
            .nav
            .get_selected_node()
            .expect("a node should be selected")
            .borrow()
            .path
            .clone();
        assert_eq!(
            selected, target,
            "quick jump should have expanded down to the target"
        );
        assert!(
            app.nav.root.borrow().children[0].borrow().is_expanded,
            "`sub` should be expanded as a side effect of the jump"
        );

        let key_esc = KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE);
        let _ = app.handle_key(key_esc).unwrap();

        assert!(
            !app.nav.root.borrow().children[0].borrow().is_expanded,
            "Esc must collapse the folder that only got expanded during the quick-jump session"
        );
        let selected_after_esc = app
            .nav
            .get_selected_node()
            .expect("a node should be selected")
            .borrow()
            .path
            .clone();
        assert_eq!(selected_after_esc, temp_dir);

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

    #[test]
    fn test_quick_jump_tab_exit_keeps_expansion_trail() {
        // Confirming via a second Tab press (as opposed to Esc) must keep the auto-expansion
        // trail — this is the existing, documented behavior for a *confirmed* exit; only Esc
        // fully cancels.
        let temp_dir = std::env::temp_dir().join("bmrk_test_quick_jump_tab_exit_keeps_expansion");
        std::fs::create_dir_all(&temp_dir).unwrap();
        let sub = temp_dir.join("sub");
        let target = sub.join("target_leaf");
        std::fs::create_dir_all(&target).unwrap();

        let mut app = App::new(temp_dir.clone()).unwrap();
        app.dir_index = crate::dir_index::DirIndex::from_paths(vec![target.clone()]);

        let key_tab = KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE);
        let _ = app.handle_key(key_tab).unwrap();
        for c in "target_leaf".chars() {
            let key = KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE);
            let _ = app.handle_key(key).unwrap();
        }

        // Second Tab press exits quick jump by confirming, not cancelling.
        let _ = app.handle_key(key_tab).unwrap();
        assert!(!app.quick_jump.active);
        assert!(
            app.nav.root.borrow().children[0].borrow().is_expanded,
            "confirming with Tab must keep the expansion, unlike Esc"
        );
        let selected = app
            .nav
            .get_selected_node()
            .expect("a node should be selected")
            .borrow()
            .path
            .clone();
        assert_eq!(selected, target);

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

    #[test]
    fn test_quick_jump_slash_narrows_scope() {
        // Two folders sharing a name prefix in different branches of the tree — under
        // whole-tree search, typing the shared name alone would be ambiguous. `/` should make
        // the second `shared` query resolve only within the branch already narrowed to.
        let temp_dir = std::env::temp_dir().join("bmrk_test_quick_jump_slash_narrow");
        std::fs::create_dir_all(&temp_dir).unwrap();
        let alpha = temp_dir.join("alpha");
        let beta = temp_dir.join("beta");
        let alpha_target = alpha.join("shared_target");
        let beta_target = beta.join("shared_target");
        let beta_only = beta.join("beta_only_target");
        std::fs::create_dir_all(&alpha_target).unwrap();
        std::fs::create_dir_all(&beta_target).unwrap();
        std::fs::create_dir_all(&beta_only).unwrap();

        let mut app = App::new(temp_dir.clone()).unwrap();
        app.dir_index = crate::dir_index::DirIndex::from_paths(vec![
            alpha_target.clone(),
            beta_target.clone(),
            beta_only.clone(),
        ]);

        let key_tab = KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE);
        let _ = app.handle_key(key_tab).unwrap();
        for c in "alpha".chars() {
            let key = KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE);
            let _ = app.handle_key(key).unwrap();
        }
        let selected = app
            .nav
            .get_selected_node()
            .expect("a node should be selected")
            .borrow()
            .path
            .clone();
        assert_eq!(selected, alpha, "quick jump should land on `alpha` first");

        // Narrow the scope to `alpha`.
        let key_slash = KeyEvent::new(KeyCode::Char('/'), KeyModifiers::NONE);
        let _ = app.handle_key(key_slash).unwrap();
        assert_eq!(app.quick_jump.scan_stack, vec![alpha.clone()]);
        assert_eq!(
            app.quick_jump.buffer, "alpha/",
            "narrowing must NOT clear the buffer — it grows into a path breadcrumb"
        );
        assert!(app.quick_jump.active, "narrowing must not exit quick jump");

        // Typing "shared" now must resolve to alpha's copy only, never beta's.
        for c in "shared".chars() {
            let key = KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE);
            let _ = app.handle_key(key).unwrap();
        }
        assert!(app.quick_jump.has_match);
        assert_eq!(
            app.quick_jump.matches,
            vec![alpha_target.clone()],
            "narrowed search must never surface beta's same-named folder"
        );
        let selected_after_narrow = app
            .nav
            .get_selected_node()
            .expect("a node should be selected")
            .borrow()
            .path
            .clone();
        assert_eq!(selected_after_narrow, alpha_target);

        // Backspace back to the segment boundary (buffer == "alpha/"), then type a query that
        // only exists under `beta` — it must NOT be found, even though it's a real match
        // elsewhere in the tree, because the scope is still locked to `alpha`.
        for _ in 0.."shared".len() {
            let key = KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE);
            let _ = app.handle_key(key).unwrap();
        }
        assert_eq!(app.quick_jump.buffer, "alpha/");
        assert_eq!(
            app.quick_jump.scan_stack,
            vec![alpha.clone()],
            "backspacing within a segment must not pop the scope"
        );
        for c in "beta_only".chars() {
            let key = KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE);
            let _ = app.handle_key(key).unwrap();
        }
        assert!(
            !app.quick_jump.has_match,
            "a folder that exists only outside the narrowed scope must not match"
        );

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

    #[test]
    fn test_quick_jump_slash_noop_without_match() {
        let temp_dir = std::env::temp_dir().join("bmrk_test_quick_jump_slash_noop");
        std::fs::create_dir_all(&temp_dir).unwrap();
        std::fs::create_dir_all(temp_dir.join("child")).unwrap();

        let mut app = App::new(temp_dir.clone()).unwrap();

        let key_tab = KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE);
        let _ = app.handle_key(key_tab).unwrap();

        // No characters typed yet — nothing to lock the scope onto.
        let key_slash = KeyEvent::new(KeyCode::Char('/'), KeyModifiers::NONE);
        let result = app.handle_key(key_slash).unwrap();
        assert!(result.is_some(), "no-op `/` must not exit the app");
        assert!(app.quick_jump.scan_stack.is_empty());
        assert_eq!(app.quick_jump.buffer, "");
        assert!(app.quick_jump.active, "quick jump must remain active");

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

    #[test]
    fn test_quick_jump_slash_appends_without_clearing_buffer() {
        let temp_dir = std::env::temp_dir().join("bmrk_test_quick_jump_slash_buffer");
        std::fs::create_dir_all(&temp_dir).unwrap();
        std::fs::create_dir_all(temp_dir.join("src")).unwrap();

        let mut app = App::new(temp_dir.clone()).unwrap();

        let key_tab = KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE);
        let _ = app.handle_key(key_tab).unwrap();
        for c in ['s', 'r'] {
            let key = KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE);
            let _ = app.handle_key(key).unwrap();
        }
        assert!(app.quick_jump.has_match, "'sr' should match 'src'");

        let key_slash = KeyEvent::new(KeyCode::Char('/'), KeyModifiers::NONE);
        let _ = app.handle_key(key_slash).unwrap();
        assert_eq!(
            app.quick_jump.buffer, "sr/",
            "`/` must append a single slash to whatever was typed, never clear it"
        );

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

    #[test]
    fn test_quick_jump_slash_physically_expands_matched_folder() {
        let temp_dir = std::env::temp_dir().join("bmrk_test_quick_jump_slash_expands");
        std::fs::create_dir_all(&temp_dir).unwrap();
        std::fs::create_dir_all(temp_dir.join("alpha").join("child")).unwrap();

        let mut app = App::new(temp_dir.clone()).unwrap();

        let key_tab = KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE);
        let _ = app.handle_key(key_tab).unwrap();
        for c in "alpha".chars() {
            let key = KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE);
            let _ = app.handle_key(key).unwrap();
        }
        assert!(
            !app.nav.root.borrow().children[0].borrow().is_expanded,
            "landing on a match must not expand it by itself (Part 1 behavior, unchanged)"
        );

        let key_slash = KeyEvent::new(KeyCode::Char('/'), KeyModifiers::NONE);
        let _ = app.handle_key(key_slash).unwrap();
        assert!(
            app.nav.root.borrow().children[0].borrow().is_expanded,
            "`/` must physically expand the folder it locks onto"
        );
        assert!(
            !app.nav.root.borrow().children[0]
                .borrow()
                .children
                .is_empty(),
            "expanding must load the folder's children"
        );

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

    #[test]
    fn test_quick_jump_backspace_pops_segment_and_recollapses() {
        let temp_dir = std::env::temp_dir().join("bmrk_test_quick_jump_backspace_pop");
        std::fs::create_dir_all(&temp_dir).unwrap();
        std::fs::create_dir_all(temp_dir.join("alpha").join("child")).unwrap();
        let alpha = temp_dir.join("alpha");

        let mut app = App::new(temp_dir.clone()).unwrap();

        let key_tab = KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE);
        let _ = app.handle_key(key_tab).unwrap();
        for c in "alpha".chars() {
            let key = KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE);
            let _ = app.handle_key(key).unwrap();
        }
        let key_slash = KeyEvent::new(KeyCode::Char('/'), KeyModifiers::NONE);
        let _ = app.handle_key(key_slash).unwrap();
        assert_eq!(app.quick_jump.scan_stack, vec![alpha.clone()]);
        assert!(app.nav.root.borrow().children[0].borrow().is_expanded);

        let key_backspace = KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE);
        let _ = app.handle_key(key_backspace).unwrap();

        assert!(
            app.quick_jump.scan_stack.is_empty(),
            "Backspace at the segment boundary must pop the locked scope"
        );
        assert_eq!(
            app.quick_jump.buffer, "alpha",
            "Backspace must strip exactly the trailing slash, keeping the typed prefix"
        );
        assert!(
            !app.nav.root.borrow().children[0].borrow().is_expanded,
            "backing out of a segment must re-collapse the folder `/` expanded"
        );
        let selected = app
            .nav
            .get_selected_node()
            .expect("a node should be selected")
            .borrow()
            .path
            .clone();
        assert_eq!(
            selected, alpha,
            "backing out must move the selection back onto the folder itself"
        );

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

    #[test]
    fn test_quick_jump_backspace_does_not_collapse_pre_existing_expansion() {
        let temp_dir = std::env::temp_dir().join("bmrk_test_quick_jump_backspace_pre_expanded");
        std::fs::create_dir_all(&temp_dir).unwrap();
        std::fs::create_dir_all(temp_dir.join("alpha").join("child")).unwrap();
        let alpha = temp_dir.join("alpha");

        let mut app = App::new(temp_dir.clone()).unwrap();
        // The user already had `alpha` open before ever touching Tab.
        app.nav.toggle_node(&alpha, false).unwrap();
        assert!(app.nav.root.borrow().children[0].borrow().is_expanded);

        let key_tab = KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE);
        let _ = app.handle_key(key_tab).unwrap();
        for c in "alpha".chars() {
            let key = KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE);
            let _ = app.handle_key(key).unwrap();
        }
        let key_slash = KeyEvent::new(KeyCode::Char('/'), KeyModifiers::NONE);
        let _ = app.handle_key(key_slash).unwrap();

        let key_backspace = KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE);
        let _ = app.handle_key(key_backspace).unwrap();

        assert!(
            app.nav.root.borrow().children[0].borrow().is_expanded,
            "backing out must never collapse a folder the user had already opened before Tab"
        );

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

    #[test]
    fn test_quick_jump_esc_after_narrow_restores_full_pre_tab_state() {
        let temp_dir = std::env::temp_dir().join("bmrk_test_quick_jump_esc_after_narrow");
        std::fs::create_dir_all(&temp_dir).unwrap();
        let sub = temp_dir.join("sub");
        let leaf = sub.join("target_leaf");
        std::fs::create_dir_all(&leaf).unwrap();

        let mut app = App::new(temp_dir.clone()).unwrap();
        app.dir_index = crate::dir_index::DirIndex::from_paths(vec![leaf.clone()]);
        let original_selected = app
            .nav
            .get_selected_node()
            .expect("a node should be selected")
            .borrow()
            .path
            .clone();

        let key_tab = KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE);
        let _ = app.handle_key(key_tab).unwrap();
        for c in "sub".chars() {
            let key = KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE);
            let _ = app.handle_key(key).unwrap();
        }
        let key_slash = KeyEvent::new(KeyCode::Char('/'), KeyModifiers::NONE);
        let _ = app.handle_key(key_slash).unwrap();
        for c in "target_leaf".chars() {
            let key = KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE);
            let _ = app.handle_key(key).unwrap();
        }
        let selected = app
            .nav
            .get_selected_node()
            .expect("a node should be selected")
            .borrow()
            .path
            .clone();
        assert_eq!(selected, leaf, "narrowed jump should still reach the leaf");
        assert!(app.nav.root.borrow().children[0].borrow().is_expanded);

        let key_esc = KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE);
        let _ = app.handle_key(key_esc).unwrap();

        assert!(!app.quick_jump.active);
        assert!(
            app.quick_jump.scan_stack.is_empty(),
            "Esc must reset the scope too"
        );
        assert!(
            !app.nav.root.borrow().children[0].borrow().is_expanded,
            "Esc must collapse everything expanded during the whole session, including after `/`"
        );
        let selected_after_esc = app
            .nav
            .get_selected_node()
            .expect("a node should be selected")
            .borrow()
            .path
            .clone();
        assert_eq!(
            selected_after_esc, original_selected,
            "Esc must restore the pre-Tab selection regardless of how many times `/` was pressed"
        );

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

    #[test]
    fn test_quick_jump_shift_tab_cycles_through_matches() {
        let temp_dir = std::env::temp_dir().join("bmrk_test_quick_jump_shift_tab");
        std::fs::create_dir_all(&temp_dir).unwrap();
        let doc1 = temp_dir.join("documents");
        let doc2 = temp_dir.join("docs_backup");
        let doc3 = temp_dir.join("docker");
        std::fs::create_dir_all(&doc1).unwrap();
        std::fs::create_dir_all(&doc2).unwrap();
        std::fs::create_dir_all(&doc3).unwrap();

        let mut app = App::new(temp_dir.clone()).unwrap();

        let key_tab = KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE);
        let _ = app.handle_key(key_tab).unwrap();
        for c in ['d', 'o', 'c'] {
            let key = KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE);
            let _ = app.handle_key(key).unwrap();
        }
        assert_eq!(
            app.quick_jump.matches.len(),
            3,
            "all three 'doc*' folders should be found"
        );
        let first_target = app
            .nav
            .get_selected_node()
            .expect("a node should be selected")
            .borrow()
            .path
            .clone();
        assert_eq!(app.quick_jump.current_index, 0);

        let key_backtab = KeyEvent::new(KeyCode::BackTab, KeyModifiers::SHIFT);
        let _ = app.handle_key(key_backtab).unwrap();
        assert!(
            app.quick_jump.active,
            "Shift+Tab must not exit quick jump, only cycle the match"
        );
        assert_eq!(app.quick_jump.current_index, 1);
        let second_target = app
            .nav
            .get_selected_node()
            .expect("a node should be selected")
            .borrow()
            .path
            .clone();
        assert_ne!(
            second_target, first_target,
            "Shift+Tab should move the selection to a different match"
        );

        // Cycle through the remaining matches and confirm it wraps back to the first.
        let _ = app.handle_key(key_backtab).unwrap();
        assert_eq!(app.quick_jump.current_index, 2);
        let _ = app.handle_key(key_backtab).unwrap();
        assert_eq!(app.quick_jump.current_index, 0, "cycling must wrap around");
        let wrapped_target = app
            .nav
            .get_selected_node()
            .expect("a node should be selected")
            .borrow()
            .path
            .clone();
        assert_eq!(wrapped_target, first_target);

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

    #[test]
    fn test_quick_jump_letters_j_and_k_are_typeable_not_navigation() {
        let temp_dir = std::env::temp_dir().join("bmrk_test_quick_jump_jk");
        std::fs::create_dir_all(&temp_dir).unwrap();
        std::fs::create_dir_all(temp_dir.join("jazz")).unwrap();

        let mut app = App::new(temp_dir.clone()).unwrap();

        let key_tab = KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE);
        let _ = app.handle_key(key_tab).unwrap();
        assert!(app.quick_jump.active);

        // 'j' must be appended to the buffer, not treated as a "move down" navigation key.
        let key_j = KeyEvent::new(KeyCode::Char('j'), KeyModifiers::NONE);
        let _ = app.handle_key(key_j).unwrap();
        assert!(
            app.quick_jump.active,
            "quick jump must stay active after 'j'"
        );
        assert_eq!(app.quick_jump.buffer, "j");

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

    #[test]
    fn test_app_new_never_spawns_index_build_thread() {
        // `App::new` must stay a pure, cheap construction with no background work started —
        // every test in this module (and anyone else's) constructs an `App` via `App::new`, so
        // spawning a real filesystem walk here would make every one of them race a `$HOME` scan
        // and write to the user's real config directory. The build is started explicitly via
        // `start_background_index()`, called once from `main.rs` after construction.
        let temp_dir = std::env::temp_dir().join("bmrk_test_no_thread_on_new");
        std::fs::create_dir_all(&temp_dir).unwrap();

        let mut app = App::new(temp_dir.clone()).unwrap();
        assert!(app.index_build_thread.is_none());
        assert!(app.index_build_receiver.is_none());
        assert!(
            !app.poll_dir_index_build(),
            "polling with no build in flight must be a no-op"
        );

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

    #[test]
    fn test_start_background_index_noop_when_disabled() {
        let temp_dir = std::env::temp_dir().join("bmrk_test_index_disabled");
        std::fs::create_dir_all(&temp_dir).unwrap();

        let mut app = App::new(temp_dir.clone()).unwrap();
        app.config.index.enabled = false;
        app.start_background_index();

        assert!(
            app.index_build_thread.is_none(),
            "disabled index must never spawn a builder thread"
        );

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

    #[test]
    fn test_quick_jump_index_hit_skips_phase_2() {
        let temp_dir = std::env::temp_dir().join("bmrk_test_dir_index_phase15_hit");
        let _ = std::fs::remove_dir_all(&temp_dir);
        let sub = temp_dir.join("sub");
        // Real nested directory, but never loaded into the in-memory tree (root's children are
        // loaded on construction, but `sub`'s own children are not, since it's never expanded),
        // so Phase 1 cannot find it — only the hand-populated index can.
        let deep_target = sub.join("deep_target_xyz");
        std::fs::create_dir_all(&deep_target).unwrap();

        let mut app = App::new(temp_dir.clone()).unwrap();
        app.dir_index = crate::dir_index::DirIndex::from_paths(vec![deep_target.clone()]);

        let key_tab = KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE);
        let _ = app.handle_key(key_tab).unwrap();
        for c in "deep_target".chars() {
            let key = KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE);
            let _ = app.handle_key(key).unwrap();
        }

        assert!(
            app.quick_jump.has_match,
            "index match should be found via Phase 1.5"
        );
        assert!(
            !app.quick_jump.is_scanning,
            "Phase 2 must be skipped when Phase 1.5 already satisfied the lookup"
        );
        let selected = app
            .nav
            .get_selected_node()
            .expect("a node should be selected");
        assert_eq!(selected.borrow().path, deep_target);

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

    #[test]
    fn test_quick_jump_index_miss_falls_back_to_phase_2() {
        let temp_dir = std::env::temp_dir().join("bmrk_test_dir_index_phase15_miss");
        let _ = std::fs::remove_dir_all(&temp_dir);
        let sub = temp_dir.join("sub");
        let target = sub.join("nested_target_zzz");
        std::fs::create_dir_all(&target).unwrap();

        // dir_index stays empty (App::new's default) — nothing under temp_dir is indexed, so
        // this proves the existing Phase 2 fallback still fires exactly as it did before this
        // feature, when the index doesn't cover the match.
        let mut app = App::new(temp_dir.clone()).unwrap();

        let key_tab = KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE);
        let _ = app.handle_key(key_tab).unwrap();
        for c in "nested_target_zzz".chars() {
            let key = KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE);
            let _ = app.handle_key(key).unwrap();
        }
        assert!(
            !app.quick_jump.has_match,
            "neither Phase 1 nor the empty index should find a not-yet-loaded nested folder"
        );

        let start = Instant::now();
        loop {
            app.poll_quick_jump();
            if app.quick_jump.has_match {
                break;
            }
            assert!(
                start.elapsed() < Duration::from_secs(5),
                "timed out waiting for the Phase 2 fallback scan to find the target"
            );
            std::thread::sleep(Duration::from_millis(20));
        }

        let selected = app
            .nav
            .get_selected_node()
            .expect("a node should be selected");
        assert_eq!(selected.borrow().path, target);

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

    #[test]
    fn test_quick_jump_merges_phase1_shallow_hit_with_index_deep_match() {
        // Regression test: Phase 1 (in-memory) finding a shallow match must not hide a deeper
        // match that only the background index knows about — the two must be merged, not
        // treated as a strict either/or. Previously, Phase 1.5 (the index) was only consulted
        // when Phase 1 found *nothing*, so a legitimate shallow Phase-1 hit (here, a direct
        // child of root, always loaded) silently dropped an index-only deep match from the
        // `Shift+Tab` cycle list — exactly the real-world case (`~/.config/bmrk` vs.
        // `~/github.com/holgertkey/bmrk`) that motivated this whole feature.
        let temp_dir = std::env::temp_dir().join("bmrk_test_merge_phase1_and_index");
        let _ = std::fs::remove_dir_all(&temp_dir);
        let shallow = temp_dir.join("bmrk_shallow");
        let deep = temp_dir.join("sub").join("bmrk_deep");
        std::fs::create_dir_all(&shallow).unwrap();
        std::fs::create_dir_all(&deep).unwrap();

        let mut app = App::new(temp_dir.clone()).unwrap();
        // `shallow` is a direct child of root, already loaded into memory by `App::new` — Phase
        // 1 will find it on its own. `deep` is nested under an unexpanded folder, so only the
        // hand-populated index knows about it.
        app.dir_index = crate::dir_index::DirIndex::from_paths(vec![shallow.clone(), deep.clone()]);

        let key_tab = KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE);
        let _ = app.handle_key(key_tab).unwrap();
        for c in "bmrk".chars() {
            let key = KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE);
            let _ = app.handle_key(key).unwrap();
        }

        assert_eq!(
            app.quick_jump.matches.len(),
            2,
            "both the Phase-1 shallow hit and the index-only deep match must be present"
        );
        let selected = app
            .nav
            .get_selected_node()
            .expect("a node should be selected")
            .borrow()
            .path
            .clone();
        assert_eq!(
            selected, shallow,
            "shallowest match still wins the initial jump"
        );

        let key_backtab = KeyEvent::new(KeyCode::BackTab, KeyModifiers::SHIFT);
        let _ = app.handle_key(key_backtab).unwrap();
        let selected_after_cycle = app
            .nav
            .get_selected_node()
            .expect("a node should be selected")
            .borrow()
            .path
            .clone();
        assert_eq!(
            selected_after_cycle, deep,
            "Shift+Tab must be able to reach the index-only deep match"
        );

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

    #[test]
    fn test_copy_path_key_sets_feedback_and_clears_on_next_key() {
        let temp_dir = std::env::temp_dir().join("bmrk_test_copy_path");
        std::fs::create_dir_all(&temp_dir).unwrap();

        let mut app = App::new(temp_dir.clone()).unwrap();
        assert!(app.nav.copy_feedback.is_none());

        let key_c = KeyEvent::new(KeyCode::Char('c'), KeyModifiers::NONE);
        let result = app.handle_key(key_c).unwrap();
        assert!(result.is_some(), "pressing 'c' should not exit the app");
        assert!(
            app.nav.copy_feedback.is_some(),
            "copy action must set some feedback"
        );

        // Any other key must clear the feedback.
        let key_j = KeyEvent::new(KeyCode::Char('j'), KeyModifiers::NONE);
        let _ = app.handle_key(key_j).unwrap();
        assert!(
            app.nav.copy_feedback.is_none(),
            "feedback must be cleared by the next keypress"
        );

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

    #[test]
    fn test_search_result_directory_selects_exact_node() {
        let temp_dir = std::env::temp_dir().join("bmrk_test_search_result_dir");
        std::fs::create_dir_all(&temp_dir).unwrap();
        let target = temp_dir.join("needle_dir");
        std::fs::create_dir_all(&target).unwrap();

        let mut app = App::new(temp_dir.clone()).unwrap();

        // Directory results can come from Phase 1 (root's direct children are already loaded
        // by Navigation::new), so this can assert immediately without polling.
        let key_slash = KeyEvent::new(KeyCode::Char('/'), KeyModifiers::NONE);
        let _ = app.handle_key(key_slash).unwrap();
        for c in "needle".chars() {
            let key = KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE);
            let _ = app.handle_key(key).unwrap();
        }
        let key_enter = KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE);
        let _ = app.handle_key(key_enter).unwrap();
        assert!(app.search.show_results);
        assert!(
            app.search
                .results
                .iter()
                .any(|r| r.path == target && r.is_dir),
            "directory result should be found via Phase 1"
        );
        app.search.selected = app
            .search
            .results
            .iter()
            .position(|r| r.path == target)
            .unwrap();

        // Press Enter again to jump to the selected directory result.
        let _ = app.handle_key(key_enter).unwrap();
        assert!(!app.search.focus_on_results);
        let selected = app
            .nav
            .get_selected_node()
            .expect("a node should be selected");
        assert_eq!(
            selected.borrow().path,
            target,
            "cursor should land exactly on the matched directory, not an arbitrary node"
        );

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

    #[test]
    fn test_search_result_file_selects_parent_folder() {
        let temp_dir = std::env::temp_dir().join("bmrk_test_search_result_file");
        std::fs::create_dir_all(&temp_dir).unwrap();
        let sub_dir = temp_dir.join("sub");
        std::fs::create_dir_all(&sub_dir).unwrap();
        let needle_file = sub_dir.join("needle.txt");
        std::fs::write(&needle_file, b"content").unwrap();

        let mut app = App::new(temp_dir.clone()).unwrap();

        let key_slash = KeyEvent::new(KeyCode::Char('/'), KeyModifiers::NONE);
        let _ = app.handle_key(key_slash).unwrap();
        for c in "needle".chars() {
            let key = KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE);
            let _ = app.handle_key(key).unwrap();
        }
        let key_enter = KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE);
        let _ = app.handle_key(key_enter).unwrap();
        assert!(app.search.show_results);

        // File results only ever come from Phase 2 (the background disk scan) — Phase 1
        // structurally never holds file nodes — so this must poll rather than assert
        // immediately, unlike the directory-result test above.
        let start = Instant::now();
        let timeout = Duration::from_secs(5);
        loop {
            app.poll_search();
            if app.search.results.iter().any(|r| r.path == needle_file) {
                break;
            }
            assert!(
                start.elapsed() < timeout,
                "timed out waiting for file result to appear"
            );
            std::thread::sleep(Duration::from_millis(20));
        }

        app.search.selected = app
            .search
            .results
            .iter()
            .position(|r| r.path == needle_file)
            .unwrap();

        let _ = app.handle_key(key_enter).unwrap();
        assert!(!app.search.focus_on_results);
        let selected = app
            .nav
            .get_selected_node()
            .expect("a node should be selected");
        assert_eq!(
            selected.borrow().path,
            sub_dir,
            "selecting a file result should land on its containing folder"
        );

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

    #[test]
    fn test_tab_with_search_results_toggles_focus_not_quick_jump() {
        let temp_dir = std::env::temp_dir().join("bmrk_test_tab_search_focus");
        std::fs::create_dir_all(&temp_dir).unwrap();

        let mut app = App::new(temp_dir.clone()).unwrap();

        // Drive search into show_results state, same as test_search_mode_activation.
        let key_slash = KeyEvent::new(KeyCode::Char('/'), KeyModifiers::NONE);
        let _ = app.handle_key(key_slash).unwrap();
        let key_r = KeyEvent::new(KeyCode::Char('r'), KeyModifiers::NONE);
        let _ = app.handle_key(key_r).unwrap();
        let key_enter = KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE);
        let _ = app.handle_key(key_enter).unwrap();
        assert!(app.search.show_results);
        let focus_before = app.search.focus_on_results;

        // Tab while results are showing must toggle focus, not activate quick jump.
        let key_tab = KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE);
        let _ = app.handle_key(key_tab).unwrap();
        assert!(
            !app.quick_jump.active,
            "quick jump must not activate while search results are showing"
        );
        assert_eq!(
            app.search.focus_on_results, !focus_before,
            "Tab should still toggle search focus"
        );

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

    #[test]
    fn test_bookmark_select_enters_selection_mode() {
        let temp_dir = std::env::temp_dir().join("bmrk_test_bm_select");
        std::fs::create_dir_all(&temp_dir).unwrap();

        let mut app = App::new(temp_dir.clone()).unwrap();

        // Press '\'' to enter bookmark selection mode
        let key_tick = KeyEvent::new(KeyCode::Char('\''), KeyModifiers::NONE);
        let result = app.handle_key(key_tick).unwrap();
        assert!(
            result.is_some(),
            "bookmark selection should not exit the app"
        );
        assert!(app.bookmarks.is_selecting);

        // Press Esc to cancel
        let key_esc = KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE);
        let _ = app.handle_key(key_esc);
        assert!(!app.bookmarks.is_selecting);

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

    #[test]
    fn test_esc_exits_app() {
        let temp_dir = std::env::temp_dir().join("bmrk_test_esc");
        std::fs::create_dir_all(&temp_dir).unwrap();

        let mut app = App::new(temp_dir.clone()).unwrap();

        // Press Esc in normal mode should return None (exit signal)
        let key_esc = KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE);
        let result = app.handle_key(key_esc).unwrap();
        assert!(result.is_none(), "Esc in normal mode should signal exit");

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

    // --- `h` key: go-to-parent at the root ---

    #[test]
    fn test_h_on_leaf_root_goes_to_parent_immediately() {
        // Regression test for a real deadlock: rooted at a directory with no subdirectories
        // (the deepest folder in a branch), `h` used to never leave — `is_expanded` was force-set
        // `true` on a childless root, and `toggle_expand`'s leaf-directory guard then refused to
        // ever flip it back to `false`, so the "go to parent" branch was never reached, no matter
        // how many times `h` was pressed.
        let temp_dir = std::env::temp_dir().join("bmrk_test_h_leaf_root");
        std::fs::create_dir_all(&temp_dir).unwrap();
        let leaf = temp_dir.join("leaf");
        std::fs::create_dir_all(&leaf).unwrap();

        let mut app = App::new(leaf.clone()).unwrap();
        assert_eq!(app.nav.root.borrow().path, leaf);

        let key_h = KeyEvent::new(KeyCode::Char('h'), KeyModifiers::NONE);
        let _ = app.handle_key(key_h).unwrap();

        assert_eq!(
            app.nav.root.borrow().path,
            temp_dir,
            "a single `h` press on a childless root must go straight to its parent"
        );

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

    #[test]
    fn test_h_on_expanded_root_with_children_goes_to_parent_in_one_press() {
        // Regression test for the two-press annoyance: previously `h` on the (expanded) root row
        // would only collapse it on the first press, requiring a second press to actually
        // navigate up — inconsistent with `u`, which always goes up in one press.
        let temp_dir = std::env::temp_dir().join("bmrk_test_h_expanded_root");
        std::fs::create_dir_all(&temp_dir).unwrap();
        let child = temp_dir.join("child");
        std::fs::create_dir_all(&child).unwrap();

        let mut app = App::new(child.clone()).unwrap();
        assert_eq!(app.nav.root.borrow().path, child);
        // `child` has a subdirectory, so it starts expanded — not the leaf case above.

        let key_h = KeyEvent::new(KeyCode::Char('h'), KeyModifiers::NONE);
        let _ = app.handle_key(key_h).unwrap();

        assert_eq!(
            app.nav.root.borrow().path,
            temp_dir,
            "a single `h` press on an expanded root must go straight to its parent"
        );

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

    #[test]
    fn test_h_on_non_root_expanded_dir_collapses_first() {
        // The root-specific one-press fix above must not change the existing, documented
        // collapse-then-move-to-parent behavior for a non-root node.
        let temp_dir = std::env::temp_dir().join("bmrk_test_h_non_root_collapse");
        std::fs::create_dir_all(&temp_dir).unwrap();
        let sub = temp_dir.join("sub");
        let grandchild = sub.join("grandchild");
        std::fs::create_dir_all(&grandchild).unwrap();

        let mut app = App::new(temp_dir.clone()).unwrap();
        // Expand `sub` and select it.
        app.nav.toggle_node(&sub, false).unwrap();
        let idx = app
            .nav
            .flat_list
            .iter()
            .position(|n| n.borrow().path == sub)
            .unwrap();
        app.nav.selected = idx;
        assert!(app.nav.root.borrow().children[0].borrow().is_expanded);

        let key_h = KeyEvent::new(KeyCode::Char('h'), KeyModifiers::NONE);
        let _ = app.handle_key(key_h).unwrap();

        assert_eq!(
            app.nav.root.borrow().path,
            temp_dir,
            "collapsing a non-root node must not change the root"
        );
        assert!(
            !app.nav.root.borrow().children[0].borrow().is_expanded,
            "the first `h` press on an expanded non-root node must collapse it"
        );
        let selected = app
            .nav
            .get_selected_node()
            .expect("a node should be selected")
            .borrow()
            .path
            .clone();
        assert_eq!(selected, sub, "selection must stay on the collapsed node");

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

    #[test]
    fn test_shift_q_force_quits_unconditionally_from_any_mode() {
        let temp_dir = std::env::temp_dir().join("bmrk_test_shift_q_force_quit");
        std::fs::create_dir_all(&temp_dir).unwrap();
        let key_shift_q = KeyEvent::new(KeyCode::Char('Q'), KeyModifiers::SHIFT);

        // Plain tree navigation mode.
        let mut app = App::new(temp_dir.clone()).unwrap();
        assert_eq!(
            app.handle_key(key_shift_q).unwrap(),
            None,
            "Shift+Q must exit immediately from tree navigation mode"
        );

        // Search input mode: normal Esc only cancels the query, it doesn't exit the app.
        let mut app = App::new(temp_dir.clone()).unwrap();
        let key_slash = KeyEvent::new(KeyCode::Char('/'), KeyModifiers::NONE);
        let _ = app.handle_key(key_slash).unwrap();
        assert!(app.search.mode, "search mode should be active");
        assert_eq!(
            app.handle_key(key_shift_q).unwrap(),
            None,
            "Shift+Q must exit immediately even while search input is active"
        );

        // Bookmark creation mode: normal Esc only cancels creation, it doesn't exit the app.
        let mut app = App::new(temp_dir.clone()).unwrap();
        let key_m = KeyEvent::new(KeyCode::Char('m'), KeyModifiers::NONE);
        let _ = app.handle_key(key_m).unwrap();
        assert!(
            app.bookmarks.is_creating,
            "bookmark creation should be active"
        );
        assert_eq!(
            app.handle_key(key_shift_q).unwrap(),
            None,
            "Shift+Q must exit immediately even while creating a bookmark"
        );

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

    // Finding #4 (.debug/BDP.md Part 5): `EventHandler::last_click_time` is a single field
    // shared across the tree, search-results, bookmark, and disk lists. It must be reset at
    // every "confirm and move on" transition, or a click on one list can be misread as the
    // second half of a double-click started on an unrelated list. These two tests cover the
    // most direct repro from the review: a Tab focus toggle, and an Enter-jump out of search
    // results, both immediately followed by a same-index click on the list now in view.

    #[test]
    fn test_last_click_time_reset_on_tab_focus_toggle() {
        let temp_dir = std::env::temp_dir().join("bmrk_test_last_click_tab_toggle");
        let _ = std::fs::remove_dir_all(&temp_dir);
        std::fs::create_dir_all(&temp_dir).unwrap();
        for i in 0..5 {
            std::fs::create_dir_all(temp_dir.join(format!("sub{}", i))).unwrap();
        }

        let mut app = App::new(temp_dir.clone()).unwrap();
        let backend = TestBackend::new(80, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        terminal.draw(|f| app.render(f)).unwrap();

        // Search for "sub" — matches all 5 top-level directories.
        for c in ['/', 's', 'u', 'b'] {
            app.handle_key(KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE))
                .unwrap();
        }
        app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE))
            .unwrap();
        assert!(app.search.show_results);
        assert!(app.search.focus_on_results);
        assert!(
            app.search.results.len() >= 4,
            "expected at least 4 search results, got {}",
            app.search.results.len()
        );
        terminal.draw(|f| app.render(f)).unwrap();

        // Tab away from results, back to the tree.
        app.handle_key(KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE))
            .unwrap();
        assert!(!app.search.focus_on_results);
        terminal.draw(|f| app.render(f)).unwrap();

        // Single-click tree row 3 — sets last_click_time.
        let tree_top = app.ui.tree_area_top;
        let tree_col = app.ui.tree_area_start + 1;
        app.handle_mouse(MouseEvent {
            kind: MouseEventKind::Down(MouseButton::Left),
            column: tree_col,
            row: tree_top + 3,
            modifiers: KeyModifiers::NONE,
        })
        .unwrap();
        assert!(app.event_handler.last_click_time.is_some());

        // Tab back onto search results — must reset the double-click timer.
        app.handle_key(KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE))
            .unwrap();
        assert!(app.search.focus_on_results);
        assert!(
            app.event_handler.last_click_time.is_none(),
            "last_click_time must be reset by the Tab focus toggle"
        );
        terminal.draw(|f| app.render(f)).unwrap();

        // Single-click search-result row 3 — same numeric index as the earlier tree click.
        let search_top = app.ui.tree_area_top;
        app.handle_mouse(MouseEvent {
            kind: MouseEventKind::Down(MouseButton::Left),
            column: 1,
            row: search_top + 3,
            modifiers: KeyModifiers::NONE,
        })
        .unwrap();

        // A double-click here would have jumped and cleared focus_on_results — asserting it's
        // still true proves this was read as a fresh single click, not a stale double-click.
        assert!(
            app.search.focus_on_results,
            "a same-index click after a Tab toggle must not be treated as a double-click"
        );
        assert_eq!(app.search.selected, 3);

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

    #[test]
    fn test_last_click_time_reset_on_search_result_enter_jump() {
        let temp_dir = std::env::temp_dir().join("bmrk_test_last_click_enter_jump");
        let _ = std::fs::remove_dir_all(&temp_dir);
        std::fs::create_dir_all(&temp_dir).unwrap();
        for i in 0..5 {
            std::fs::create_dir_all(temp_dir.join(format!("sub{}", i))).unwrap();
        }
        // sub1 gets a child, so an erroneous stale-double-click expanding it is observable.
        std::fs::create_dir_all(temp_dir.join("sub1").join("child")).unwrap();

        let mut app = App::new(temp_dir.clone()).unwrap();
        let backend = TestBackend::new(80, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        terminal.draw(|f| app.render(f)).unwrap();

        for c in ['/', 's', 'u', 'b'] {
            app.handle_key(KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE))
                .unwrap();
        }
        app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE))
            .unwrap();
        assert!(app.search.show_results);
        assert!(app.search.focus_on_results);
        assert!(
            app.search.results.len() >= 4,
            "expected at least 4 search results, got {}",
            app.search.results.len()
        );
        terminal.draw(|f| app.render(f)).unwrap();

        // Single-click search result row 1 (expected to be "sub1", given Phase 1's traversal
        // order matches directory-listing order) — sets last_click_time.
        let top = app.ui.tree_area_top;
        app.handle_mouse(MouseEvent {
            kind: MouseEventKind::Down(MouseButton::Left),
            column: 1,
            row: top + 1,
            modifiers: KeyModifiers::NONE,
        })
        .unwrap();
        assert!(app.event_handler.last_click_time.is_some());
        let clicked_path = app.search.results[app.search.selected].path.clone();

        // Enter-jump out of the focused result must reset the double-click timer.
        app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE))
            .unwrap();
        assert!(
            !app.search.focus_on_results,
            "Enter-jump should return focus to the tree"
        );
        assert!(
            app.event_handler.last_click_time.is_none(),
            "last_click_time must be reset after an Enter-jump from search results"
        );
        terminal.draw(|f| app.render(f)).unwrap();

        let jumped_idx = app
            .nav
            .flat_list
            .iter()
            .position(|n| n.borrow().path == clicked_path)
            .expect("jumped-to node must be visible in the tree");
        assert!(!app.nav.flat_list[jumped_idx].borrow().is_expanded);
        let flat_len_before = app.nav.flat_list.len();

        // Click the same row again immediately: a stale double-click timer would erroneously
        // expand the jumped-to directory.
        let tree_top = app.ui.tree_area_top;
        app.handle_mouse(MouseEvent {
            kind: MouseEventKind::Down(MouseButton::Left),
            column: app.ui.tree_area_start + 1,
            row: tree_top + jumped_idx as u16,
            modifiers: KeyModifiers::NONE,
        })
        .unwrap();

        assert!(
            !app.nav.flat_list[jumped_idx].borrow().is_expanded,
            "a same-index click right after an Enter-jump must not be treated as a stale double-click"
        );
        assert_eq!(app.nav.flat_list.len(), flat_len_before);

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

    #[test]
    fn test_search_results_focus_blocks_unrelated_tree_hotkeys() {
        // Regression test: while browsing search results (focus_on_results), keys other than
        // j/k/Enter/Tab/q/Esc must be inert — they used to fall through to the general match and
        // silently act on the hidden tree selection underneath (e.g. `c` copied the tree
        // cursor's path, `m` opened bookmark creation for the tree cursor, `u`/Backspace/`h`
        // moved the tree cursor), none of which is visible while results are shown. The results
        // hint bar advertises only `jk:select Enter:jump q:exit Esc:cancel/close`.
        let temp_dir = std::env::temp_dir().join("bmrk_test_search_focus_blocks_hotkeys");
        let _ = std::fs::remove_dir_all(&temp_dir);
        std::fs::create_dir_all(&temp_dir).unwrap();
        for i in 0..3 {
            std::fs::create_dir_all(temp_dir.join(format!("sub{}", i))).unwrap();
        }

        let mut app = App::new(temp_dir.clone()).unwrap();

        for c in ['/', 's', 'u', 'b'] {
            app.handle_key(KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE))
                .unwrap();
        }
        app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE))
            .unwrap();
        assert!(app.search.show_results);
        assert!(app.search.focus_on_results);

        let tree_selection_before = app
            .nav
            .get_selected_node()
            .expect("a node should be selected")
            .borrow()
            .path
            .clone();

        for (label, key) in [
            (
                "copy_path",
                KeyEvent::new(KeyCode::Char('c'), KeyModifiers::NONE),
            ),
            (
                "create_bookmark",
                KeyEvent::new(KeyCode::Char('m'), KeyModifiers::NONE),
            ),
            (
                "select_bookmark",
                KeyEvent::new(KeyCode::Char('\''), KeyModifiers::NONE),
            ),
            (
                "select_disk",
                KeyEvent::new(KeyCode::Char('d'), KeyModifiers::NONE),
            ),
            (
                "go_to_parent",
                KeyEvent::new(KeyCode::Char('u'), KeyModifiers::NONE),
            ),
            (
                "go_back",
                KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE),
            ),
            (
                "h_left",
                KeyEvent::new(KeyCode::Char('h'), KeyModifiers::NONE),
            ),
        ] {
            app.handle_key(key).unwrap();
            assert!(
                app.search.focus_on_results,
                "{label} must not change search focus"
            );
            assert!(
                !app.bookmarks.is_creating,
                "{label} must not open bookmark creation"
            );
            assert!(
                !app.bookmarks.is_selecting,
                "{label} must not open bookmark selection"
            );
            assert!(
                !app.disks.is_selecting,
                "{label} must not open disk selection"
            );
            assert!(
                app.nav.copy_feedback.is_none(),
                "{label} must not copy the hidden tree selection"
            );
            let tree_selection_after = app
                .nav
                .get_selected_node()
                .expect("a node should be selected")
                .borrow()
                .path
                .clone();
            assert_eq!(
                tree_selection_after, tree_selection_before,
                "{label} must not move the hidden tree selection"
            );
        }

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

    #[test]
    fn test_results_filter_slash_narrows_then_enter_jumps() {
        let temp_dir = std::env::temp_dir().join("bmrk_test_results_filter_enter");
        let _ = std::fs::remove_dir_all(&temp_dir);
        std::fs::create_dir_all(&temp_dir).unwrap();
        for i in 0..5 {
            std::fs::create_dir_all(temp_dir.join(format!("sub{}", i))).unwrap();
        }

        let mut app = App::new(temp_dir.clone()).unwrap();
        let backend = TestBackend::new(80, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        terminal.draw(|f| app.render(f)).unwrap();

        for c in ['/', 's', 'u', 'b'] {
            app.handle_key(KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE))
                .unwrap();
        }
        app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE))
            .unwrap();
        let total = app.search.results.len();
        assert!(
            total >= 4,
            "expected the search to find sub0..sub4, got {total}"
        );

        // '/' opens the results filter (search key is '/', but focus is on results).
        app.handle_key(KeyEvent::new(KeyCode::Char('/'), KeyModifiers::NONE))
            .unwrap();
        assert!(
            app.search.filtering_results,
            "'/' must open the results filter"
        );
        assert!(!app.search.mode, "'/' here must NOT start a fresh search");

        for c in ['s', 'u', 'b', '2'] {
            app.handle_key(KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE))
                .unwrap();
        }
        assert_eq!(app.search.result_filter, "sub2");
        assert_eq!(
            app.search.results.len(),
            1,
            "filter 'sub2' must narrow to the single matching result"
        );
        let target = app.search.results[0].path.clone();
        assert!(target.ends_with("sub2"));

        // Enter jumps straight to the selected filtered result and leaves both sub-modes.
        app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE))
            .unwrap();
        assert!(!app.search.filtering_results);
        assert!(!app.search.focus_on_results);
        let selected = app
            .nav
            .get_selected_node()
            .expect("a node should be selected")
            .borrow()
            .path
            .clone();
        assert_eq!(
            selected, target,
            "Enter must jump to the filtered result in the tree"
        );

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

    #[test]
    fn test_results_filter_tab_returns_to_navigation_and_esc_clears() {
        let temp_dir = std::env::temp_dir().join("bmrk_test_results_filter_tab_esc");
        let _ = std::fs::remove_dir_all(&temp_dir);
        std::fs::create_dir_all(&temp_dir).unwrap();
        for i in 0..5 {
            std::fs::create_dir_all(temp_dir.join(format!("sub{}", i))).unwrap();
        }

        let mut app = App::new(temp_dir.clone()).unwrap();

        for c in ['/', 's', 'u', 'b'] {
            app.handle_key(KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE))
                .unwrap();
        }
        app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE))
            .unwrap();
        let total = app.search.results.len();

        // Filter down, then Tab: stays on results, filter still applied, input closed.
        app.handle_key(KeyEvent::new(KeyCode::Char('/'), KeyModifiers::NONE))
            .unwrap();
        for c in ['s', 'u', 'b', '3'] {
            app.handle_key(KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE))
                .unwrap();
        }
        assert_eq!(app.search.results.len(), 1);
        app.handle_key(KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE))
            .unwrap();
        assert!(!app.search.filtering_results, "Tab closes the filter input");
        assert!(
            app.search.focus_on_results,
            "Tab from the filter stays on results"
        );
        assert_eq!(
            app.search.result_filter, "sub3",
            "Tab keeps the filter applied"
        );
        assert_eq!(app.search.results.len(), 1);

        // 'j' now navigates the (single-item) results list again, not the filter.
        app.handle_key(KeyEvent::new(KeyCode::Char('j'), KeyModifiers::NONE))
            .unwrap();
        assert_eq!(
            app.search.result_filter, "sub3",
            "'j' must not type into the applied filter"
        );

        // Re-open and Esc: filter cleared, full list restored.
        app.handle_key(KeyEvent::new(KeyCode::Char('/'), KeyModifiers::NONE))
            .unwrap();
        app.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE))
            .unwrap();
        assert!(!app.search.filtering_results);
        assert!(app.search.result_filter.is_empty());
        assert_eq!(
            app.search.results.len(),
            total,
            "Esc restores every result that was found"
        );
        assert!(
            app.search.show_results && app.search.focus_on_results,
            "Esc on the filter must not close the results panel"
        );

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

    #[test]
    fn test_results_filter_mouse_double_click_jump_leaves_filter_mode() {
        // Regression: a mouse double-click on a result while the filter caret is open jumps and
        // drops focus_on_results; filtering_results must be cleared too, or the early filter
        // block would keep swallowing every keystroke while the tree is in view.
        let temp_dir = std::env::temp_dir().join("bmrk_test_results_filter_mouse_jump");
        let _ = std::fs::remove_dir_all(&temp_dir);
        std::fs::create_dir_all(&temp_dir).unwrap();
        for i in 0..5 {
            std::fs::create_dir_all(temp_dir.join(format!("sub{}", i))).unwrap();
        }

        let mut app = App::new(temp_dir.clone()).unwrap();
        let backend = TestBackend::new(80, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        terminal.draw(|f| app.render(f)).unwrap();

        for c in ['/', 's', 'u', 'b'] {
            app.handle_key(KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE))
                .unwrap();
        }
        app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE))
            .unwrap();
        terminal.draw(|f| app.render(f)).unwrap();

        app.handle_key(KeyEvent::new(KeyCode::Char('/'), KeyModifiers::NONE))
            .unwrap();
        assert!(app.search.filtering_results);
        terminal.draw(|f| app.render(f)).unwrap();

        let row = app.ui.tree_area_top + 1;
        let click = MouseEvent {
            kind: MouseEventKind::Down(MouseButton::Left),
            column: 1,
            row,
            modifiers: KeyModifiers::NONE,
        };
        app.handle_mouse(click).unwrap();
        app.handle_mouse(click).unwrap(); // double-click -> jump

        assert!(
            !app.search.focus_on_results,
            "double-click jump drops results focus"
        );
        assert!(
            !app.search.filtering_results,
            "double-click jump must also leave the filter input, or the tree becomes unresponsive"
        );

        // A tree hotkey now works again instead of being eaten as filter input.
        let sel_before = app
            .nav
            .get_selected_node()
            .expect("a node should be selected")
            .borrow()
            .path
            .clone();
        app.handle_key(KeyEvent::new(KeyCode::Char('j'), KeyModifiers::NONE))
            .unwrap();
        let sel_after = app
            .nav
            .get_selected_node()
            .expect("a node should be selected")
            .borrow()
            .path
            .clone();
        assert_ne!(
            sel_before, sel_after,
            "'j' must move the tree cursor after the jump"
        );

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