mnml-rs 0.2.20

A NvChad-style terminal IDE in Rust — vim or standard editing, LSP, git, and an embedded HTTP client.
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
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
//! The terminal frontend: raw-mode / alt-screen / mouse-capture setup, the
//! crossterm event loop, and the shared key/mouse dispatchers (`dispatch_key` /
//! `dispatch_mouse`) that the headless+IPC loop also calls — so headless behavior
//! matches the real UI.

pub mod chord;
pub mod handlers;
pub mod mouse;
pub use chord::{chord_timeout_ms, dispatch_chord_chain, tick_chord_chain};
use handlers::overlay::{
    handle_git_section_commit_key, handle_glyph_builder_key, handle_help_overlay_key,
    handle_integration_edit_key, handle_picker_key, handle_prompt_key, handle_search_section_key,
    handle_settings_overlay_key,
};
use handlers::pane::{handle_pane_key, handle_tree_key};
pub(crate) use mouse::coalesce_scroll;
pub use mouse::dispatch_mouse;

use std::io::{self, Stdout};
use std::time::{Duration, Instant};

use ratatui::Terminal;
use ratatui::backend::CrosstermBackend;
use ratatui::crossterm::cursor::{SetCursorStyle, Show};
use ratatui::crossterm::event::{
    self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEvent, KeyEventKind,
    KeyModifiers, KeyboardEnhancementFlags, PopKeyboardEnhancementFlags,
    PushKeyboardEnhancementFlags,
};
use ratatui::crossterm::execute;
use ratatui::crossterm::terminal::{
    EnterAlternateScreen, LeaveAlternateScreen, SetTitle, disable_raw_mode, enable_raw_mode,
    supports_keyboard_enhancement,
};

use crate::app::App;
use crate::focus::Focus;
use crate::ipc::{self, Ipc};
use crate::pane::Pane;
use crate::ui;

/// Drain queued OS notifications from `app.pending_os_notifications`
/// and emit each as an OSC 9 + OSC 777 escape sequence (with an
/// optional BEL for sound). Ghostty / iTerm2 / kitty / WezTerm
/// route these to native OS notification banners; other
/// terminals silently consume the sequence.
fn emit_pending_os_notifications(
    app: &mut App,
    backend: &mut CrosstermBackend<Stdout>,
) -> io::Result<()> {
    use ratatui::crossterm::style::Print;
    for (title, body, sound) in app.take_pending_os_notifications() {
        // OSC 9 — the de facto standard used by iTerm2 (and now
        // Ghostty, WezTerm, kitty, Windows Terminal). Body-only.
        let osc9 = format!("\x1b]9;{title}: {body}\x07");
        // OSC 777 — xterm / gnome-terminal / older kitty format.
        // Takes title + body separately.
        let osc777 = format!("\x1b]777;notify;{title};{body}\x07");
        let bel = if sound { "\x07" } else { "" };
        let _ = execute!(backend, Print(osc9), Print(osc777), Print(bel));
    }
    Ok(())
}

/// Run the terminal UI. `Ok(true)` ⇒ exit for a rebuild+relaunch (the `run.sh`
/// wrapper watches for that); `Ok(false)` ⇒ normal quit.
pub fn run(mut app: App) -> Result<bool, String> {
    // Workspace basename for the terminal-window title — picks up the
    // current project name so multiple mnml tabs are distinguishable
    // ("mnml — mnml", "mnml — work", …).
    let title = match app.workspace.file_name().and_then(|s| s.to_str()) {
        Some(name) if !name.is_empty() => format!("mnml — {name}"),
        _ => "mnml".to_string(),
    };
    let blink = app.config.editor.cursor_blink;
    // Before setup, so a panic *during* setup is covered too.
    install_panic_hook();
    let mut term =
        setup_terminal(&title, blink).map_err(|e| format!("terminal setup failed: {e}"))?;
    let result = run_loop(&mut term, &mut app);
    let _ = restore_terminal(&mut term);
    result
        .map(|()| app.restart_requested)
        .map_err(|e| format!("{e}"))
}

/// Undo everything `setup_terminal` turned on, writing to `io::stdout()`
/// directly rather than through a `Terminal` handle — a panic hook has no
/// access to one. Mirrors `restore_terminal`; every step is best-effort,
/// because a panicking process must not panic again on its way out.
fn emergency_restore_terminal() {
    if supports_keyboard_enhancement().unwrap_or(false) {
        let _ = execute!(io::stdout(), PopKeyboardEnhancementFlags);
    }
    let _ = disable_raw_mode();
    let _ = execute!(
        io::stdout(),
        LeaveAlternateScreen,
        ratatui::crossterm::style::Print("\x1b[?1003l"),
        DisableMouseCapture,
        ratatui::crossterm::event::DisableBracketedPaste,
        SetCursorStyle::DefaultUserShape,
        Show,
    );
}

/// Restore the terminal on a panic, then let the previous hook run.
///
/// Without this, a panic anywhere in `run_loop` / `app.tick()` / `ui::draw`
/// unwinds straight past `restore_terminal`, and the process exits without
/// ever sending `disable_raw_mode` / `LeaveAlternateScreen` / show-cursor.
/// termios belongs to the tty, not the process, so the user's shell is left
/// with echo and canonical mode off — typing shows nothing, Enter does not
/// submit — still painted on the alternate screen. The only way out is to
/// blind-type `stty sane`.
///
/// Chaining to the previous hook keeps the panic message and backtrace.
fn install_panic_hook() {
    install_panic_hook_with(emergency_restore_terminal);
}

/// Seam for testing: same wiring, with the teardown injected.
fn install_panic_hook_with(restore: fn()) {
    let prev = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |info| {
        restore();
        prev(info);
    }));
}

fn setup_terminal(
    title: &str,
    cursor_blink: bool,
) -> io::Result<Terminal<CrosstermBackend<Stdout>>> {
    enable_raw_mode()?;
    let mut out = io::stdout();
    // mouse-round-9 SEV-3 2026-07-11 — was hardcoded SteadyBar.
    let cursor_style = if cursor_blink {
        SetCursorStyle::BlinkingBar
    } else {
        SetCursorStyle::SteadyBar
    };
    if let Err(e) = execute!(
        out,
        EnterAlternateScreen,
        EnableMouseCapture,
        // Enable all-motion mouse events (?1003h) so hover-without-button
        // generates `MouseEventKind::Moved`. crossterm's `EnableMouseCapture`
        // only turns on button + drag tracking by default. Needed for the
        // statusline chip tooltips.
        ratatui::crossterm::style::Print("\x1b[?1003h"),
        // Enable bracketed paste (?2004h) so external file drops arrive
        // as `Event::Paste(text)` instead of typed-through characters.
        // Powers external drag-and-drop (#7).
        ratatui::crossterm::event::EnableBracketedPaste,
        cursor_style,
        // OSC 0/2 — sets the terminal window/tab title.
        SetTitle(title),
    ) {
        let _ = disable_raw_mode();
        return Err(e);
    }
    // Ask for the kitty keyboard protocol so chords the legacy encoding can't
    // express — `Ctrl+Shift+P`, `Ctrl+I` vs `Tab`, etc. — come through distinctly.
    // No-op on terminals that don't support it.
    if supports_keyboard_enhancement().unwrap_or(false) {
        let _ = execute!(
            out,
            PushKeyboardEnhancementFlags(KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES)
        );
    }
    Terminal::new(CrosstermBackend::new(out)).inspect_err(|_| {
        let _ = disable_raw_mode();
    })
}

fn restore_terminal(term: &mut Terminal<CrosstermBackend<Stdout>>) -> io::Result<()> {
    if supports_keyboard_enhancement().unwrap_or(false) {
        let _ = execute!(term.backend_mut(), PopKeyboardEnhancementFlags);
    }
    disable_raw_mode()?;
    execute!(
        term.backend_mut(),
        LeaveAlternateScreen,
        // Pair with the ?1003h we set in setup_terminal so the host terminal
        // returns to standard tracking.
        ratatui::crossterm::style::Print("\x1b[?1003l"),
        DisableMouseCapture,
        // Pair with the EnableBracketedPaste we sent — otherwise the host
        // shell keeps receiving \e[200~/\e[201~ markers around every paste,
        // breaking clipboard paste after mnml exits.
        ratatui::crossterm::event::DisableBracketedPaste,
        SetCursorStyle::DefaultUserShape
    )?;
    term.show_cursor()?;
    Ok(())
}

fn run_loop(term: &mut Terminal<CrosstermBackend<Stdout>>, app: &mut App) -> io::Result<()> {
    // The interactive loop also speaks the file-IPC channel (so `./run.sh restart`,
    // E2E driving, and "agent inspects the live UI" work against the real terminal,
    // not just headless). Best-effort: if the workspace fs is read-only, skip it.
    let mut ipc = Ipc::init(&app.workspace).ok();
    if let Some(ipc) = ipc.as_mut() {
        let (w, h) = term.size().map(|s| (s.width, s.height)).unwrap_or((0, 0));
        ipc.append_event(&format!(
            "{{\"event\":\"start\",\"mode\":\"tui\",\"cols\":{w},\"rows\":{h}}}"
        ));
    }

    app.run_startup_tasks();
    // Background now-playing poller for the statusline miniplayer —
    // real terminal loop only (headless / e2e skip it).
    app.start_now_playing_poller();
    app.start_sonos_worker();

    // 2026-07-29 — IPC dump throttle bookkeeping. See the block
    // near the dump call for rationale.
    let mut last_ipc_dump: Option<Instant> = None;

    loop {
        let frame_start = std::time::Instant::now();
        app.tick();
        // Chord-chain timeout — fires the pending fallback (if any)
        // when the user pauses past `chord_timeout_ms`. Must run
        // every frame regardless of redraw so a dangling prefix
        // doesn't sit forever after the user gives up.
        tick_chord_chain(app);
        if app.redraw_requested {
            app.redraw_requested = false;
            // Force a fresh paint over a cleared buffer (an external process
            // can leave the terminal in any state).
            term.clear()?;
        }
        term.draw(|f| ui::draw(f, app))?;
        // 2026-07-19 — record frame duration RIGHT after the draw
        // completes. The previous recording point was at the bottom
        // of the loop AFTER `event::poll(120ms)`, which included
        // the idle poll wait as "frame time" — the stress meter
        // was pinned red on any idle session (user report). Now
        // it measures the actual tick+draw work.
        app.record_frame_duration(frame_start.elapsed().as_millis());
        emit_pending_os_notifications(app, term.backend_mut())?;
        crate::app::dispatch::emit_image_placements(app);
        if let Some(ipc) = ipc.as_mut() {
            // 2026-07-29 — throttle the IPC screen/status/rects
            // dump to ~10 Hz. Previously ran on every tick — at 40ms
            // (Pty-open cadence) that's 75 sync disk writes/sec just
            // for IPC introspection. On a macOS system with any I/O
            // pressure this added noticeable typing lag. IPC
            // consumers (headless test drivers, click-audit scripts)
            // don't need more than ~10 fps of ground truth.
            // COMMAND draining still runs every tick so keystrokes /
            // IPC commands stay instant — only the DUMPS are throttled.
            const IPC_DUMP_MIN_MS: u128 = 100;
            if last_ipc_dump
                .map(|t: Instant| t.elapsed().as_millis() >= IPC_DUMP_MIN_MS)
                .unwrap_or(true)
            {
                ipc::dump_screen_status(ipc, term.current_buffer_mut(), app);
                last_ipc_dump = Some(Instant::now());
            }
            ipc::drain_commands(ipc, app);
            ipc::drain_plugin_events(ipc, app);
        }
        // #files item 6 — drain the transfer workers. Cheap when idle
        // (an empty `try_recv`), and it must run every tick regardless
        // of input: progress that only advances when the user happens to
        // press a key reads as a hang, which is the thing moving the
        // copies off the render thread exists to prevent.
        app.poll_transfers();
        if app.should_quit {
            app.save_session_on_quit();
            break;
        }
        // Poll faster while a transfer is running, so the chip's
        // percentage moves smoothly rather than in 120ms steps.
        // Poll faster while a pty is open so streaming output stays smooth.
        // DAP sessions also need fast polling so stopped/output events
        // surface promptly.
        let timeout = Duration::from_millis(
            if app.has_pty_pane()
                || app.has_pending_ai()
                || app.dap.is_some()
                || !app.transfers.is_empty()
            {
                40
            } else {
                120
            },
        );
        if event::poll(timeout)? {
            match event::read()? {
                Event::Key(k) if k.kind != KeyEventKind::Release => dispatch_key(app, k),
                Event::Mouse(m) => {
                    // Wheel coalescing: when the read event is a
                    // ScrollUp/ScrollDown, drain every other
                    // immediately-available scroll event of the
                    // same direction from crossterm's queue, sum
                    // them, dispatch ONE batched scroll. Fixes
                    // post-release over-scroll — macOS produces
                    // 30+ events per spin; without this they queue
                    // and keep applying for ~2s after release.
                    if let Some(batched) = coalesce_scroll(&m)? {
                        dispatch_mouse(app, batched);
                    } else {
                        dispatch_mouse(app, m);
                    }
                    // code-reviewer W-2 2026-06-28: coalesce_scroll
                    // may have read a non-scroll event from the
                    // queue while looking for more wheel events.
                    // Drain the stash so the click/key isn't lost.
                    if let Some(leftover) = mouse::take_coalesce_leftover() {
                        match leftover {
                            Event::Key(k) if k.kind != KeyEventKind::Release => {
                                dispatch_key(app, k)
                            }
                            Event::Mouse(m) => dispatch_mouse(app, m),
                            _ => {}
                        }
                    }
                }
                Event::Resize(_, _) => {}
                Event::Paste(text) => {
                    // Priority 0 — modal overlay open: paste routes
                    // to the overlay's focused text field. Covers
                    // Ctrl+V AND drag-drop from Finder (terminals
                    // translate a drop into a bracketed-paste of the
                    // dropped path). 2026-07-11 user request.
                    if app.glyph_builder.is_some() {
                        let cleaned = text
                            .trim()
                            .trim_matches(|c| c == '\'' || c == '"')
                            .to_string();
                        if let Some(s) = app.glyph_builder.as_mut() {
                            s.insert_str(&cleaned);
                        }
                        continue;
                    }
                    if app.integration_edit.is_some() {
                        // integration_edit_paste reads the clipboard
                        // rather than the event's text — synthesize by
                        // setting the clipboard and calling it. Trim
                        // there too.
                        app.clipboard.set(text.trim().to_string(), false);
                        app.integration_edit_paste();
                        continue;
                    }
                    // Prompt overlay — Cmd+V / Ctrl+V on ANY prompt
                    // (single-line text input) inserts the pasted
                    // text at the caret. Every overlay text field
                    // must ship with paste per user 2026-07-15
                    // "overlay-text-field-affordances" — no more
                    // append-only prompts.
                    if let Some(p) = app.prompt.as_mut() {
                        p.insert_str(text.trim_end_matches('\n'));
                        continue;
                    }
                    // 2026-08-08 — `:` cmdline capture. Cmd+V arrives
                    // as a bracketed-paste; without this branch the
                    // paste silently dropped (user report). Same
                    // filter as the typed-char path — strip control
                    // chars and newlines so multi-line paste stays
                    // single-line.
                    if app.no_pane_cmdline.is_some() {
                        for c in text.chars() {
                            if c != '\n' && c != '\r' && (c as u32) >= 0x20 {
                                app.no_pane_cmdline_push_char(c);
                            }
                        }
                        continue;
                    }
                    // Picker (Ctrl+P / Ctrl+Shift+P / etc.) — user
                    // report 2026-08-05: paste into the Open File
                    // picker dropped silently. Same treatment as
                    // prompt: insert at end of query, skip newlines.
                    if let Some(p) = app.picker.as_mut() {
                        p.insert_str(text.trim_end_matches('\n'));
                        continue;
                    }
                    // Workspace picker filter — same class as the
                    // main picker, different backing store.
                    if app.workspace_picker_open {
                        for c in text.chars() {
                            if c != '\n' && c != '\r' && (c as u32) >= 0x20 {
                                app.workspace_picker_filter.push(c);
                            }
                        }
                        continue;
                    }
                    // Grep-panel filter — same pattern.
                    if app.git_palette_filter_focused {
                        for c in text.chars() {
                            if c != '\n' && c != '\r' && (c as u32) >= 0x20 {
                                app.git_palette_filter.push(c);
                            }
                        }
                        continue;
                    }
                    // Tree filter (when filter_mode is active).
                    if app.tree.filter_mode {
                        for c in text.chars() {
                            if c != '\n' && c != '\r' && (c as u32) >= 0x20 {
                                app.tree.filter_push(c);
                            }
                        }
                        continue;
                    }
                    // Pane-scoped inputs (Cheatsheet, Browser
                    // filters, WebSocket send input). Only handle if
                    // the active pane matches AND its input mode is
                    // on.
                    if let Some(active) = app.active
                        && let Some(pane) = app.panes.get_mut(active)
                    {
                        match pane {
                            crate::pane::Pane::Cheatsheet(c) if c.filter_mode => {
                                for ch in text.chars() {
                                    if ch != '\n' && ch != '\r' && (ch as u32) >= 0x20 {
                                        c.query.push(ch);
                                    }
                                }
                                continue;
                            }
                            crate::pane::Pane::Browser(b) => {
                                let target: Option<&mut String> = if b.net_filter_mode {
                                    Some(&mut b.net_filter)
                                } else if b.dom_filter_mode {
                                    Some(&mut b.dom_filter)
                                } else if b.cookies_filter_mode {
                                    Some(&mut b.cookies_filter)
                                } else if b.storage_filter_mode {
                                    Some(&mut b.storage_filter)
                                } else {
                                    None
                                };
                                if let Some(dst) = target {
                                    for ch in text.chars() {
                                        if ch != '\n' && ch != '\r' && (ch as u32) >= 0x20 {
                                            dst.push(ch);
                                        }
                                    }
                                    continue;
                                }
                            }
                            crate::pane::Pane::Websocket(w) => {
                                // WS send-input is a multi-line
                                // buffer (paste JSON payload etc.),
                                // so we preserve newlines here.
                                for ch in text.chars() {
                                    if ch == '\r' {
                                        continue;
                                    }
                                    w.input.push(ch);
                                }
                                continue;
                            }
                            _ => {}
                        }
                    }
                    // Priority 1 — drag-and-drop of external files
                    // (#7): terminals emit a bracketed-paste with a
                    // filesystem path when the user drops a file.
                    if try_open_dragged_path(app, &text) {
                        continue;
                    }
                    // Priority 2 — pasting a curl / http-verb URL
                    // shape into a Request pane populates the form
                    // (matches Postman / Bruno "copy as cURL from
                    // DevTools, paste here" workflow). Guarded on
                    // the active pane being a Request AND the paste
                    // content matching a lightweight curl-shape check
                    // so a normal text paste into a text field isn't
                    // hijacked.
                    let request_active = app
                        .active
                        .and_then(|i| app.panes.get(i))
                        .map(|p| matches!(p, crate::pane::Pane::Request(_)))
                        .unwrap_or(false);
                    if request_active && crate::app::App::text_looks_like_curl(&text) {
                        app.http_paste_curl_from_text(&text);
                        continue;
                    }
                    // 2026-08-08 (nvchad-user R5 SEV-2) — vim `:` cmdline
                    // paste. The `no_pane_cmdline` branch above only fires
                    // when there's no focused editor; when vim owns the
                    // cmdline (the common case — editor pane focused,
                    // user types `:e <path>` and pastes) the paste event
                    // fell through silently. Route into the InputHandler's
                    // cmdline API so the pasted text lands at the caret.
                    if let Some(editor) = app.active_editor_mut()
                        && let Some(mut cur) = editor.input.cmdline_get()
                    {
                        let caret = editor
                            .input
                            .cmdline_caret()
                            .unwrap_or(cur.len())
                            .min(cur.len());
                        let clean: String = text
                            .chars()
                            .filter(|c| *c != '\n' && *c != '\r' && (*c as u32) >= 0x20)
                            .collect();
                        cur.insert_str(caret, &clean);
                        let new_caret = caret + clean.len();
                        editor.input.cmdline_set(Some(cur));
                        editor.input.set_cmdline_caret(new_caret);
                        continue;
                    }
                    // 2026-08-08 (nvchad-user R5 SEV-2) — insert-mode
                    // paste in the editor (both vim insert mode and
                    // Standard mode). Route via `EditOp::InsertStr`
                    // through `Editor::apply` so vim's undo group stays
                    // intact and the standard mode's history is
                    // recorded consistently. In Normal / Visual the
                    // buffer isn't accepting text input, so falls
                    // through to the silent-drop below.
                    let insert_mode = app.editing_mode() == crate::input::EditingMode::Insert;
                    if insert_mode && app.active_editor_mut().is_some() {
                        let clean: String = text.replace('\r', "");
                        // Split-borrow: pull clipboard out first, then
                        // reborrow the editor. Both live on `app`.
                        let mut clip = std::mem::replace(
                            &mut app.clipboard,
                            crate::clipboard::Clipboard::detached(),
                        );
                        if let Some(editor) = app.active_editor_mut() {
                            let _ = editor.editor.apply(
                                crate::edit_op::EditOp::InsertStr(clean),
                                24,
                                &mut clip,
                            );
                            editor.mark_edited();
                        }
                        app.clipboard = clip;
                        continue;
                    }
                    // Nothing else routes Paste events today; drop
                    // silently as before.
                }
                _ => {}
            }
        }
        // (Frame-duration sample moved earlier — right after
        // term.draw — so idle poll wait doesn't count as stress.)
    }

    if let Some(ipc) = ipc.as_mut() {
        term.draw(|f| ui::draw(f, app))?;
        ipc::dump_screen_status(ipc, term.current_buffer_mut(), app);
        ipc.append_event(if app.restart_requested {
            "{\"event\":\"exit\",\"restart\":true}"
        } else {
            "{\"event\":\"exit\"}"
        });
    }
    Ok(())
}

// T-2: coalesce_scroll + SCROLL_BATCH_COUNT + take_scroll_batch_count
// moved to src/tui/mouse.rs (re-exported above).

/// External drag-and-drop (#7). Terminals that emit a bracketed
/// paste of a filesystem path should route as an open, not as a
/// text-insert. Detects:
/// - A single line (or newline-separated batch) whose trimmed value
///   is an existing file path (or `file://` URL).
/// - Multi-file drops: one open per line.
/// Returns true when at least one path opened.
fn try_open_dragged_path(app: &mut App, text: &str) -> bool {
    let mut opened_any = false;
    for raw in text.lines().map(str::trim).filter(|s| !s.is_empty()) {
        // Strip `file://` prefix + a common wrapping quote/escape pair.
        let stripped = raw
            .strip_prefix("file://")
            .unwrap_or(raw)
            .trim_matches(&['"', '\''] as &[_]);
        // Percent-decode `%20` etc — macOS Finder + several terminals
        // emit percent-encoded URIs for paths with spaces.
        let decoded = percent_decode(stripped);
        let path = std::path::PathBuf::from(decoded);
        if path.is_file() {
            app.open_path(&path);
            opened_any = true;
        }
    }
    opened_any
}

/// Minimal `%XX` decoder — covers the URL-encoded drag-and-drop
/// case without pulling in a URL crate. Accumulates the decoded
/// BYTE stream and converts to UTF-8 at the end so multibyte
/// sequences like `%C3%A9` reassemble as `é` instead of two Latin-1
/// scalars (`é`). Malformed UTF-8 falls through via `from_utf8_lossy`
/// rather than erroring.
fn percent_decode(s: &str) -> String {
    let bytes = s.as_bytes();
    let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'%'
            && i + 2 < bytes.len()
            && bytes[i + 1].is_ascii_hexdigit()
            && bytes[i + 2].is_ascii_hexdigit()
            && let Ok(v) = u8::from_str_radix(
                std::str::from_utf8(&bytes[i + 1..=i + 2]).unwrap_or("00"),
                16,
            )
        {
            out.push(v);
            i += 3;
            continue;
        }
        out.push(bytes[i]);
        i += 1;
    }
    String::from_utf8_lossy(&out).into_owned()
}

// ─── key dispatch (shared with headless/IPC) ────────────────────────

/// Translate a startup-picker selection into the corresponding command
/// or App method. Called from `dispatch_key` after the user commits.
fn fire_startup_action(action: crate::app::StartupPickerAction, app: &mut App) {
    use crate::app::StartupPickerAction::*;
    match action {
        NewFile => {
            crate::command::run("file.new", app);
        }
        OpenFile => {
            // #1226 — was `view.discovery`, the F1 click-discovery
            // overlay. The variant's own doc comment already called
            // this "the fuzzy file picker"; now it is one.
            crate::command::run("picker.files", app);
        }
        OpenFolder => {
            // Opens the AddWorkspace path prompt (`~/` is supported);
            // accepting it canonicalizes the path + adds it as an
            // extra workspace via `App::add_workspace_runtime`.
            crate::command::run("view.add_workspace", app);
        }
        SwitchWorkspace(idx) => {
            app.switch_workspace(idx);
        }
        OpenProject(path) => {
            // Same path as `view.add_workspace` once it has the
            // resolved path — registers the folder as an extra
            // workspace + switches focus to it.
            app.add_workspace_runtime(path, None);
        }
    }
}

/// Try to summon a menu via Alt+<letter> or F10. Returns true when a
/// menu was opened (caller should stop further key dispatch). Called
/// from `dispatch_key` only when no menu is currently open and the
/// `[ui] menu_bar` mode isn't `"hidden"`.
fn try_open_menu_from_key(app: &mut App, key: KeyEvent) -> bool {
    // R6 nvchad SEV-2 2026-08-09 — Alt+letter used to open the menu
    // dropdown ON TOP OF any already-open overlay (Ctrl+P picker,
    // Settings, workspace picker, prompt, vim `:` cmdline, no-pane
    // cmdline). Result: a three-layer overlay stack eating keys
    // across two input contexts. Bail before the accelerator handler
    // when any modal overlay owns focus.
    if app.picker.is_some()
        || app.prompt.is_some()
        || app.settings_overlay.is_some()
        || app.workspace_picker_open
        || app.no_pane_cmdline.is_some()
    {
        return false;
    }
    // Vim `:` cmdline lives inside the active editor pane's input
    // handler — check via `cmdline_get()`, which returns None on
    // handlers that don't own a cmdline (standard mode).
    if let Some(idx) = app.active
        && let Some(crate::pane::Pane::Editor(b)) = app.panes.get(idx)
        && b.input.cmdline_get().is_some()
    {
        return false;
    }
    let menus = crate::menu_bar::bar(app);
    // R6 keyboard/mouse/nvchad triple-corroborated 2026-08-09 — the
    // menu-bar paint clips menus that don't fit before the centred
    // workspace-chip cluster (at 120 cols only File/Edit/Selection
    // render). The prior visibility gate on Alt+letter/F10 (added in
    // keyboard-round-10 F1 to prevent firing an invisible first
    // Action on Enter) locked six of the ten menus out of the
    // keyboard path — Alt+V / G / R / T / W / H silently no-op'd at
    // any real-world width and arrow-nav wrapped through only the
    // three drawn menus.
    //
    // The stale rationale: "invisible menu + Enter = fires the
    // wrong Action". That risk lives in `handle_menu_key`'s Enter
    // handler, which fires whichever item is *highlighted*; the
    // dropdown itself always paints (it renders over the workspace
    // chip cluster), so once open the user sees exactly what they'd
    // fire. Enter-safety comes from the dropdown paint, not the
    // parent chip's visibility.
    //
    // Drop the visibility gate on both accelerators — Alt+V now
    // opens the View dropdown even when the "View" word isn't drawn,
    // and arrow-nav cycles through ALL menus.
    // F10 — open the first menu whose label is alphabetic
    // (skip the brand menu, whose label starts with a Nerd Font
    // glyph). Falls back to index 0 if no alphabetic menu exists.
    //
    // R6 R2 vscode-keyboard SEV-2 F3 2026-08-09 — DAP-gate. When
    // a debug session is active, F10 belongs to dap.next
    // (VS Code + IntelliJ convention). Prior behavior unconditionally
    // summoned the File menu, blocking step-over for the entire
    // debug session. Skip the menu-summon when app.dap is Some;
    // dispatch_chord_chain then reaches the F10 → dap.next binding
    // in the normal way. Users who still want the menu bar during
    // a debug session have Alt+F / Alt+E / etc.
    if key.code == KeyCode::F(10)
        && key.modifiers.is_empty()
        && !menus.is_empty()
        && app.dap.is_none()
    {
        let target = menus
            .iter()
            .position(|m| {
                m.label
                    .chars()
                    .next()
                    .is_some_and(|c| c.is_ascii_alphabetic())
            })
            .unwrap_or(0);
        app.menu_open = Some(crate::menu_bar::MenuOpenState::new_keyboard(target));
        return true;
    }
    // Alt+<letter> — open the menu whose FIRST ALPHABETIC char
    // matches. For the brand menu (`>  mnml`), that's `m`; for
    // `File`, `f`; etc. Matching the first alpha char (instead of
    // strictly the first char) lets the brand menu have an Alt
    // shortcut too, despite leading with a non-alpha prompt mark.
    //
    // input-handler-reviewer 2026-06-29 SEV-2: must NOT match
    // Ctrl+Alt+<letter> — those are global chords (Ctrl+Alt+W
    // closes right-panel tab, etc.) that the chord layer claims.
    // `modifiers.contains(ALT)` is a subset check, so without the
    // explicit `!contains(CONTROL)` exclusion, Ctrl+Alt+W was
    // being consumed by the menu-bar accelerator (matching 'W' →
    // Window menu) before reaching dispatch_chord_chain.
    // R14 vscode-keyboard K1 (2026-08-23) — the SHIFT check was
    // missing, so `Shift+Alt+F` (VS Code's Format Document, the
    // universal formatting chord) was stolen by the File menu.
    // Any Shift+Alt+<letter> where the letter matched a menu's
    // first-alpha char lost the same way. Excluding SHIFT closes
    // the whole class; Alt-only accelerators still work.
    if key.modifiers.contains(KeyModifiers::ALT)
        && !key.modifiers.contains(KeyModifiers::CONTROL)
        && !key.modifiers.contains(KeyModifiers::SHIFT)
        && let KeyCode::Char(ch) = key.code
    {
        let ch_lower = ch.to_ascii_lowercase();
        if let Some((i, _)) = menus.iter().enumerate().find(|(_, m)| {
            m.label
                .chars()
                .find(|c| c.is_ascii_alphabetic())
                .is_some_and(|c| c.to_ascii_lowercase() == ch_lower)
        }) {
            app.menu_open = Some(crate::menu_bar::MenuOpenState::new_keyboard(i));
            return true;
        }
    }
    false
}

/// Handle a key while a menu dropdown is open. Returns true when the
/// key was consumed by the menu (caller should stop dispatch).
fn handle_menu_key(app: &mut App, key: KeyEvent) -> bool {
    let menus = crate::menu_bar::bar(app);
    let Some(open) = app.menu_open.as_ref().cloned() else {
        return false;
    };
    let Some(menu) = menus.get(open.menu_idx) else {
        return false;
    };
    // R6 R2 vscode-keyboard F8 (2026-08-09) — a top-level global
    // chord fired while a menu is open should close the menu and
    // let the chord dispatcher take the key. VS Code convention.
    // Previously Ctrl+P/Ctrl+Shift+P/F1/etc. silently no-oped:
    // this fn returned `false` because Ctrl+letter didn't match a
    // mnemonic, but `try_open_menu_from_key` also bailed because
    // `menu_open.is_some()`, so nothing ever ran. Close the menu,
    // return false so `dispatch_chord_chain` gets the key.
    // #1229 — ANY Ctrl+char, not just letters.
    //
    // This was `c.is_ascii_alphabetic()`, which silently excluded the
    // punctuation chords. `ctrl+;` is bound to `palette`, so with a menu
    // open the palette DID open (this fn returned false and the chord
    // dispatcher ran it) but the menu stayed up and kept eating every
    // subsequent keystroke — reported as "i see the command panel but
    // cant type as focus still on the file menu i had open".
    //
    // Punctuation chords are exactly the ones an alphabetic guard misses,
    // and #1220 was the same shape: `nav.back`/`nav.forward` shipped on
    // `ctrl+minus` and were dead for months because the parser did not
    // name punctuation keys.
    let is_ctrl_char =
        key.modifiers.contains(KeyModifiers::CONTROL) && matches!(key.code, KeyCode::Char(_));
    let is_fkey = matches!(
        key.code,
        KeyCode::F(1)
            | KeyCode::F(2)
            | KeyCode::F(3)
            | KeyCode::F(4)
            | KeyCode::F(5)
            | KeyCode::F(6)
            | KeyCode::F(7)
            | KeyCode::F(8)
            | KeyCode::F(9)
            | KeyCode::F(10)
            | KeyCode::F(11)
            | KeyCode::F(12)
    );
    if is_ctrl_char || is_fkey {
        app.menu_open = None;
        return false;
    }
    // #1097 (2026-08-20) — `/` toggles filter mode. In filter mode,
    // printable chars append to `filter`, Backspace shortens, Esc
    // clears (first) then closes menu (second). Non-filter mode keeps
    // the existing mnemonic-cycle behavior so muscle memory holds.
    if matches!(key.code, KeyCode::Char('/'))
        && !key.modifiers.contains(KeyModifiers::CONTROL)
        && !key.modifiers.contains(KeyModifiers::ALT)
        && let Some(s) = app.menu_open.as_mut()
    {
        s.filter_focused = !s.filter_focused;
        if !s.filter_focused {
            s.filter.clear();
        }
        s.last_mnemonic = None;
        s.item_idx = 0;
        return true;
    }
    // Filter-mode key routing — intercept BEFORE the standard arrow /
    // Enter / mnemonic paths so typing narrows without triggering
    // mnemonic cycling. Arrows + Enter still fall through so the user
    // can nav filtered results and fire the highlighted match.
    if open.filter_focused {
        match key.code {
            KeyCode::Backspace => {
                if let Some(s) = app.menu_open.as_mut() {
                    if s.filter.pop().is_none() {
                        // Empty filter + Backspace → drop filter mode.
                        s.filter_focused = false;
                    }
                    s.item_idx = 0;
                }
                return true;
            }
            KeyCode::Esc => {
                if let Some(s) = app.menu_open.as_mut() {
                    if s.filter.is_empty() {
                        // Second Esc closes the menu.
                        app.menu_open = None;
                    } else {
                        // First Esc clears the filter, stays in menu.
                        s.filter.clear();
                        s.filter_focused = false;
                        s.item_idx = 0;
                    }
                }
                return true;
            }
            KeyCode::Char(c)
                if !key.modifiers.contains(KeyModifiers::CONTROL)
                    && !key.modifiers.contains(KeyModifiers::ALT)
                    && !c.is_control() =>
            {
                if let Some(s) = app.menu_open.as_mut() {
                    s.filter.push(c);
                    // Snap highlight to first visible match so the
                    // narrowed set is immediately actionable.
                    if let Some(&first) = s.visible_indexes(&menu.items).first() {
                        s.item_idx = first;
                    }
                }
                return true;
            }
            _ => {} // Arrows / Enter fall through to standard nav.
        }
    }
    // keyboard-round-14 SEV-3 #11 2026-07-17 — Alt+letter that
    // matches the currently-open menu's first-alpha closes it
    // (VS Code convention: Alt+V opens View → Alt+V again closes).
    // Was: silent no-op — user needed Esc or Alt+different-letter
    // to close. Only matches the SAME menu; Alt+other-letter still
    // switches menus (existing behavior below).
    // Same SHIFT guard as the open-side accelerator above (R14
    // vscode-keyboard K1 2026-08-23) — Shift+Alt+<letter> is
    // never a menu-close accelerator either.
    if key.modifiers.contains(KeyModifiers::ALT)
        && !key.modifiers.contains(KeyModifiers::CONTROL)
        && !key.modifiers.contains(KeyModifiers::SHIFT)
        && let KeyCode::Char(ch) = key.code
    {
        let ch_lower = ch.to_ascii_lowercase();
        let same_first_alpha = menu
            .label
            .chars()
            .find(|c| c.is_ascii_alphabetic())
            .is_some_and(|c| c.to_ascii_lowercase() == ch_lower);
        if same_first_alpha {
            app.menu_open = None;
            return true;
        }
    }
    // Submenu keyboard handling. If a submenu is open (`sub_item_idx
    // is Some`), nav is routed into IT instead of the parent menu.
    // Left closes the submenu (back to parent). Esc closes both.
    if let Some(sub_idx) = open.sub_item_idx
        && let Some(crate::menu_bar::MenuItem::Submenu { items, .. }) =
            menu.items.get(open.item_idx)
    {
        match key.code {
            KeyCode::Esc => {
                app.menu_open = None;
                return true;
            }
            KeyCode::Left => {
                // Close just the submenu, stay on the parent row.
                if let Some(s) = app.menu_open.as_mut() {
                    s.sub_item_idx = None;
                }
                return true;
            }
            KeyCode::Up => {
                let n = items.len();
                if n > 0 {
                    let start = (sub_idx + n - 1) % n;
                    let new_idx = walk_to_action(items, start, false);
                    if let Some(s) = app.menu_open.as_mut() {
                        s.sub_item_idx = Some(new_idx);
                    }
                }
                return true;
            }
            KeyCode::Down => {
                let n = items.len();
                if n > 0 {
                    let start = (sub_idx + 1) % n;
                    let new_idx = walk_to_action(items, start, true);
                    if let Some(s) = app.menu_open.as_mut() {
                        s.sub_item_idx = Some(new_idx);
                    }
                }
                return true;
            }
            KeyCode::Enter | KeyCode::Right => {
                if let Some(crate::menu_bar::MenuItem::Action { command_id, .. }) =
                    items.get(sub_idx)
                {
                    let id = command_id.clone();
                    app.menu_open = None;
                    crate::command::run(&id, app);
                }
                return true;
            }
            _ => {}
        }
    }
    match key.code {
        KeyCode::Esc => {
            app.menu_open = None;
            true
        }
        KeyCode::Left => {
            // R6 keyboard/mouse/nvchad 2026-08-09 — arrow-nav cycles
            // through ALL menus, not just the ones currently painted.
            // Same rationale as `try_open_menu_from_key`: dropdown
            // Enter-safety comes from the dropdown paint itself, not
            // the parent chip's visibility. Prior gate locked six of
            // ten menus out of ←→ nav at typical widths.
            let all: Vec<usize> = (0..menus.len()).collect();
            if let Some(prev) = prev_visible_menu(open.menu_idx, &all, menus.len()) {
                app.menu_open = Some(crate::menu_bar::MenuOpenState::new_keyboard(prev));
            }
            true
        }
        KeyCode::Right => {
            // Submenu open-on-right when the highlighted parent row
            // IS a Submenu. Otherwise fall through to next-menu nav.
            if let Some(crate::menu_bar::MenuItem::Submenu { .. }) = menu.items.get(open.item_idx) {
                if let Some(s) = app.menu_open.as_mut() {
                    s.sub_item_idx = Some(0);
                }
                return true;
            }
            let all: Vec<usize> = (0..menus.len()).collect();
            if let Some(next) = next_visible_menu(open.menu_idx, &all, menus.len()) {
                app.menu_open = Some(crate::menu_bar::MenuOpenState::new_keyboard(next));
            }
            true
        }
        KeyCode::Up => {
            // #1097 — when filter is active, nav the FILTERED index
            // list; otherwise walk_to_action on the full items list
            // (existing behavior).
            if !open.filter.is_empty() {
                let vis = open.visible_indexes(&menu.items);
                if !vis.is_empty()
                    && let Some(s) = app.menu_open.as_mut()
                {
                    let cur = vis.iter().position(|&i| i == s.item_idx).unwrap_or(0);
                    let n = vis.len();
                    s.item_idx = vis[(cur + n - 1) % n];
                    s.keyboard_opened = true;
                }
                return true;
            }
            let n = menu.items.len();
            if n > 0 {
                // Skip past Separators by walking until we hit an
                // Action. `usize::MAX` (fresh-mouse-open) wraps to last.
                let start = if open.item_idx == usize::MAX {
                    n - 1
                } else {
                    (open.item_idx + n - 1) % n
                };
                let new_idx = walk_to_action(&menu.items, start, false);
                if let Some(s) = app.menu_open.as_mut() {
                    s.item_idx = new_idx;
                    s.keyboard_opened = true;
                    s.last_mnemonic = None;
                }
            }
            true
        }
        KeyCode::Down => {
            if !open.filter.is_empty() {
                let vis = open.visible_indexes(&menu.items);
                if !vis.is_empty()
                    && let Some(s) = app.menu_open.as_mut()
                {
                    let cur = vis.iter().position(|&i| i == s.item_idx).unwrap_or(0);
                    s.item_idx = vis[(cur + 1) % vis.len()];
                    s.keyboard_opened = true;
                }
                return true;
            }
            let n = menu.items.len();
            if n > 0 {
                let start = if open.item_idx == usize::MAX {
                    0
                } else {
                    (open.item_idx + 1) % n
                };
                let new_idx = walk_to_action(&menu.items, start, true);
                if let Some(s) = app.menu_open.as_mut() {
                    s.item_idx = new_idx;
                    s.keyboard_opened = true;
                    s.last_mnemonic = None;
                }
            }
            true
        }
        KeyCode::Enter => {
            // keyboard-round-9 SEV-2 F1 2026-07-14 — walk to the
            // nearest Action if item_idx points somewhere invalid
            // (usize::MAX after a mouse open, or a Separator). Prior
            // impl silently swallowed Enter in those cases; users
            // expected first-item activation. Enter on a Submenu row
            // OPENS the submenu instead of firing.
            if let Some(crate::menu_bar::MenuItem::Submenu { .. }) = menu.items.get(open.item_idx) {
                if let Some(s) = app.menu_open.as_mut() {
                    s.sub_item_idx = Some(0);
                }
                return true;
            }
            let target = match menu.items.get(open.item_idx) {
                Some(crate::menu_bar::MenuItem::Action { .. }) => open.item_idx,
                _ => walk_to_action(&menu.items, 0, true),
            };
            if let Some(crate::menu_bar::MenuItem::Action { command_id, .. }) =
                menu.items.get(target)
            {
                let id = command_id.clone();
                app.menu_open = None;
                crate::command::run(&id, app);
            }
            true
        }
        // keyboard-round-9 SEV-2 F1 2026-07-14 — printable-char
        // mnemonic (first-letter match) highlights the matching
        // Action; a second press of the SAME letter cycles to the
        // next match; Enter commits. design-round-4 issue 1
        // 2026-07-14 — was single-shot "fire the first match", so
        // View's 7 "Toggle*" items all collapsed onto "Toggle file
        // tree" and the other 6 were unreachable. Any OTHER
        // printable char is still swallowed so it can't leak into
        // the editor while the menu is open.
        KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
            let lower = c.to_ascii_lowercase();
            let matches: Vec<usize> = menu
                .items
                .iter()
                .enumerate()
                .filter_map(|(i, it)| match it {
                    crate::menu_bar::MenuItem::Action { label, .. } => label
                        .chars()
                        .find(|ch| ch.is_ascii_alphabetic())
                        .and_then(|first| (first.to_ascii_lowercase() == lower).then_some(i)),
                    _ => None,
                })
                .collect();
            if let Some(&first) = matches.first() {
                // nvchad-user + vscode-user-keyboard 2026-07-30 both
                // flagged: pressing `s` for Save only highlighted the
                // row (Enter still required). Every OS menu bar fires
                // on the mnemonic directly. Compromise: single match
                // → fire immediately; multiple matches → cycle-then-
                // Enter so the 7-item `View → Toggle*` case still
                // works (repeat-tap `t` cycles between them).
                if matches.len() == 1
                    && let Some(crate::menu_bar::MenuItem::Action { command_id, .. }) =
                        menu.items.get(first)
                {
                    let id = command_id.to_string();
                    app.menu_open = None;
                    crate::command::run(&id, app);
                    return true;
                }
                // Repeat press of same letter → advance to next match
                // (wraps). Different letter → land on first match.
                let target = if open.last_mnemonic == Some(lower) && matches.len() > 1 {
                    matches
                        .iter()
                        .find(|&&idx| idx > open.item_idx)
                        .copied()
                        .unwrap_or(first)
                } else {
                    first
                };
                if let Some(s) = app.menu_open.as_mut() {
                    s.item_idx = target;
                    s.keyboard_opened = true;
                    s.last_mnemonic = Some(lower);
                }
            }
            // Swallow the char either way — no bleed into the editor.
            true
        }
        _ => false,
    }
}

/// Sort + dedup the visible-menu indexes and return the next one after
/// `cur` (wraps). Returns None when `visible` is empty (menu bar hasn't
/// rendered yet) or has one element (nothing to advance to).
/// keyboard-round-10 SEV-2 F1.
fn next_visible_menu(cur: usize, visible: &[usize], _total: usize) -> Option<usize> {
    let mut vis: Vec<usize> = visible.to_vec();
    vis.sort_unstable();
    vis.dedup();
    if vis.len() < 2 {
        return None;
    }
    // First visible > cur, else wrap to smallest.
    Some(
        vis.iter()
            .copied()
            .find(|&i| i > cur)
            .unwrap_or_else(|| vis[0]),
    )
}

fn prev_visible_menu(cur: usize, visible: &[usize], _total: usize) -> Option<usize> {
    let mut vis: Vec<usize> = visible.to_vec();
    vis.sort_unstable();
    vis.dedup();
    if vis.len() < 2 {
        return None;
    }
    // Last visible < cur, else wrap to largest.
    Some(
        vis.iter()
            .copied()
            .rev()
            .find(|&i| i < cur)
            .unwrap_or_else(|| vis[vis.len() - 1]),
    )
}

/// Walk through `items` starting at `start`, in the given direction
/// (`true` = forward, `false` = backward), returning the index of the
/// first Action found. Returns `start` if no Action exists.
fn walk_to_action(items: &[crate::menu_bar::MenuItem], start: usize, forward: bool) -> usize {
    let n = items.len();
    let mut idx = start;
    for _ in 0..n {
        // nvchad-user r2 2026-08-05 — added `Submenu` to the match.
        // Was: `Action` only, so Down/Up arrow silently skipped
        // over `Open recent file ▸` and the submenu was
        // keyboard-unreachable. Submenu is a selectable row too —
        // the parent's Right/Enter handler opens the child when
        // it's highlighted.
        if matches!(
            items.get(idx),
            Some(
                crate::menu_bar::MenuItem::Action { .. }
                    | crate::menu_bar::MenuItem::Submenu { .. }
            )
        ) {
            return idx;
        }
        idx = if forward {
            (idx + 1) % n
        } else {
            (idx + n - 1) % n
        };
    }
    start
}

pub fn dispatch_key(app: &mut App, key: KeyEvent) {
    // Any keystroke cancels a pending hover tooltip / divider highlight —
    // the user moved on to typing, the hover-cue is no longer relevant.
    app.hover_chip = None;
    app.hover_divider_idx = None;
    app.hover_tree_edge = false;
    app.hover_right_panel_edge = false;
    // #20 v5 — Ctrl+Shift+Z as a global keyboard shortcut for the
    // pending-undo chip. Consumed before overlay routing so it
    // works even when a picker / prompt is open (undo of the last
    // destructive action shouldn't require dismissing the overlay
    // above it first). Only fires when there IS a pending_undo,
    // so this key stays free for other flows otherwise.
    if key.code == KeyCode::Char('Z')
        && key
            .modifiers
            .contains(KeyModifiers::CONTROL | KeyModifiers::SHIFT)
        && app.pending_undo.is_some()
    {
        app.commit_pending_undo();
        return;
    }
    // F2 focus routing: `lsp.rename` claims F2 in the static keymap
    // (VS Code: rename symbol under cursor), but VS Code ALSO uses
    // F2 to rename the selected file when the tree is focused. When
    // no overlay is claiming keys and Focus == Tree, redirect F2 to
    // `file.rename`. This lives here (not in the keymap) so the
    // static registry can bind F2 to `lsp.rename` alone — dropping
    // the previous keymap-collision warning. 2026-07-08.
    if key.code == KeyCode::F(2)
        && key.modifiers.is_empty()
        && app.picker.is_none()
        && app.prompt.is_none()
        && app.whichkey.is_none()
        && app.context_menu.is_none()
        && app.menu_open.is_none()
        && app.focus == crate::focus::Focus::Tree
        && app.tree.selected_file().is_some()
    {
        let _ = crate::command::run("file.rename", app);
        return;
    }
    // Same idiom for Ctrl+D → `file.duplicate` when Focus == Tree.
    // The `editor.add_cursor_at_next_word` command owns `ctrl+d` in
    // the standard keymap and gets dispatched by the chord chain
    // BEFORE `handle_tree_key` runs — so its own Ctrl+D branch (which
    // routes to `file.duplicate`) never fired. This special-case
    // routes the key to the tree action first when tree is focused
    // and no overlay is claiming input. vscode-user-keyboard
    // 2026-07-10 SEV-2 fix.
    if key.code == KeyCode::Char('d')
        && key.modifiers == KeyModifiers::CONTROL
        && app.picker.is_none()
        && app.prompt.is_none()
        && app.whichkey.is_none()
        && app.context_menu.is_none()
        && app.menu_open.is_none()
        && app.focus == crate::focus::Focus::Tree
        && app.tree.selected_file().is_some()
    {
        let _ = crate::command::run("file.duplicate", app);
        return;
    }
    // Full-screen escape hatch: when full-screen is on and no
    // overlay is claiming Esc, treat Esc as "exit full-screen" so
    // the user is never trapped. Overlays (picker / prompt /
    // which-key) get first dibs by returning before this check below.
    if app.fullscreen_mode
        && key.code == KeyCode::Esc
        && app.picker.is_none()
        && app.prompt.is_none()
        && app.whichkey.is_none()
        && app.context_menu.is_none()
        && app.menu_open.is_none()
    {
        app.toggle_fullscreen_mode();
        return;
    }
    // Workspace-picker dropdown — when open, intercept keys so they
    // navigate the picker (not the editor below).
    if app.workspace_picker_open {
        match key.code {
            KeyCode::Esc => {
                app.workspace_picker_open = false;
                app.workspace_picker_filter.clear();
                return;
            }
            KeyCode::Char(c)
                if !key
                    .modifiers
                    .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT) =>
            {
                app.workspace_picker_filter.push(c);
                return;
            }
            _ => {
                // 2026-08-08 — Backspace / Ctrl+U / Ctrl+W / Ctrl+V.
                let r = crate::ui::text_input::handle_filter_shortcut(
                    key,
                    &mut app.workspace_picker_filter,
                    Some(&mut app.clipboard),
                );
                if r == crate::ui::text_input::TextKeyResult::Handled {
                    return;
                }
            }
        }
    }
    // Workspaces editor overlay — intercept keyboard so arrows
    // navigate, Enter edits, n adds, d deletes, Esc closes.
    if app.workspaces_editor_open && app.prompt.is_none() && app.context_menu.is_none() {
        let total = app.config.workspaces.len() + 1; // +1 for the "Add" action row
        match key.code {
            KeyCode::Esc => {
                app.close_workspaces_editor();
                return;
            }
            // Reorder (Shift+↑/↓ and `K`/`J`) MUST be matched
            // before the bare Up/Down arms below — otherwise the
            // unguarded ↑/↓ arms swallow the Shift variant.
            KeyCode::Up if key.modifiers.contains(KeyModifiers::SHIFT) => {
                let sel = app.workspaces_editor_selected;
                if sel < app.config.workspaces.len() {
                    app.workspaces_editor_move_up(sel);
                }
                return;
            }
            KeyCode::Down if key.modifiers.contains(KeyModifiers::SHIFT) => {
                let sel = app.workspaces_editor_selected;
                if sel < app.config.workspaces.len() {
                    app.workspaces_editor_move_down(sel);
                }
                return;
            }
            KeyCode::Char('K') => {
                let sel = app.workspaces_editor_selected;
                if sel < app.config.workspaces.len() {
                    app.workspaces_editor_move_up(sel);
                }
                return;
            }
            KeyCode::Char('J') => {
                let sel = app.workspaces_editor_selected;
                if sel < app.config.workspaces.len() {
                    app.workspaces_editor_move_down(sel);
                }
                return;
            }
            KeyCode::Up | KeyCode::Char('k') => {
                if app.workspaces_editor_selected > 0 {
                    app.workspaces_editor_selected -= 1;
                } else {
                    app.workspaces_editor_selected = total.saturating_sub(1);
                }
                return;
            }
            KeyCode::Down | KeyCode::Char('j') => {
                app.workspaces_editor_selected =
                    (app.workspaces_editor_selected + 1) % total.max(1);
                return;
            }
            KeyCode::Enter => {
                let sel = app.workspaces_editor_selected;
                if sel < app.config.workspaces.len() {
                    app.workspaces_editor_open_rename(sel);
                } else {
                    // + Add row.
                    crate::command::run("view.add_workspace", app);
                }
                return;
            }
            KeyCode::Char('n') => {
                crate::command::run("view.add_workspace", app);
                return;
            }
            KeyCode::Char('d') => {
                let sel = app.workspaces_editor_selected;
                if sel < app.config.workspaces.len() {
                    app.workspaces_editor_delete(sel);
                }
                return;
            }
            _ => {}
        }
    }
    // Dock widget kebab menu — when open, intercept keys so they
    // navigate the menu rather than falling through to editor /
    // tree handlers.
    if app.dock_kebab_menu.is_some() {
        let menu = app.dock_kebab_menu.as_ref().unwrap();
        let items_len = menu.items.len();
        match key.code {
            KeyCode::Esc => {
                app.dock_kebab_menu = None;
                return;
            }
            KeyCode::Down | KeyCode::Tab => {
                if let Some(m) = app.dock_kebab_menu.as_mut() {
                    let mut i = m.selected;
                    for _ in 0..items_len {
                        i = (i + 1) % items_len;
                        if matches!(
                            m.items[i],
                            crate::dock::KebabMenuItem::Header(_)
                                | crate::dock::KebabMenuItem::Separator
                        ) {
                            continue;
                        }
                        break;
                    }
                    m.selected = i;
                }
                return;
            }
            KeyCode::Up | KeyCode::BackTab => {
                if let Some(m) = app.dock_kebab_menu.as_mut() {
                    let mut i = m.selected;
                    for _ in 0..items_len {
                        i = if i == 0 { items_len - 1 } else { i - 1 };
                        if matches!(
                            m.items[i],
                            crate::dock::KebabMenuItem::Header(_)
                                | crate::dock::KebabMenuItem::Separator
                        ) {
                            continue;
                        }
                        break;
                    }
                    m.selected = i;
                }
                return;
            }
            KeyCode::Enter => {
                let (wid, item) = {
                    let m = app.dock_kebab_menu.as_ref().unwrap();
                    (m.widget_id, m.items.get(m.selected).copied())
                };
                if let Some(item) = item {
                    crate::dock::apply_kebab_choice(app, wid, item);
                }
                return;
            }
            _ => {}
        }
    }
    // Integrations rail filter — explicit focus (was auto-focused,
    // but that stole `:` / palette shortcuts / any global char while
    // the section was open; kept accreting gates for every collision
    // until 2026-07-04 flipped it to explicit). Focus is set by
    // pressing `/` in the panel or clicking the filter chip.
    // code-reviewer 2026-07-09: add `prompt.is_none()` +
    // `no_pane_cmdline.is_none()` guards for parity with the
    // other panels' hoisted absorb; the prior version could still
    // eat keys while a confirm dialog was open or the no-pane
    // cmdline was capturing.
    if app.focus == crate::focus::Focus::Tree
        && app.active_section == crate::app::ActivitySection::Integrations
        && app.picker.is_none()
        && app.integration_edit.is_none()
        && app.prompt.is_none()
        && app.no_pane_cmdline.is_none()
    {
        // Not-yet-focused: `/` enters filter mode (matches vim /
        // less search idiom). All other chars flow through so
        // global shortcuts still fire from the panel.
        if !app.integrations_panel_filter_focused {
            if let KeyCode::Char('/') = key.code
                && !key
                    .modifiers
                    .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT)
            {
                app.integrations_panel_filter_focused = true;
                return;
            }
        } else {
            // Focused: chars append, Backspace pops, Esc clears +
            // unfocuses, Enter commits + unfocuses.
            match key.code {
                KeyCode::Esc => {
                    app.integrations_panel_filter.clear();
                    app.integrations_panel_filter_focused = false;
                    return;
                }
                KeyCode::Enter => {
                    app.integrations_panel_filter_focused = false;
                    return;
                }
                KeyCode::Char(c)
                    if !key
                        .modifiers
                        .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT) =>
                {
                    app.integrations_panel_filter.push(c);
                    return;
                }
                _ => {
                    // 2026-08-08 — Backspace / Ctrl+U / Ctrl+W /
                    // Ctrl+V via the shared filter helper.
                    let r = crate::ui::text_input::handle_filter_shortcut(
                        key,
                        &mut app.integrations_panel_filter,
                        Some(&mut app.clipboard),
                    );
                    if r == crate::ui::text_input::TextKeyResult::Handled {
                        return;
                    }
                }
            }
        }
    }
    // HTTP rail filter — same `/` → focus, then char/backspace/Esc/Enter.
    if !app.http_panel_filter_focused
        && app.focus == crate::focus::Focus::Tree
        && app.active_section == crate::app::ActivitySection::Http
        && app.picker.is_none()
        && app.no_pane_cmdline.is_none()
        && let KeyCode::Char('/') = key.code
        && !key
            .modifiers
            .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT)
    {
        app.http_panel_filter_focused = true;
        return;
    }
    // Absorb block must re-check the same guards as the entry —
    // the `_filter_focused` flag alone would trap keys after
    // focus moves to a pane / a picker opens / a prompt fires.
    // nvchad-user + vscode-user-mouse + vscode-user-keyboard all
    // hit variants of that on 2026-07-09. Same guard-hoist
    // pattern for all four filter panels below.
    if app.http_panel_filter_focused
        && app.focus == crate::focus::Focus::Tree
        && app.active_section == crate::app::ActivitySection::Http
        && app.picker.is_none()
        && app.no_pane_cmdline.is_none()
        && app.prompt.is_none()
    {
        match key.code {
            KeyCode::Esc => {
                app.http_panel_filter.clear();
                app.http_panel_filter_focused = false;
                app.http_panel_cursor_reset();
                return;
            }
            KeyCode::Enter => {
                app.http_panel_filter_focused = false;
                // Filter accepted — snap cursor to first visible
                // row so `j`/`k`/Enter operate on the narrowed set.
                app.http_panel_cursor_reset();
                return;
            }
            KeyCode::Char(c)
                if !key
                    .modifiers
                    .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT) =>
            {
                app.http_panel_filter.push(c);
                app.http_panel_cursor_reset();
                return;
            }
            _ => {
                // 2026-08-08 — Backspace / Ctrl+U / Ctrl+W / Ctrl+V
                // via the shared filter helper. cursor_reset() runs
                // if the filter actually changed.
                let before = app.http_panel_filter.len();
                let r = crate::ui::text_input::handle_filter_shortcut(
                    key,
                    &mut app.http_panel_filter,
                    Some(&mut app.clipboard),
                );
                if r == crate::ui::text_input::TextKeyResult::Handled {
                    if app.http_panel_filter.len() != before {
                        app.http_panel_cursor_reset();
                    }
                    return;
                }
            }
        }
    }
    // HTTP panel row navigation — j/k / arrows / Enter when the
    // panel has focus and no filter's active. Keyboard-user SEV-2 #4
    // fix (2026-07-07).
    if app.focus == crate::focus::Focus::Tree
        && app.active_section == crate::app::ActivitySection::Http
        && !app.http_panel_filter_focused
        && app.picker.is_none()
        && app.no_pane_cmdline.is_none()
        && !key
            .modifiers
            .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT)
    {
        match key.code {
            KeyCode::Down | KeyCode::Char('j') => {
                app.http_panel_cursor_down();
                return;
            }
            KeyCode::Up | KeyCode::Char('k') => {
                app.http_panel_cursor_up();
                return;
            }
            KeyCode::Enter => {
                app.http_panel_cursor_activate();
                return;
            }
            _ => {}
        }
    }
    // TODOs / Notes rail filter — same `/` idiom as HTTP + Agents.
    // Focus on `/`, then intercept typing / backspace / Esc / Enter.
    if !app.todos_panel_filter_focused
        && app.focus == crate::focus::Focus::Tree
        && app.active_section == crate::app::ActivitySection::Todos
        && app.picker.is_none()
        && app.no_pane_cmdline.is_none()
        && let KeyCode::Char('/') = key.code
        && !key
            .modifiers
            .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT)
    {
        app.todos_panel_filter_focused = true;
        return;
    }
    if app.todos_panel_filter_focused
        && app.focus == crate::focus::Focus::Tree
        && app.active_section == crate::app::ActivitySection::Todos
        && app.picker.is_none()
        && app.no_pane_cmdline.is_none()
        && app.prompt.is_none()
    {
        match key.code {
            KeyCode::Esc => {
                app.todos_panel_filter.clear();
                app.todos_panel_filter_focused = false;
                return;
            }
            KeyCode::Enter => {
                app.todos_panel_filter_focused = false;
                return;
            }
            KeyCode::Char(c)
                if !key
                    .modifiers
                    .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT) =>
            {
                app.todos_panel_filter.push(c);
                return;
            }
            _ => {
                // 2026-08-08 — Backspace / Ctrl+U / Ctrl+W / Ctrl+V.
                let r = crate::ui::text_input::handle_filter_shortcut(
                    key,
                    &mut app.todos_panel_filter,
                    Some(&mut app.clipboard),
                );
                if r == crate::ui::text_input::TextKeyResult::Handled {
                    return;
                }
            }
        }
    }
    // Findings rail filter (2026-08-23 user ask) — mirrors the
    // TODOs block above verbatim. Findings is a workspace-scoped
    // *.md archive; the filter matches on the row's rendered
    // relative name.
    if !app.findings_panel_filter_focused
        && app.focus == crate::focus::Focus::Tree
        && app.active_section == crate::app::ActivitySection::Findings
        && app.picker.is_none()
        && app.no_pane_cmdline.is_none()
        && let KeyCode::Char('/') = key.code
        && !key
            .modifiers
            .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT)
    {
        app.findings_panel_filter_focused = true;
        return;
    }
    if app.findings_panel_filter_focused
        && app.focus == crate::focus::Focus::Tree
        && app.active_section == crate::app::ActivitySection::Findings
        && app.picker.is_none()
        && app.no_pane_cmdline.is_none()
        && app.prompt.is_none()
    {
        match key.code {
            KeyCode::Esc => {
                app.findings_panel_filter.clear();
                app.findings_panel_filter_focused = false;
                return;
            }
            KeyCode::Enter => {
                app.findings_panel_filter_focused = false;
                return;
            }
            KeyCode::Char(c)
                if !key
                    .modifiers
                    .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT) =>
            {
                app.findings_panel_filter.push(c);
                return;
            }
            _ => {
                let r = crate::ui::text_input::handle_filter_shortcut(
                    key,
                    &mut app.findings_panel_filter,
                    Some(&mut app.clipboard),
                );
                if r == crate::ui::text_input::TextKeyResult::Handled {
                    return;
                }
            }
        }
    }
    // Row nav on TODOs / Notes / Sessions when the panel has
    // focus and the filter isn't focused. Mirrors the HTTP
    // panel's j/k/arrow/Enter handling. vscode-user-keyboard
    // SEV-2 fix 2026-07-09.
    if app.focus == crate::focus::Focus::Tree
        && app.picker.is_none()
        && app.no_pane_cmdline.is_none()
        && app.prompt.is_none()
        && !key
            .modifiers
            .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT)
    {
        match (app.active_section, key.code) {
            (crate::app::ActivitySection::Todos, KeyCode::Down | KeyCode::Char('j'))
                if !app.todos_panel_filter_focused =>
            {
                app.todos_panel_cursor_down();
                return;
            }
            (crate::app::ActivitySection::Todos, KeyCode::Up | KeyCode::Char('k'))
                if !app.todos_panel_filter_focused =>
            {
                app.todos_panel_cursor_up();
                return;
            }
            (crate::app::ActivitySection::Todos, KeyCode::Enter)
                if !app.todos_panel_filter_focused =>
            {
                app.todos_panel_activate();
                return;
            }
            (crate::app::ActivitySection::Notes, KeyCode::Down | KeyCode::Char('j'))
                if !app.notes_panel_filter_focused =>
            {
                app.notes_panel_cursor_down();
                return;
            }
            (crate::app::ActivitySection::Notes, KeyCode::Up | KeyCode::Char('k'))
                if !app.notes_panel_filter_focused =>
            {
                app.notes_panel_cursor_up();
                return;
            }
            (crate::app::ActivitySection::Notes, KeyCode::Enter)
                if !app.notes_panel_filter_focused =>
            {
                app.notes_panel_activate();
                return;
            }
            (crate::app::ActivitySection::Sessions, KeyCode::Down | KeyCode::Char('j'))
                if !app.sessions_panel_filter_focused =>
            {
                app.sessions_panel_cursor_down();
                return;
            }
            (crate::app::ActivitySection::Sessions, KeyCode::Up | KeyCode::Char('k'))
                if !app.sessions_panel_filter_focused =>
            {
                app.sessions_panel_cursor_up();
                return;
            }
            (crate::app::ActivitySection::Sessions, KeyCode::Enter)
                if !app.sessions_panel_filter_focused =>
            {
                app.sessions_panel_activate();
                return;
            }
            _ => {}
        }
    }
    if !app.sessions_panel_filter_focused
        && app.focus == crate::focus::Focus::Tree
        && app.active_section == crate::app::ActivitySection::Sessions
        && app.picker.is_none()
        && app.no_pane_cmdline.is_none()
        && let KeyCode::Char('/') = key.code
        && !key
            .modifiers
            .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT)
    {
        app.sessions_panel_filter_focused = true;
        return;
    }
    if app.sessions_panel_filter_focused
        && app.focus == crate::focus::Focus::Tree
        && app.active_section == crate::app::ActivitySection::Sessions
        && app.picker.is_none()
        && app.no_pane_cmdline.is_none()
        && app.prompt.is_none()
    {
        match key.code {
            KeyCode::Esc => {
                app.sessions_panel_filter.clear();
                app.sessions_panel_filter_focused = false;
                return;
            }
            KeyCode::Enter => {
                app.sessions_panel_filter_focused = false;
                return;
            }
            KeyCode::Char(c)
                if !key
                    .modifiers
                    .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT) =>
            {
                app.sessions_panel_filter.push(c);
                return;
            }
            _ => {
                // 2026-08-08 — Backspace / Ctrl+U / Ctrl+W / Ctrl+V.
                let r = crate::ui::text_input::handle_filter_shortcut(
                    key,
                    &mut app.sessions_panel_filter,
                    Some(&mut app.clipboard),
                );
                if r == crate::ui::text_input::TextKeyResult::Handled {
                    return;
                }
            }
        }
    }
    if !app.notes_panel_filter_focused
        && app.focus == crate::focus::Focus::Tree
        && app.active_section == crate::app::ActivitySection::Notes
        && app.picker.is_none()
        && app.no_pane_cmdline.is_none()
        && let KeyCode::Char('/') = key.code
        && !key
            .modifiers
            .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT)
    {
        app.notes_panel_filter_focused = true;
        return;
    }
    if app.notes_panel_filter_focused
        && app.focus == crate::focus::Focus::Tree
        && app.active_section == crate::app::ActivitySection::Notes
        && app.picker.is_none()
        && app.no_pane_cmdline.is_none()
        && app.prompt.is_none()
    {
        match key.code {
            KeyCode::Esc => {
                app.notes_panel_filter.clear();
                app.notes_panel_filter_focused = false;
                return;
            }
            KeyCode::Enter => {
                app.notes_panel_filter_focused = false;
                return;
            }
            KeyCode::Char(c)
                if !key
                    .modifiers
                    .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT) =>
            {
                app.notes_panel_filter.push(c);
                return;
            }
            _ => {
                // 2026-08-08 — Backspace / Ctrl+U / Ctrl+W / Ctrl+V.
                let r = crate::ui::text_input::handle_filter_shortcut(
                    key,
                    &mut app.notes_panel_filter,
                    Some(&mut app.clipboard),
                );
                if r == crate::ui::text_input::TextKeyResult::Handled {
                    return;
                }
            }
        }
    }
    // Agents rail filter — `/` in the panel focuses filter (matches
    // vim / less search idiom, mirrors the Integrations panel behavior).
    // Once focused, intercept typing / backspace / Esc / Enter.
    if !app.agents_panel_filter_focused
        && app.focus == crate::focus::Focus::Tree
        && app.active_section == crate::app::ActivitySection::Agents
        && app.picker.is_none()
        && app.no_pane_cmdline.is_none()
        && let KeyCode::Char('/') = key.code
        && !key
            .modifiers
            .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT)
    {
        app.agents_panel_filter_focused = true;
        return;
    }
    // code-reviewer 2026-07-09: agents' absorb also needed the
    // guard-hoist — same class as the four filter panels fixed
    // in the parent commit.
    if app.agents_panel_filter_focused
        && app.focus == crate::focus::Focus::Tree
        && app.active_section == crate::app::ActivitySection::Agents
        && app.picker.is_none()
        && app.no_pane_cmdline.is_none()
        && app.prompt.is_none()
    {
        match key.code {
            KeyCode::Esc => {
                app.agents_panel_filter.clear();
                app.agents_panel_filter_focused = false;
                return;
            }
            KeyCode::Enter => {
                app.agents_panel_filter_focused = false;
                return;
            }
            KeyCode::Char(c)
                if !key
                    .modifiers
                    .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT) =>
            {
                app.agents_panel_filter.push(c);
                return;
            }
            _ => {
                // 2026-08-08 — Backspace / Ctrl+U / Ctrl+W / Ctrl+V.
                let r = crate::ui::text_input::handle_filter_shortcut(
                    key,
                    &mut app.agents_panel_filter,
                    Some(&mut app.clipboard),
                );
                if r == crate::ui::text_input::TextKeyResult::Handled {
                    return;
                }
            }
        }
    }
    // Cloud Agents quick-fire prompt — `/` to focus (matches the
    // Integrations / Agents / Settings idiom), then chars append,
    // Enter submits, Esc clears + unfocuses.
    if !app.cloud_run_prompt_focused
        && app.focus == crate::focus::Focus::Tree
        && app.active_section == crate::app::ActivitySection::CloudAgents
        && app.picker.is_none()
        && app.no_pane_cmdline.is_none()
        && let KeyCode::Char('/') = key.code
        && !key
            .modifiers
            .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT)
    {
        app.cloud_run_prompt_focused = true;
        return;
    }
    // Cloud Agents quick-fire prompt input (hybrid UX — daily-driver
    // path that uses the saved [cloud_run.defaults]). Absorb guard-
    // hoisted 2026-07-10 to match the other panels — was capturing
    // keys across section changes and picker opens (SEV-2 class).
    if app.cloud_run_prompt_focused
        && app.focus == crate::focus::Focus::Tree
        && app.active_section == crate::app::ActivitySection::CloudAgents
        && app.picker.is_none()
        && app.no_pane_cmdline.is_none()
        && app.prompt.is_none()
    {
        match key.code {
            KeyCode::Esc => {
                app.cloud_run_prompt_input.clear();
                app.cloud_run_prompt_focused = false;
                return;
            }
            KeyCode::Enter => {
                app.cloud_run_quick_send();
                return;
            }
            KeyCode::Char(c)
                if !key
                    .modifiers
                    .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT) =>
            {
                app.cloud_run_prompt_input.push(c);
                return;
            }
            _ => {
                // 2026-08-08 — Backspace / Ctrl+U / Ctrl+W / Ctrl+V.
                let r = crate::ui::text_input::handle_filter_shortcut(
                    key,
                    &mut app.cloud_run_prompt_input,
                    Some(&mut app.clipboard),
                );
                if r == crate::ui::text_input::TextKeyResult::Handled {
                    return;
                }
            }
        }
    }
    // Same idiom for the Cloud Agents panel filter.
    if app.cloud_agents_filter_focused
        && app.focus == crate::focus::Focus::Tree
        && app.active_section == crate::app::ActivitySection::CloudAgents
        && app.picker.is_none()
        && app.no_pane_cmdline.is_none()
        && app.prompt.is_none()
    {
        match key.code {
            KeyCode::Esc => {
                app.cloud_agents_filter.clear();
                app.cloud_agents_filter_focused = false;
                return;
            }
            KeyCode::Enter => {
                app.cloud_agents_filter_focused = false;
                return;
            }
            KeyCode::Char(c)
                if !key
                    .modifiers
                    .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT) =>
            {
                app.cloud_agents_filter.push(c);
                return;
            }
            _ => {
                // 2026-08-08 — Backspace / Ctrl+U / Ctrl+W / Ctrl+V.
                let r = crate::ui::text_input::handle_filter_shortcut(
                    key,
                    &mut app.cloud_agents_filter,
                    Some(&mut app.clipboard),
                );
                if r == crate::ui::text_input::TextKeyResult::Handled {
                    return;
                }
            }
        }
    }
    // NewCloudRunWizard (Cloud Agents version) keys.
    if app
        .active
        .and_then(|i| app.panes.get(i))
        .map(|p| matches!(p, crate::pane::Pane::NewCloudRunWizard(_)))
        .unwrap_or(false)
    {
        match key.code {
            KeyCode::Esc => {
                app.new_cloud_run_wizard_close();
                return;
            }
            KeyCode::Up | KeyCode::Char('k') => {
                app.new_cloud_run_wizard_move(-1);
                return;
            }
            KeyCode::Down | KeyCode::Char('j') => {
                app.new_cloud_run_wizard_move(1);
                return;
            }
            KeyCode::Backspace => {
                app.new_cloud_run_wizard_backspace();
                return;
            }
            KeyCode::Tab | KeyCode::Enter => {
                app.new_cloud_run_wizard_next();
                return;
            }
            KeyCode::Char(ch)
                if !key
                    .modifiers
                    .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT) =>
            {
                app.new_cloud_run_wizard_type(ch);
                return;
            }
            _ => {}
        }
    }
    // NewCloudAgentWizard pane — when active, intercept arrows,
    // Tab, Enter, Esc, and typing so the keys don't fall through
    // to the editor underneath.
    if app
        .active
        .and_then(|i| app.panes.get(i))
        .map(|p| matches!(p, crate::pane::Pane::NewCloudAgentWizard(_)))
        .unwrap_or(false)
    {
        match key.code {
            KeyCode::Esc => {
                app.new_cloud_agent_wizard_close();
                return;
            }
            KeyCode::Up | KeyCode::Char('k') => {
                app.new_cloud_agent_wizard_move(-1);
                return;
            }
            KeyCode::Down | KeyCode::Char('j') => {
                app.new_cloud_agent_wizard_move(1);
                return;
            }
            KeyCode::Backspace => {
                app.new_cloud_agent_wizard_backspace();
                return;
            }
            KeyCode::Tab => {
                app.new_cloud_agent_wizard_next();
                return;
            }
            KeyCode::Enter => {
                app.new_cloud_agent_wizard_next();
                return;
            }
            KeyCode::Char(' ') => {
                app.new_cloud_agent_wizard_toggle();
                return;
            }
            KeyCode::Char('a') => {
                app.new_cloud_agent_wizard_select_all();
                return;
            }
            KeyCode::Char(ch)
                if !key
                    .modifiers
                    .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT) =>
            {
                app.new_cloud_agent_wizard_type(ch);
                return;
            }
            _ => {}
        }
    }
    // Git-palette filter input — when focused, intercept typing /
    // backspace / Esc here so the keys don't fall through to the
    // editor. 2026-07-10 audit: guard-hoisted to match the other
    // panel filters (same absorb-block class as the SEV-2 fixes).
    if app.git_palette_filter_focused
        && app.focus == crate::focus::Focus::Tree
        && app.active_section == crate::app::ActivitySection::Git
        && app.picker.is_none()
        && app.no_pane_cmdline.is_none()
        && app.prompt.is_none()
    {
        match key.code {
            KeyCode::Esc => {
                app.git_palette_filter.clear();
                app.git_palette_filter_focused = false;
                return;
            }
            KeyCode::Enter => {
                app.git_palette_filter_focused = false;
                return;
            }
            KeyCode::Char(c)
                if !key
                    .modifiers
                    .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT) =>
            {
                app.git_palette_filter.push(c);
                return;
            }
            _ => {
                // 2026-08-08 — Backspace / Ctrl+U / Ctrl+W / Ctrl+V.
                let r = crate::ui::text_input::handle_filter_shortcut(
                    key,
                    &mut app.git_palette_filter,
                    Some(&mut app.clipboard),
                );
                if r == crate::ui::text_input::TextKeyResult::Handled {
                    return;
                }
            }
        }
    }
    // Menu-bar dropdown — intercept keys before anything else so
    // Esc / arrows / Enter target the menu instead of the editor.
    if app.menu_open.is_some() && handle_menu_key(app, key) {
        return;
    }
    // Menu summon — Alt+letter opens the corresponding menu,
    // F10 opens the first menu. Gated by menu_bar mode != "hidden".
    if app.menu_open.is_none()
        && app.config.ui.menu_bar != "hidden"
        && try_open_menu_from_key(app, key)
    {
        return;
    }
    // 2026-06-22 — Esc during an in-flight tree-file drag aborts
    // the drag: clears tree_drag + the drop-zone overlay. User
    // can release the mouse anywhere safely after that without
    // triggering drag-to-split. Matches the VS Code / macOS
    // convention of Esc-cancels-drag.
    if key.code == KeyCode::Esc && app.tree_drag.is_some() {
        app.tree_drag = None;
        app.rects.tab_drop_target = None;
        return;
    }
    // Same idiom for the hover-help drag-resize handle. If the terminal
    // ever fails to deliver the mouse-up (focus loss mid-drag, SGR glitch,
    // mouse leaves the window), the drag stays armed and would silently
    // intercept the next unrelated left-drag anywhere. Esc gives the user
    // a bailout.
    if key.code == KeyCode::Esc && app.hover_help_drag.is_some() {
        app.hover_help_drag = None;
        return;
    }
    // AI ghost-text: while a suggestion is showing, bare `Tab` accepts
    // all of it, `Ctrl+Right` accepts the next word, `Ctrl+Down` the
    // next line (both leave the remainder as a ghost); any other key
    // dismisses it (and then does its normal thing).
    //
    // 2026-08-19 (#1070) — accepting a ghost also dismisses any open
    // LSP completion popup. The two UIs commonly overlap: the user
    // types "reset(" which auto-triggers `textDocument/completion`
    // AND fires the ghost debounce; the ghost lands first, but the
    // completion popup stays visible underneath. Bare Tab hits this
    // early-return before the popup's own Tab-accept branch below
    // (line ~2335), so without this the popup lingers indefinitely.
    // Confirmed via hero-tape review: the popup stuck around for
    // ~15s across the hover-help + settings beats.
    if app.has_ghost_suggestion() {
        if key.code == KeyCode::Tab && key.modifiers.is_empty() {
            app.accept_ghost_suggestion();
            app.completion = None;
            return;
        }
        if key.code == KeyCode::Right && key.modifiers == KeyModifiers::CONTROL {
            app.accept_ghost_word();
            app.completion = None;
            return;
        }
        if key.code == KeyCode::Down && key.modifiers == KeyModifiers::CONTROL {
            app.accept_ghost_line();
            app.completion = None;
            return;
        }
        app.clear_ghost_suggestion();
    }
    // 2026-06-08 vscode hunt SEV-2: `Ctrl+S` (Save) is a global
    // muscle-memory reflex — VS Code fires it from any focus. mnml
    // used to swallow it inside every overlay (palette, prompts,
    // settings) which led to silent data loss: "find something,
    // hit Ctrl+S to checkpoint, keep going" left the file dirty
    // with no toast, no error. Intercept here before any
    // overlay-consuming branch runs. Overlay state is untouched —
    // save fires, the user keeps doing whatever they were doing.
    // Skip when a pty pane has the focus (the shell legitimately
    // wants `Ctrl+S` for XOFF flow control); the keymap below
    // handles the not-in-overlay case the same way it did before.
    if key.code == KeyCode::Char('s')
        && key.modifiers == KeyModifiers::CONTROL
        && !matches!(
            app.active.and_then(|i| app.panes.get(i)),
            Some(Pane::Pty(_))
        )
        // R10 keyboard SEV-1 (2026-08-11) — the Integration Configure
        // overlay owns Ctrl+S itself (`save_integration_settings`).
        // The interceptor used to fire global `save_active` first,
        // and the pane's handler at overlay.rs:41 never ran. Footer
        // said `[Ctrl+S] save` and did nothing. Skip the interceptor
        // so the overlay handler sees the chord.
        && app.integration_settings.is_none()
        // R11 vscode-keyboard SEV-2 (2026-08-23) — the `Ctrl+K
        // Ctrl+S` keymap chord (opens keys.edit) was being shadowed
        // by this interceptor: after `Ctrl+K` the chord chain
        // was pending, and the bare `Ctrl+S` step fired save
        // instead of resolving the sequence. Skip when a chord
        // chain is mid-flight so `dispatch_chord_chain` sees the
        // second key. Same gate shape as vim_reserves_key /
        // pty_reserves_key elsewhere in this file.
        && app.pending_chord_seq.is_empty()
    {
        // Anything in flight that would have consumed the chord
        // (palette / prompt / settings) is still alive afterwards;
        // we just don't let it eat the save.
        app.save_active();
        return;
    }
    // Scratch terminal — when focused, route keystrokes to the pty
    // (with Esc as the way out). The chord that toggles it (`term.
    // scratch_toggle`) still works as the close gesture because the
    // command resolver runs against the keymap below — but only when
    // the scratch term isn't focused.
    if let Some(scratch) = app.scratch_term.as_mut()
        && scratch.focused
    {
        // keyboard-round-12 SEV-2 2026-07-14 — Ctrl+` must escape
        // the pty-forwarding branch so it can reach the toggle
        // command and CLOSE the scratch term. Was: every non-Esc
        // key (including the toggle chord itself) got forwarded
        // to the child, which just typed a backtick into the
        // shell — the close half of the toggle was unreachable
        // from the keyboard. Also handle Ctrl+~ / Ctrl+Shift+` in
        // case a terminal delivers Shift with the tilde form.
        let is_close_chord = matches!(key.code, KeyCode::Char('`') | KeyCode::Char('~'))
            && key.modifiers.contains(KeyModifiers::CONTROL);
        if is_close_chord {
            app.toggle_scratch_term();
            return;
        }
        if key.code == KeyCode::Esc {
            scratch.focused = false;
            return;
        }
        let bytes = crate::app::dispatch::pty_key_bytes(key);
        if !bytes.is_empty() {
            scratch.session.write_bytes(&bytes);
        }
        return;
    }
    // Native mixr panel — when focused, route *every* key (incl. Esc,
    // which mixr uses for back-navigation) to mixr over the wire.
    // Startup picker intercept — when the launch-time chooser is up,
    // it owns the keyboard. Esc / q dismisses; arrows + digits move /
    // commit; everything else is swallowed so it doesn't leak through
    // to the underlying editor.
    if app.startup_picker.is_some() {
        match key.code {
            KeyCode::Esc | KeyCode::Char('q') => {
                app.dismiss_startup_picker();
            }
            KeyCode::Up | KeyCode::Char('k') => {
                app.startup_picker_move(-1);
            }
            KeyCode::Down | KeyCode::Char('j') => {
                app.startup_picker_move(1);
            }
            KeyCode::Enter => {
                if let Some(action) = app.startup_picker_commit() {
                    fire_startup_action(action, app);
                }
            }
            KeyCode::Char(c) if c.is_ascii_digit() && c != '0' => {
                if let Some(action) = app.startup_picker_press_digit(c) {
                    fire_startup_action(action, app);
                }
            }
            _ => {}
        }
        return;
    }
    // Macro recording — capture every keystroke that flows through here.
    // Replaying explicitly skips this so it doesn't re-record into a new
    // macro mid-replay.
    if let crate::app::MacroState::Recording { keys, .. } = &mut app.macro_state {
        keys.push(key);
    }
    // Esc dismisses any visible toast (visual fluff the user explicitly
    // said "go away" to). Doesn't return — other Esc handlers further
    // down still fire (e.g. exit overlays, leave visual mode).
    if key.code == KeyCode::Esc {
        app.toast = None;
        app.toast_stack.clear();
        // F1 discovery overlay closes on Esc too — same dismiss gesture as
        // tooltips/toasts.
        app.show_discovery_overlay = false;
        // Welcome overlay also dismisses on Esc (and persists the marker
        // so it doesn't auto-reopen next launch). Only when it's the
        // thing on screen — this block runs before the wizard / prompt
        // handlers below, so `show_welcome` alone would let an Esc
        // aimed at those retire a card the user never saw (#1216).
        if app.welcome_visible() {
            app.dismiss_welcome();
        }
        app.show_about = false;
    }
    // The AI usage overlay was retired 2026-08-16 in favor of a
    // proper `Pane::AiUsage` — no key-steal shim needed anymore.
    // Flash intercept: when label overlay is up, Esc cancels; a printable
    // char matching a label commits the jump; an unmatched key cancels
    // and falls through to normal dispatch.
    if app.flash_state.is_some() {
        if key.code == KeyCode::Esc {
            app.flash_cancel();
            return;
        }
        if let KeyCode::Char(c) = key.code
            && app.flash_consume_char(c)
        {
            return;
        }
        // No match — drop state and re-dispatch the keystroke normally.
        app.flash_cancel();
    }
    // The settings overlay steals all keys until it's saved (Enter) or
    // cancelled (Esc). Keyboard-only — see CLAUDE.md's "Family settings
    // UI convention".
    if app.settings_overlay.is_some() {
        handle_settings_overlay_key(app, key);
        return;
    }
    // First-launch wizard — steals all keys until Finish (Enter) or
    // Ask-me-later (Esc). Sits ABOVE the settings-overlay branch
    // because we want the wizard to win when both are somehow open
    // (shouldn't happen; belt-and-braces).
    if app.first_launch.is_some() {
        crate::tui::handlers::overlay::handle_first_launch_key(app, key);
        return;
    }
    // Per-integration Settings pane — same modal-precedence idea.
    if app.integration_settings.is_some() {
        crate::tui::handlers::overlay::handle_integration_settings_key(app, key);
        return;
    }
    // #20 Pattern B — a pending confirm modal wins over everything
    // else. Blocks all input until dismissed (Esc / N) or fired
    // (Enter / Y).
    if app.pending_confirm.is_some() {
        crate::tui::handlers::overlay::handle_confirm_modal_key(app, key);
        return;
    }
    // An open picker / palette overlay steals all keys until it's
    // dismissed. Checked BEFORE the integration-edit panel so Ctrl+G
    // from inside the edit panel (which opens the glyph picker on
    // top) routes subsequent keys to the picker's filter input,
    // not back into the Glyph field char-by-char.
    if app.picker.is_some() {
        handle_picker_key(app, key);
        return;
    }
    // Integration edit panel — all-keys-stolen while open; Enter
    // saves, Esc cancels, Tab cycles fields, ←→ cycles color, other
    // chars type into the focused text field.
    // Glyph builder is checked BEFORE integration_edit because when
    // both are open (edit panel → glyph action menu → builder), the
    // builder is the visual front layer. Reverse order made Esc
    // close the edit panel first (behind) then the builder — user
    // saw two Escs to close what they expected to be one.
    if app.glyph_builder.is_some() {
        handle_glyph_builder_key(app, key);
        return;
    }
    if app.integration_edit.is_some() {
        handle_integration_edit_key(app, key);
        return;
    }
    // Search activity-bar section: input focused → printable keys
    // append to the query, Backspace deletes, Enter runs the grep,
    // ↑↓ navigates results, Esc blurs.
    if app.search_input_focused {
        handle_search_section_key(app, key);
        return;
    }
    // Git activity-bar section: commit textarea focused → printables
    // append to the buffer, Backspace deletes, Ctrl+Enter commits,
    // Esc blurs.
    if app.git_section_commit_focused {
        handle_git_section_commit_key(app, key);
        return;
    }
    // Help overlay — scroll + dismiss. No editing.
    if app.help_overlay.is_some() {
        handle_help_overlay_key(app, key);
        return;
    }
    // The LSP signature-help popup: Esc dismisses; Up / Down cycle through
    // overload signatures (only when there's more than one — otherwise the
    // arrow keys still navigate the editor). Any other key falls through (we
    // want typing to continue updating the popup, not dismiss it). Cursor
    // jumps via commands clear the popup separately.
    if let Some(sig) = app.signature.as_mut() {
        match key.code {
            KeyCode::Esc => {
                app.signature = None;
                return;
            }
            KeyCode::Down if sig.signatures.len() > 1 => {
                sig.cycle();
                return;
            }
            KeyCode::Up if sig.signatures.len() > 1 => {
                sig.cycle_prev();
                return;
            }
            _ => {}
        }
    }
    // Peek-definition overlay — Esc closes; arrows / j / k / PgUp /
    // PgDn scroll within the box; anything else closes + falls
    // through to normal handling.
    if app.peek_overlay.is_some() {
        match key.code {
            KeyCode::Esc => {
                app.peek_overlay = None;
                return;
            }
            KeyCode::Up | KeyCode::Char('k') => {
                if let Some(po) = &mut app.peek_overlay {
                    po.scroll_up();
                }
                return;
            }
            KeyCode::Down | KeyCode::Char('j') => {
                if let Some(po) = &mut app.peek_overlay {
                    po.scroll_down();
                }
                return;
            }
            KeyCode::PageUp => {
                if let Some(po) = &mut app.peek_overlay {
                    for _ in 0..5 {
                        po.scroll_up();
                    }
                }
                return;
            }
            KeyCode::PageDown => {
                if let Some(po) = &mut app.peek_overlay {
                    for _ in 0..5 {
                        po.scroll_down();
                    }
                }
                return;
            }
            _ => {
                // 2026-06-21 lsp-cheat-test SEV-2: was falling
                // through to the editor, so in vim mode pressing
                // `x` to dismiss the overlay also deleted the
                // char under cursor. Now: close + EAT the
                // keystroke. User can re-issue if they actually
                // wanted to do something with it.
                app.peek_overlay = None;
                return;
            }
        }
    }
    // An LSP hover popup is up: arrows / j / k / PgUp / PgDn scroll it; Esc
    // closes it; anything else closes it and is then handled normally.
    if app.hover.is_some() {
        match key.code {
            KeyCode::Esc => {
                app.hover = None;
                return;
            }
            KeyCode::Up | KeyCode::Char('k') => {
                if let Some(h) = &mut app.hover {
                    h.scroll_by(-1);
                }
                return;
            }
            KeyCode::Down | KeyCode::Char('j') => {
                if let Some(h) = &mut app.hover {
                    h.scroll_by(1);
                }
                return;
            }
            KeyCode::PageUp => {
                if let Some(h) = &mut app.hover {
                    h.scroll_by(-6);
                }
                return;
            }
            KeyCode::PageDown => {
                if let Some(h) = &mut app.hover {
                    h.scroll_by(6);
                }
                return;
            }
            _ => app.hover = None, // fall through to normal handling
        }
    }
    // An as-you-type LSP completion popup is up: arrows / Ctrl+N·P move the
    // selection, Tab / Enter accept, Esc dismisses it; identifier keys (and `.`,
    // `:`, Backspace) fall through to the editor — the resulting edit re-filters
    // it (`App::completion_on_edit`); anything else dismisses it and is handled
    // normally.
    if app.completion.is_some() {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        match key.code {
            KeyCode::Esc => {
                app.completion = None;
                return;
            }
            KeyCode::Tab | KeyCode::Enter => {
                // While a snippet placeholder cycle is active, Tab / Shift+Tab
                // navigate placeholders (dismissing this popup) instead of
                // accepting a completion — otherwise an as-you-type popup that
                // happened to be open races with the snippet's Tab and steals
                // it (the flaky-on-CI snippet failures). Enter still accepts.
                // SHIFT modifier honoured so Shift+Tab retreats rather than
                // inadvertently advancing forward (latent bug surfaced by the
                // 2026-06-26 review of the flake).
                if key.code == KeyCode::Tab && app.snippet_session.is_some() {
                    app.completion = None;
                    if key.modifiers.contains(KeyModifiers::SHIFT) {
                        app.snippet_prev_placeholder();
                    } else {
                        app.snippet_next_placeholder();
                    }
                } else {
                    app.completion_accept();
                }
                return;
            }
            KeyCode::Up => {
                app.completion_move(-1);
                return;
            }
            KeyCode::Down => {
                app.completion_move(1);
                return;
            }
            KeyCode::Char('p') if ctrl => {
                app.completion_move(-1);
                return;
            }
            KeyCode::Char('n') if ctrl => {
                app.completion_move(1);
                return;
            }
            // Ctrl+K / Ctrl+J — vim-style alternates for Up / Down.
            KeyCode::Char('k') if ctrl => {
                app.completion_move(-1);
                return;
            }
            KeyCode::Char('j') if ctrl => {
                app.completion_move(1);
                return;
            }
            KeyCode::PageUp => {
                app.completion_move(-8);
                return;
            }
            KeyCode::PageDown => {
                app.completion_move(8);
                return;
            }
            KeyCode::Char(c)
                if !ctrl && (c.is_alphanumeric() || c == '_' || c == '.' || c == ':') => {}
            KeyCode::Backspace => {}
            _ => app.completion = None, // fall through, handled normally
        }
    }
    // A snippet placeholder cycle is active: Tab jumps forward to the next
    // `$N` / `$0` stop; Shift-Tab walks back to the previous stop; Esc
    // dismisses. Anything else falls through (typing, arrows, etc. all work
    // normally — the session just tracks length deltas so the next Tab
    // targets the right spot).
    if app.snippet_session.is_some() {
        match key.code {
            // Shift+Tab (some terminals only synthesize BackTab; kitty etc.
            // send Tab+Shift) → previous placeholder.
            KeyCode::Tab if key.modifiers.contains(KeyModifiers::SHIFT) => {
                app.snippet_prev_placeholder();
                return;
            }
            KeyCode::Tab => {
                app.snippet_next_placeholder();
                return;
            }
            KeyCode::BackTab => {
                app.snippet_prev_placeholder();
                return;
            }
            KeyCode::Esc => {
                app.snippet_session = None;
                return;
            }
            _ => {} // fall through, handled normally
        }
    }
    // The right-click context menu steals keys: ↑↓/jk move, Enter runs, Esc closes.
    if app.context_menu.is_some() {
        match key.code {
            KeyCode::Up | KeyCode::Char('k') => app.context_menu_move(-1),
            KeyCode::Down | KeyCode::Char('j') => app.context_menu_move(1),
            // `\u{2192}` / `l` opens the focused row's child; `\u{2190}` / `h`
            // steps back out to the parent without losing it. Esc still
            // closes the whole chain, because a user reaching for Esc
            // wants out of the menu, not one level of it.
            KeyCode::Right | KeyCode::Char('l') => {
                if let Some(m) = app.context_menu.as_ref() {
                    let i = m.selected;
                    let curatable = m.curatable;
                    if app.context_menu_row_has_submenu(i) {
                        app.open_context_submenu(i);
                    } else if curatable {
                        // `→` means "more about this row" either way, so
                        // the kebab is not mouse-only.
                        app.open_menu_row_options(i);
                    }
                }
            }
            KeyCode::Left | KeyCode::Char('h') => app.close_context_submenu(),
            KeyCode::Enter => app.context_menu_accept(),
            KeyCode::Esc => app.context_menu_cancel(),
            _ => {} // keep the menu up
        }
        return;
    }
    // The interactive replace overlay (`:%s/.../.../c`) steals keys:
    // y = replace this, n = skip, a = replace all remaining, q/Esc = quit.
    // Per-match cursor jump is handled by App; we just route the key.
    if app.replace_confirm.is_some() {
        match key.code {
            KeyCode::Char('y' | 'Y') => app.replace_confirm_yes(),
            KeyCode::Char('n' | 'N') => app.replace_confirm_no(),
            KeyCode::Char('a' | 'A') => app.replace_confirm_all(),
            KeyCode::Char('q' | 'Q') | KeyCode::Esc => app.replace_confirm_quit(),
            _ => {}
        }
        return;
    }
    // The "unsaved changes" confirm overlay steals keys: s/Enter = Save, d = Discard, c/Esc = Cancel.
    if app.close_prompt.is_some() {
        match key.code {
            KeyCode::Char('s' | 'S') | KeyCode::Enter => app.close_prompt_resolve(0),
            KeyCode::Char('d' | 'D') => app.close_prompt_resolve(1),
            KeyCode::Char('c' | 'C') | KeyCode::Esc => app.close_prompt_resolve(2),
            _ => {}
        }
        return;
    }
    // The single-line text-input overlay (commit message, …) steals keys.
    if app.prompt.is_some() {
        // R10 vscode-keyboard SEV-2 (2026-08-11) — Ctrl+Shift+P
        // from within a prompt should dismiss the prompt and open
        // the palette, matching VS Code + the earlier fix in
        // `open_command_palette`. Without this guard the prompt
        // handler ate the chord before palette-open ran, and Esc
        // then leaked stray keys into the underneath prompt.
        if key.code == KeyCode::Char('P')
            && key
                .modifiers
                .contains(KeyModifiers::CONTROL | KeyModifiers::SHIFT)
        {
            app.open_command_palette();
            return;
        }
        handle_prompt_key(app, key);
        return;
    }
    // A leader sequence in flight: walk the which-key trie until a leaf / dead end / Esc.
    if app.whichkey.is_some() {
        match key.code {
            KeyCode::Esc => app.whichkey_cancel(),
            KeyCode::Backspace => app.whichkey_cancel(),
            KeyCode::Char(c) => app.whichkey_feed(c),
            _ => {} // other keys: keep the popup up
        }
        return;
    }

    // Esc aborts an in-flight chord-chain pending WITHOUT firing the
    // inner fallback. Vim's convention — without this, `ctrl+k` then
    // Esc would still commit to `whichkey.leader` via the timeout
    // fallback, defeating the purpose of an abort.
    if matches!(key.code, KeyCode::Esc) && !app.pending_chord_seq.is_empty() {
        app.pending_chord_seq.clear();
        app.pending_chord_deadline = None;
        app.pending_chord_fallback = None;
        return;
    }

    // 2026-06-20 — Esc on bare focus with in-flight HTTP work
    // aborts. Runs AFTER overlay/cmdline gates so it doesn't
    // steal Esc from picker / prompt / cmdline cancellation,
    // but BEFORE the pane-focused handlers so users don't lose
    // the chord to a deeper handler. Idempotent — also fine if
    // no work is in flight.
    if matches!(key.code, KeyCode::Esc)
        && app.picker.is_none()
        && app.prompt.is_none()
        && app.context_menu.is_none()
        && app.no_pane_cmdline.is_none()
        && (app.http_bench_rx.is_some()
            || app.http_sync_rx.is_some()
            || app.lookup_fire_rx.is_some())
    {
        app.http_abort_all();
        return;
    }

    // App-level chords (any focus) resolve through the one keymap table — registry
    // defaults overlaid with `[keys.*]` config. These win over the focused pane;
    // all built-in defaults are modified/F-keys the editor doesn't want anyway.
    //
    // Chord-chain aware: feeds the key into the pending sequence and dispatches
    // based on the resolve_seq result. See `dispatch_chord_chain` for the full
    // state machine. Returns true if the key was consumed (no fall-through);
    // false if it wasn't (fall through to the focused handler).
    // Ctrl+; → open the ex-cmdline regardless of focus, input mode,
    // or any pending chord-chain state. Sits ABOVE dispatch_chord_chain
    // because a half-typed leader sequence in editor focus would
    // otherwise push this key onto pending_chord_seq and either fire
    // a multi-key chord or leave the cmdline open silently swallowed.
    // User-reported 2026-06-18 that Ctrl+; worked in tree focus but
    // failed in pane focus — symptom of a leader chord left dangling
    // in the pane's interaction.
    if key.code == KeyCode::Char(';') && key.modifiers.contains(KeyModifiers::CONTROL) {
        // Clear any in-flight chord chain — fresh chord, fresh state.
        app.pending_chord_seq.clear();
        app.pending_chord_deadline = None;
        app.pending_chord_fallback = None;
        if app.no_pane_cmdline.is_none() {
            app.open_ex_command_prompt();
        }
        return;
    }

    // 2026-06-19 — Ctrl+] / Ctrl+[ in a Request pane's Edit view
    // cycle the tab strip (Body/Headers/Params/Vars/Source). In
    // standard input mode, the global chord chain binds these to
    // editor.indent_line / outdent_line, which would otherwise
    // swallow them. Intercept first when we're on a Request pane
    // in Edit view so tab cycling works in both input modes.
    // api-workflow third hunt SEV-2.
    if matches!(key.code, KeyCode::Char(']') | KeyCode::Char('['))
        && key.modifiers.contains(KeyModifiers::CONTROL)
        && matches!(app.focus, Focus::Pane)
        && let Some(cur) = app.active
        && let Some(Pane::Request(rp)) = app.panes.get_mut(cur)
        && rp.view == crate::request_pane::ViewMode::Edit
    {
        rp.edit_tab = if key.code == KeyCode::Char(']') {
            rp.edit_tab.next()
        } else {
            rp.edit_tab.prev()
        };
        // When jumping to the Source tab, focus the Source field
        // so the user can immediately type. When leaving Source,
        // restore URL focus (the natural default for the other
        // tabs).
        if rp.edit_tab == crate::request_pane::EditTab::Source {
            rp.focus = crate::request_pane::EditField::Source;
        } else if rp.focus == crate::request_pane::EditField::Source {
            rp.focus = crate::request_pane::EditField::Url;
        }
        return;
    }
    // 2026-06-19 — keyboard hunt SEV-2: Ctrl+1..5 jumps directly
    // to the matching Edit-view tab. Same Request-pane-only gate as
    // Ctrl+]/Ctrl+[. Same standard-mode chord-chain bypass needed
    // for the same reason.
    if key.modifiers.contains(KeyModifiers::CONTROL)
        && matches!(
            key.code,
            KeyCode::Char('1')
                | KeyCode::Char('2')
                | KeyCode::Char('3')
                | KeyCode::Char('4')
                | KeyCode::Char('5')
                | KeyCode::Char('6')
        )
        && matches!(app.focus, Focus::Pane)
        && let Some(cur) = app.active
        && let Some(Pane::Request(rp)) = app.panes.get_mut(cur)
        && rp.view == crate::request_pane::ViewMode::Edit
    {
        use crate::request_pane::EditTab;
        rp.edit_tab = match key.code {
            KeyCode::Char('1') => EditTab::Body,
            KeyCode::Char('2') => EditTab::Headers,
            KeyCode::Char('3') => EditTab::Params,
            KeyCode::Char('4') => EditTab::Auth,
            KeyCode::Char('5') => EditTab::Vars,
            KeyCode::Char('6') => EditTab::Source,
            _ => rp.edit_tab,
        };
        if rp.edit_tab == EditTab::Source {
            rp.focus = crate::request_pane::EditField::Source;
        } else if rp.focus == crate::request_pane::EditField::Source {
            rp.focus = crate::request_pane::EditField::Url;
        }
        return;
    }

    // nvchad-round-15 SEV-2 F2 2026-07-15 — Ctrl+B in vim Normal /
    // Visual mode is canonical PageUp (since 1976 vi). The global
    // keymap binds it to `view.toggle_tree` — correct in standard
    // mode, but in vim Normal mode the vim.rs handler at :2839
    // owns Ctrl+B. Without this bypass, `dispatch_chord_chain`
    // below would fire the global toggle first and the vim.rs
    // branch is dead code. Skip chord_chain when the current key
    // is a vim-reserved Normal-mode chord so it falls through to
    // the focused input handler naturally. Matches the same
    // reasoning as the existing round-10 Ctrl+F fix (vim.rs side).
    let vim_reserves_key = {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        let vim_mode = app.editing_mode();
        let vim_normal_or_visual = matches!(
            vim_mode,
            crate::input::EditingMode::Normal
                | crate::input::EditingMode::Visual
                | crate::input::EditingMode::VisualLine
                | crate::input::EditingMode::VisualBlock
        );
        // R13 nvchad SEV-2 2026-08-23 — insert-mode Ctrl+O is vim's
        // canonical "one-shot normal command" chord (`Ctrl+O h`
        // moves left without leaving Insert). The global keymap
        // owns `Ctrl+O = picker.files`; without a per-key insert-
        // mode bypass here the chord chain fires the picker instead
        // of falling through to the vim handler.
        let vim_insert = matches!(vim_mode, crate::input::EditingMode::Insert);
        let normal_reserved = vim_normal_or_visual
            && ctrl
            && !key.modifiers.contains(KeyModifiers::ALT)
            // R7 nvchad SEV-2 2026-08-09 — extended from `b`/`B`
            // (page-back) to also include `o`/`O`/`i`. Vim owns:
            //   Ctrl+B / Ctrl+F — page back/forward
            //   Ctrl+O / Ctrl+I — jumplist back/forward
            && matches!(
                key.code,
                KeyCode::Char('b')
                    | KeyCode::Char('B')
                    | KeyCode::Char('o')
                    | KeyCode::Char('O')
                    | KeyCode::Char('i')
                    | KeyCode::Char('I')
                    // R10 nvchad SEV-3 — Ctrl+W window-prefix.
                    | KeyCode::Char('w')
                    | KeyCode::Char('W')
            );
        let insert_reserved = vim_insert
            && ctrl
            && !key.modifiers.contains(KeyModifiers::ALT)
            // #1229 (R17 nvchad) — `p` joins `o` here so vim's INSERT
            // keyword-completion pair works. `Ctrl+N` was already freed
            // (it is in keymap.rs's vim removal list) but `Ctrl+P` was
            // deliberately left bound globally to `picker.files`, so
            // `vim.rs`'s `editor.keyword_complete_back` arm had never
            // once run — completion cycled forward only. Reserving it
            // here rather than removing the global binding keeps
            // `Ctrl+P` = file picker in NORMAL, where the nvchad muscle
            // memory actually lives.
            //
            // LOWERCASE ONLY, unlike the `o`/`O` pair above:
            // `Ctrl+Shift+P` is the command palette, and vim users want
            // that from INSERT too. Reserving `P` would make the
            // palette dead in INSERT — do not "tidy" this into a pair.
            && (matches!(key.code, KeyCode::Char('o') | KeyCode::Char('O'))
                // `p` must additionally reject SHIFT. This guard matches on
                // the RAW `key.code`, not the SHIFT-normalised `Chord`, so
                // `Ctrl+Shift+P` arrives here as either `Char('P')` or
                // `Char('p')` + SHIFT depending on the terminal — and the
                // second shape would be reserved, killing the command
                // palette in INSERT. Caught by
                // `ctrl_shift_p_still_opens_the_palette_from_insert`, which
                // failed on the first cut of this fix.
                || (matches!(key.code, KeyCode::Char('p'))
                    && !key.modifiers.contains(KeyModifiers::SHIFT)));
        // #1229 (R17 nvchad SEV-2) — `nav.back` / `nav.forward` are
        // registered globally with no editing-mode gate, so `Ctrl+-` fired
        // from INSERT and VISUAL: one keystroke changed which file you were
        // editing AND dropped you to NORMAL, mid-sentence. Reserve the
        // chord in those two modes so it reaches the vim handler, which
        // ignores it — nav stays live in NORMAL, where it belongs.
        //
        // This allowlist is the wrong shape for the job and we know it;
        // every chord missing from it turns a `vim.rs` arm into dead code
        // you can only find by pressing the key. #1215 (invert dispatch —
        // let the focused handler decline first) is the real fix.
        // Listed positively rather than as "not Normal": the first cut of
        // this said `(insert || normal_or_visual) && !Normal`, which reads
        // as "every mode but Normal" but silently omitted Replace — a
        // typing mode with exactly the same problem as Insert.
        let nav_chord = matches!(key.code, KeyCode::Char('-') | KeyCode::Char('_'));
        let nav_reserved = matches!(
            vim_mode,
            crate::input::EditingMode::Insert
                | crate::input::EditingMode::Replace
                | crate::input::EditingMode::Visual
                | crate::input::EditingMode::VisualLine
                | crate::input::EditingMode::VisualBlock
        ) && ctrl
            && nav_chord;
        // R16 nvchad SEV-2 2026-08-24 — when the vim handler has a pending
        // prefix (`Ctrl+W`, `g`, `y`/`d`/`c`/`>`, `r`, `f`/`t`, `[`/`]`,
        // `m`/`'`/`` ` ``, macro register targets), the NEXT keystroke is
        // vim's — chord-chain must not eat it. Was: after `Ctrl+W`, the
        // follow-up `h`/`j`/`k`/`l` fell into `dispatch_chord_chain` and
        // never reached the vim handler's Window branch. Arrow keys
        // slipped past because the chain rejects them; the letter forms
        // did not.
        let pending_vim_chord = app
            .active_editor()
            .and_then(|b| b.input.pending_display())
            .is_some();
        normal_reserved || insert_reserved || nav_reserved || pending_vim_chord
    };

    // keyboard-round-14 SEV-2 2026-07-16 — when a Pty pane is
    // focused, forward the shell-critical ctrl chords straight to
    // the child instead of letting the global keymap eat them.
    // Was: Ctrl+D fired `editor.add_cursor_at_next_word` even from
    // a focused shell (breaking exit); Ctrl+K fired the whichkey
    // leader (breaking kill-line); Ctrl+R fired `find.find`
    // (breaking reverse-history-search); Ctrl+N/P fired autocomplete
    // move (breaking readline history); Ctrl+F fired
    // `find.find` (breaking readline forward-char). These are the
    // 6 chords a shell user hits within seconds of dropping into an
    // integration. Sits above dispatch_chord_chain so the key falls
    // through to the focused-Pty handler naturally.
    //
    // Exceptions:
    //  * Ctrl+F in a claude-code pane keeps its filename-inject
    //    (handled in pane.rs before the pty write path).
    //  * Ctrl+` still toggles the scratch terminal (kb-round-12).
    //  * Ctrl+C / Ctrl+U / Ctrl+A already fell through correctly.
    let pty_reserves_key = {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        let active_is_pty = app.focus == crate::focus::Focus::Pane
            && app
                .active
                .and_then(|i| app.panes.get(i))
                .is_some_and(|p| matches!(p, crate::pane::Pane::Pty(_)));
        active_is_pty
            && ctrl
            && !key.modifiers.contains(KeyModifiers::ALT)
            && !key.modifiers.contains(KeyModifiers::SHIFT)
            && matches!(
                key.code,
                KeyCode::Char('d')
                    | KeyCode::Char('D')
                    | KeyCode::Char('k')
                    | KeyCode::Char('K')
                    | KeyCode::Char('n')
                    | KeyCode::Char('N')
                    | KeyCode::Char('p')
                    | KeyCode::Char('P')
                    | KeyCode::Char('r')
                    | KeyCode::Char('R')
                    | KeyCode::Char('f')
                    | KeyCode::Char('F')
            )
    };

    // vscode-user-keyboard SEV-2: when the chord chain bottoms out
    // and fires its fallback (typically `whichkey.leader`), the
    // current key was being dropped instead of fed into the just-
    // opened whichkey overlay — making `<leader>tr` need three
    // keys (`Ctrl+K t t r`) instead of two. Now: if whichkey was
    // NOT open before chord-dispatch but IS open after, re-route
    // the current key to the overlay's char-feed.
    let whichkey_was_open = app.whichkey.is_some();
    // 2026-07-22 fix: bare `Delete` was bound globally to
    // `file.delete` (with no Focus::Tree gate), so pressing Delete
    // in the Request pane or the code editor teleported to the
    // tree's file-delete-confirm dialog instead of forward-
    // deleting a char at the caret. Skip the chord-chain machinery
    // for lone Delete when focus is NOT on the tree AND no chord
    // is pending — pane handlers own the key in that case.
    let delete_owns_focus = matches!(key.code, KeyCode::Delete)
        && key.modifiers.is_empty()
        && !matches!(app.focus, crate::focus::Focus::Tree)
        && app.pending_chord_seq.is_empty();
    // R10 nvchad SEV-2 2026-08-10 — when vim's `:` cmdline is open,
    // ALL keys belong to the cmdline. Was: space in `:set nowrap`
    // got eaten by dispatch_chord_chain as a leader chord, and the
    // cmdline saw `:setnowrap`. Every other char (`s`, `e`, `t`,
    // `n`, ...) was fine because the chord-chain fell through for
    // non-bound keys — but leader = space, so space specifically
    // got trapped.
    let vim_cmdline_open = app
        .active
        .and_then(|i| app.panes.get(i))
        .and_then(|p| p.as_editor())
        .map(|b| b.input.is_cmdline_open())
        .unwrap_or(false);
    // R11 claude-agents SEV-2 + 2026-08-10 e2e-fix — bare `space` is
    // the leader chord, but leader dispatch must NOT fire when the
    // focused surface is a text-input context: (1) an editor in
    // Insert / Replace mode or modeless (Standard) — typing " " in
    // a buffer used to get eaten and `HELLO fn main` became
    // `HELLOfn main`; (2) the Claude Agents dashboard, which uses
    // bare space as its multi-select toggle; (3) any non-editor
    // pane whose handler will treat bare space as text (DAP REPL,
    // HTTP request body, settings picker filter, …). The safe
    // gate is: bare space only reaches chord chain when vim is in
    // a modal state (Normal / Visual*) — that's the ONLY context
    // where `<space>ff` should route to the leader. Everywhere
    // else, bare space is text input.
    let vim_op_pending = app
        .active
        .and_then(|i| app.panes.get(i))
        .and_then(|p| p.as_editor())
        .map(|b| b.input.is_op_pending())
        .unwrap_or(false);
    let pane_wants_bare_space = matches!(key.code, KeyCode::Char(' '))
        && key.modifiers.is_empty()
        && (
            // 2026-08-18 (#968 reviewer follow-up) — Tree focus was
            // previously EXCLUDED from the bypass so `<space>ff`
            // leader chord could work from the tree, but that meant
            // pane.rs::handle_tree_key's Space arm (documented as
            // "activate row") was unreachable. Now Tree focus bypasses
            // the chord chain: Space activates the focused row, and
            // leader chords are reached via Ctrl+K (which also opens
            // whichkey) or by first focusing a pane.
            matches!(app.focus, crate::focus::Focus::Tree)
                || vim_op_pending
                || !matches!(
                    app.editing_mode(),
                    crate::input::EditingMode::Normal
                        | crate::input::EditingMode::Visual
                        | crate::input::EditingMode::VisualLine
                        | crate::input::EditingMode::VisualBlock
                )
        );
    if !vim_reserves_key
        && !pty_reserves_key
        && !delete_owns_focus
        && !vim_cmdline_open
        && !pane_wants_bare_space
        && dispatch_chord_chain(app, key)
    {
        return;
    }
    if !whichkey_was_open
        && app.whichkey.is_some()
        && let KeyCode::Char(c) = key.code
    {
        app.whichkey_feed(c);
        return;
    }

    // When the no-pane cmdline is open, it owns every keystroke
    // regardless of which side of the focus boundary the user
    // started typing from. Without this gate a pane-focused user
    // who hit Ctrl+; would land in the cmdline visually but their
    // typing would still go to the editor.
    if app.no_pane_cmdline.is_some() {
        let shift = key.modifiers.contains(KeyModifiers::SHIFT);
        match key.code {
            KeyCode::Esc => app.no_pane_cmdline_cancel(),
            // Enter runs whatever is currently in the cmdline.
            // 2026-06-19 — earlier impl auto-substituted the
            // popup match, but that breaks legitimate vim
            // abbreviations (`:reg`, `:wq`, …). Users wanting
            // the popup match use Tab/click first to put it
            // into the line.
            KeyCode::Enter => {
                // 2026-06-24 — if the user has navigated the popup
                // with ↑/↓/Tab (selected index != 0), accept the
                // highlighted match before committing. Index 0 is
                // the auto-selected first match — leaving it
                // unaccepted preserves the vim convention where
                // `:reg<Enter>` fires the literal `:reg` instead
                // of whatever `:registers`/etc. matched first.
                if app.cmdline_popup_is_showing() && app.cmdline_popup_selected > 0 {
                    app.cmdline_popup_accept_current();
                }
                app.no_pane_cmdline_commit();
            }
            // 2026-06-19 — popup nav. Tab / Down advance the
            // highlighted match; Shift+Tab / Up retreat. Rewrites
            // the cmdline to the new selection so Enter fires
            // whatever's highlighted. No-op when popup isn't
            // showing (compute returns <2 matches).
            KeyCode::Tab if shift => app.cmdline_popup_move(-1),
            KeyCode::Tab => app.cmdline_popup_move(1),
            KeyCode::Down => app.cmdline_popup_move(1),
            KeyCode::Up => app.cmdline_popup_move(-1),
            KeyCode::PageDown => app.cmdline_popup_move(8),
            KeyCode::PageUp => app.cmdline_popup_move(-8),
            KeyCode::Home => app.cmdline_popup_move_to(0),
            KeyCode::End => app.cmdline_popup_move_to(usize::MAX),
            _ => {
                // 2026-08-08 — common Ctrl+U / Ctrl+W / Ctrl+V /
                // Backspace shortcuts on the `:` cmdline. Uses the
                // shared filter helper so the routing matches
                // every other append-only surface.
                if let Some(buf) = app.no_pane_cmdline.as_mut() {
                    let r = crate::ui::text_input::handle_filter_shortcut(
                        key,
                        buf,
                        Some(&mut app.clipboard),
                    );
                    if r == crate::ui::text_input::TextKeyResult::Handled {
                        return;
                    }
                }
                if let KeyCode::Char(c) = key.code
                    && !key.modifiers.contains(KeyModifiers::CONTROL)
                {
                    app.no_pane_cmdline_push_char(c);
                }
            }
        }
        return;
    }

    // Snapshot cursor position BEFORE dispatch so we can record a
    // vim-jumplist entry after any key that produced a "big jump"
    // (>= JUMP_ROW_THRESHOLD rows away from the previous position,
    // OR a file switch). Fix 2026-07-07 — was: only `open_path`
    // pushed nav_back, so within-file jumps like `G`/`gg`/`{N}G`/
    // `/pattern` never made Ctrl+O go anywhere.
    let before = app.current_nav_point();
    // #1076 (2026-08-19) — global Ctrl+W (buffer.close) intercept for
    // Standard mode. Prior #1037 fix routed Ctrl+W through
    // `handle_pane_key`'s view-only branch, but many pane-openers
    // (`open_claude_usage_pane`, `open_codex_usage_pane`,
    // `open_spend_report_pane`, `open_integration_detail_pane`, …)
    // call `reveal_pane` without also shifting focus to
    // `Focus::Pane`. If the user opens Claude Usage from the palette
    // while focused on the tree, Ctrl+W goes to `handle_tree_key`
    // which has no close branch → key gets eaten silently.
    //
    // In standard/VS Code mode Ctrl+W is unambiguously "close the
    // active pane" no matter where focus is (the palette + menu-bar
    // both bind it to `buffer.close`). Route it directly here so it
    // stops depending on where the user happened to click last.
    //
    // Vim mode preserved: Ctrl+W in vim is the window-navigation
    // prefix, handled downstream — leave it to the pane router.
    if key.code == KeyCode::Char('w')
        && key.modifiers == KeyModifiers::CONTROL
        && !app.ctrl_w_is_window_nav()
        && app.active.is_some()
    {
        app.close_active_pane();
        return;
    }
    match app.focus {
        Focus::Tree => handle_tree_key(app, key),
        Focus::Pane => handle_pane_key(app, key),
        // Right panel behaves like a pane for key routing — the
        // pane handler already reads `app.right_panel_focus_active`
        // when dispatching outline/diag/grep keys.
        Focus::RightPanel => handle_pane_key(app, key),
        Focus::BottomPanel => handle_pane_key(app, key),
    }
    if let Some(before) = before
        && let Some(after) = app.current_nav_point()
    {
        const JUMP_ROW_THRESHOLD: usize = 3;
        let big_row_move =
            before.path == after.path && before.row.abs_diff(after.row) >= JUMP_ROW_THRESHOLD;
        let file_switched = before.path != after.path;
        if big_row_move || file_switched {
            app.record_within_file_jump(before);
        }
    }
    // Reset AFTER the recorder runs. `record_within_file_jump`
    // consults this flag to decide whether to clear nav_forward;
    // leaving it stale would suppress the clear on the NEXT key's
    // fresh jump. nvchad SEV-2 2026-07-10.
    app.nav_jump_in_progress = false;
}

// T-1: chord-chain dispatch + tick + timeout const moved to src/tui/chord.rs.
// Re-exported above (`pub use chord::*`) so existing call sites work.

// T-3: overlay key handlers moved to src/tui/handlers/overlay.rs.
// Imported above so existing dispatch_key call sites work.

// T-4: handle_tree_key, handle_pane_key, handle_md_preview_key,
// handle_diff_key, handle_request_key, is_view_only_pane moved to
// src/tui/handlers/pane.rs (imported above).

/// Shell out `mixr --command <verb>` for the statusline transport
/// chip. Detached + non-blocking so a slow mixr-side handler can't
/// stutter the render loop; failures are logged and otherwise
/// swallowed so an absent / not-on-PATH mixr doesn't surface as a
/// scary toast for users who don't have mixr installed at all.
/// The `mixr --command` path writes to `~/.mixr/command` (an atomic
/// file write) which a running mixr polls — nothing else is needed.
pub(crate) fn send_mixr_command(verb: &str) {
    let result = std::process::Command::new("mixr")
        .args(["--command", verb])
        .spawn();
    if let Err(e) = result {
        eprintln!("mnml: send_mixr_command({verb:?}) failed: {e}");
    }
}

/// Drive Apple Music / Spotify via AppleScript for the statusline
/// transport chips. `app_name` is the source string mnml reads from
/// `now_playing` (`"Music"` / `"Spotify"`), `verb` is an AppleScript
/// transport command — `"playpause"`, `"next track"`, etc.
///
/// Detached + non-blocking; failures log and are swallowed so a user
/// without the named app installed doesn't get a scary toast.
pub(crate) fn send_macos_player(app_name: &str, verb: &str) {
    // Whitelist the source names we recognize so a malformed
    // `np.source` can't be coerced into arbitrary AppleScript.
    let app = match app_name {
        s if s.eq_ignore_ascii_case("Music") => "Music",
        s if s.eq_ignore_ascii_case("Spotify") => "Spotify",
        _ => return,
    };
    let script = format!("tell application \"{app}\" to {verb}");
    let result = std::process::Command::new("osascript")
        .args(["-e", &script])
        .spawn();
    if let Err(e) = result {
        eprintln!("mnml: send_macos_player({app_name:?}, {verb:?}) failed: {e}");
    }
}

#[cfg(test)]
mod welcome_esc_tests {
    use super::dispatch_key;
    use crate::app::App;
    use crate::config::Config;
    use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

    fn esc() -> KeyEvent {
        KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)
    }

    /// #1216, keyboard half — Esc on the wizard means "ask me later".
    /// The welcome-dismiss block runs earlier in `dispatch_key` than
    /// the wizard handler, so it used to consume the same Esc and
    /// write `.mnml/.welcomed` for a card that was never on screen.
    #[test]
    fn esc_deferring_the_wizard_leaves_the_welcome_for_afterwards() {
        let d = tempfile::tempdir().unwrap();
        let mut app = App::new(d.path().to_path_buf(), Config::default()).unwrap();
        app.maybe_show_welcome_on_launch();
        app.open_first_launch();

        dispatch_key(&mut app, esc());

        assert!(app.first_launch.is_none(), "Esc should close the wizard");
        assert!(
            app.show_welcome,
            "the welcome card should now be the thing on screen"
        );
        assert!(!d.path().join(".mnml/.welcomed").exists());
    }

    #[test]
    fn esc_on_the_bare_welcome_still_dismisses_it() {
        let d = tempfile::tempdir().unwrap();
        let mut app = App::new(d.path().to_path_buf(), Config::default()).unwrap();
        app.maybe_show_welcome_on_launch();

        dispatch_key(&mut app, esc());

        assert!(!app.show_welcome);
        assert!(d.path().join(".mnml/.welcomed").exists());
    }
}

#[cfg(test)]
mod files_pane_modifier_tests {
    use crate::app::App;
    use crate::config::Config;
    use crate::file_browser::Sort;
    use crate::tui::handlers::pane::handle_pane_key;
    use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

    fn pane(dir: &std::path::Path) -> (tempfile::TempDir, App, usize) {
        let d = tempfile::tempdir().unwrap();
        std::fs::create_dir(d.path().join("sub")).unwrap();
        std::fs::write(d.path().join("a.txt"), "a").unwrap();
        let mut cfg = Config::default();
        cfg.editor.input_style = "standard".to_string();
        let mut app = App::new(d.path().to_path_buf(), cfg).unwrap();
        let target = if dir.as_os_str().is_empty() {
            d.path().to_path_buf()
        } else {
            dir.to_path_buf()
        };
        app.open_files_pane(Some(target));
        let pid = app.active.unwrap();
        (d, app, pid)
    }

    /// Drives `handle_pane_key` DIRECTLY rather than `dispatch_key`.
    ///
    /// Going through `dispatch_key` made these tests vacuous: `Ctrl+S` is
    /// bound globally to `file.save`, so the chord layer consumed it and
    /// it never reached the Files branch — the tests passed with the guard
    /// deliberately disabled. Testing the handler directly exercises the
    /// guard itself, which is the thing being asserted.
    ///
    /// #files — the bare-char arms were modifier-BLIND, so `Ctrl+S` (save)
    /// cycled the sort order and `Ctrl+H` walked to the parent directory.
    /// Same class as #1213, where vim mode read arrow modifiers instead of
    /// discarding them.
    #[test]
    fn ctrl_s_does_not_cycle_the_sort_order() {
        let _lk = crate::test_env_lock()
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let (_d, mut app, pid) = pane(std::path::Path::new(""));
        let before = match app.panes.get(pid) {
            Some(crate::pane::Pane::Files(f)) => f.sort,
            _ => panic!(),
        };
        assert_eq!(before, Sort::DirsFirstName, "setup");

        handle_pane_key(
            &mut app,
            KeyEvent::new(KeyCode::Char('s'), KeyModifiers::CONTROL),
        );

        let after = match app.panes.get(pid) {
            Some(crate::pane::Pane::Files(f)) => f.sort,
            _ => panic!(),
        };
        assert_eq!(
            after, before,
            "Ctrl+S cycled the sort — the bare-char arm is modifier-blind"
        );
    }

    /// And bare `s` must still cycle it, or the guard went too far.
    #[test]
    fn bare_s_still_cycles_the_sort_order() {
        let _lk = crate::test_env_lock()
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let (_d, mut app, pid) = pane(std::path::Path::new(""));
        handle_pane_key(
            &mut app,
            KeyEvent::new(KeyCode::Char('s'), KeyModifiers::NONE),
        );
        let after = match app.panes.get(pid) {
            Some(crate::pane::Pane::Files(f)) => f.sort,
            _ => panic!(),
        };
        assert_ne!(after, Sort::DirsFirstName, "bare `s` stopped working");
    }

    /// `Ctrl+H` must not be read as the vim-style "go up".
    #[test]
    fn ctrl_h_does_not_navigate_to_the_parent() {
        let _lk = crate::test_env_lock()
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let (d, mut app, pid) = pane(std::path::Path::new(""));
        let sub = d.path().join("sub");
        if let Some(crate::pane::Pane::Files(f)) = app.panes.get_mut(pid) {
            f.navigate_to(&sub);
        }
        let before = match app.panes.get(pid) {
            Some(crate::pane::Pane::Files(f)) => f.cwd.clone(),
            _ => panic!(),
        };
        handle_pane_key(
            &mut app,
            KeyEvent::new(KeyCode::Char('h'), KeyModifiers::CONTROL),
        );
        let after = match app.panes.get(pid) {
            Some(crate::pane::Pane::Files(f)) => f.cwd.clone(),
            _ => panic!(),
        };
        assert_eq!(before, after, "Ctrl+H navigated up");
    }
}

#[cfg(test)]
mod files_pane_vim_safety {
    use crate::app::App;
    use crate::config::Config;
    use crate::tui::handlers::pane::handle_pane_key;
    use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

    fn pane(style: &str) -> (tempfile::TempDir, App, usize) {
        let d = tempfile::tempdir().unwrap();
        for n in ["one.txt", "two.txt"] {
            std::fs::write(d.path().join(n), n).unwrap();
        }
        let mut cfg = Config::default();
        cfg.editor.input_style = style.to_string();
        let mut app = App::new(d.path().to_path_buf(), cfg).unwrap();
        app.open_files_pane(None);
        let pid = app.active.unwrap();
        (d, app, pid)
    }

    fn entries(d: &std::path::Path) -> usize {
        std::fs::read_dir(d).map(|r| r.count()).unwrap_or(0)
    }

    /// SEV-1 from the vim tester: `Ctrl+D` is vim's half-page-down, and it
    /// was bound to `file.duplicate` — an immediate, unconfirmed,
    /// un-undoable write. They pressed it and duplicated a file the screen
    /// gave no indication was selected.
    #[test]
    fn ctrl_d_does_not_write_to_disk_in_vim_style() {
        let _lk = crate::test_env_lock()
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let (d, mut app, _pid) = pane("vim");
        let before = entries(d.path());
        handle_pane_key(
            &mut app,
            KeyEvent::new(KeyCode::Char('d'), KeyModifiers::CONTROL),
        );
        assert_eq!(
            entries(d.path()),
            before,
            "Ctrl+D duplicated a file in vim style — that is half-page-down"
        );
    }

    /// `Ctrl+V` is visual-block. It was bound to paste, and the tester
    /// moved three off-screen files with it.
    #[test]
    fn ctrl_v_does_not_move_files_in_vim_style() {
        let _lk = crate::test_env_lock()
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let (d, mut app, pid) = pane("vim");
        // Arm the clipboard the way the tester did, then fire Ctrl+V.
        let paths: Vec<std::path::PathBuf> = match app.panes.get(pid) {
            Some(crate::pane::Pane::Files(f)) => f.entries.iter().map(|e| e.path.clone()).collect(),
            _ => panic!(),
        };
        app.file_stage_clipboard_many(paths, true);
        let before = entries(d.path());
        handle_pane_key(
            &mut app,
            KeyEvent::new(KeyCode::Char('v'), KeyModifiers::CONTROL),
        );
        assert_eq!(
            entries(d.path()),
            before,
            "Ctrl+V moved files in vim style — that is visual-block"
        );
    }

    /// Standard style KEEPS the VS Code chords — the fix must not remove
    /// the feature for the users it was built for.
    #[test]
    fn standard_style_still_has_the_ctrl_clipboard() {
        let _lk = crate::test_env_lock()
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let (_d, mut app, _pid) = pane("standard");
        handle_pane_key(
            &mut app,
            KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL),
        );
        assert!(
            !app.file_clipboard.is_empty(),
            "Ctrl+C stopped staging the clipboard in standard style"
        );
    }

    /// Vim users get the ranger vocabulary instead, and it is TWO-KEY so a
    /// single stray press cannot move anything.
    #[test]
    fn vim_style_yy_copies_but_a_single_y_does_not() {
        let _lk = crate::test_env_lock()
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let (_d, mut app, _pid) = pane("vim");
        handle_pane_key(
            &mut app,
            KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE),
        );
        assert!(
            app.file_clipboard.is_empty(),
            "one `y` staged the clipboard — a stray press must do nothing"
        );
        handle_pane_key(
            &mut app,
            KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE),
        );
        assert!(!app.file_clipboard.is_empty(), "`yy` did not copy");
    }

    /// A pending `y` must not survive an unrelated key, or a stray press
    /// later completes an operation the user forgot starting.
    #[test]
    fn a_pending_operation_is_cancelled_by_any_other_key() {
        let _lk = crate::test_env_lock()
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let (_d, mut app, _pid) = pane("vim");
        handle_pane_key(
            &mut app,
            KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE),
        );
        handle_pane_key(
            &mut app,
            KeyEvent::new(KeyCode::Char('j'), KeyModifiers::NONE),
        );
        assert!(app.files_pending_op.is_none(), "pending op survived `j`");
        handle_pane_key(
            &mut app,
            KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE),
        );
        assert!(
            app.file_clipboard.is_empty(),
            "a `y` after an unrelated key completed the earlier `y`"
        );
    }
}

#[cfg(test)]
mod files_pane_review_fixes {
    use super::dispatch_key;
    use crate::app::App;
    use crate::config::Config;
    use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

    fn files_pane(style: &str) -> (tempfile::TempDir, App, usize) {
        let d = tempfile::tempdir().unwrap();
        for n in ["a.txt", "b.txt"] {
            std::fs::write(d.path().join(n), n).unwrap();
        }
        let mut cfg = Config::default();
        cfg.editor.input_style = style.to_string();
        let mut app = App::new(d.path().to_path_buf(), cfg).unwrap();
        app.open_files_pane(None);
        let pid = app.active.unwrap();
        (d, app, pid)
    }

    /// Review finding (critical) — `Pane::Files` was missing from
    /// `is_view_only_pane`, so `:` never reached the ex-cmdline. Chord
    /// dispatch runs BEFORE `handle_pane_key`, so a key the Files branch
    /// does not name is dropped, not passed on: a vim user was trapped.
    #[test]
    fn colon_opens_the_cmdline_from_a_files_pane() {
        let _lk = crate::test_env_lock()
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let (_d, mut app, _pid) = files_pane("vim");
        dispatch_key(
            &mut app,
            KeyEvent::new(KeyCode::Char(':'), KeyModifiers::NONE),
        );
        assert!(
            app.no_pane_cmdline.is_some(),
            "`:` was swallowed by the Files pane — a vim user cannot reach \
             the ex-cmdline from it"
        );
    }

    /// Review finding — `g` meant "destinations picker" here while EVERY
    /// other listing pane in mnml binds it to "go to top". Now `g`/`G`
    /// are top/bottom and `b` browses.
    #[test]
    fn g_goes_to_the_top_like_every_other_listing_pane() {
        let _lk = crate::test_env_lock()
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let (_d, mut app, pid) = files_pane("standard");
        if let Some(crate::pane::Pane::Files(f)) = app.panes.get_mut(pid) {
            f.selected = f.entries.len() - 1;
        }
        crate::tui::handlers::pane::handle_pane_key(
            &mut app,
            KeyEvent::new(KeyCode::Char('g'), KeyModifiers::NONE),
        );
        let sel = match app.panes.get(pid) {
            Some(crate::pane::Pane::Files(f)) => f.selected,
            _ => panic!(),
        };
        assert_eq!(sel, 0, "`g` did not go to the top");
        assert!(
            app.picker.is_none(),
            "`g` opened a picker — the destinations binding is still on it"
        );
    }

    /// The modifier guard is now a blocklist, so a NEW bare-char binding
    /// is covered without anyone remembering to update a second list.
    /// `Ctrl+<any letter>` must be inert in the pane.
    #[test]
    fn every_modified_char_is_inert_in_the_files_pane() {
        let _lk = crate::test_env_lock()
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        for ch in ['s', 'h', 'g', 'b', 'a', 'p', 'r', '.'] {
            let (_d, mut app, pid) = files_pane("standard");
            let before = match app.panes.get(pid) {
                Some(crate::pane::Pane::Files(f)) => (f.cwd.clone(), f.sort, f.selected),
                _ => panic!(),
            };
            crate::tui::handlers::pane::handle_pane_key(
                &mut app,
                KeyEvent::new(KeyCode::Char(ch), KeyModifiers::CONTROL),
            );
            let after = match app.panes.get(pid) {
                Some(crate::pane::Pane::Files(f)) => (f.cwd.clone(), f.sort, f.selected),
                _ => panic!(),
            };
            assert_eq!(
                before, after,
                "Ctrl+{ch} changed the pane — a modified key reached a \
                 bare-char arm"
            );
        }
    }
}

#[cfg(test)]
mod menu_dismiss_tests {
    use super::dispatch_key;
    use crate::app::App;
    use crate::config::Config;
    use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

    fn app_in_tmp() -> (tempfile::TempDir, App) {
        let d = tempfile::tempdir().unwrap();
        let _ = std::fs::write(d.path().join("a.txt"), "a");
        let mut cfg = Config::default();
        cfg.editor.input_style = "standard".to_string();
        let app = App::new(d.path().to_path_buf(), cfg).unwrap();
        (d, app)
    }

    /// #1229 (user report) — "if i have file menu open and then ctrl ; to
    /// type a command i see the command panel but cant type as focus still
    /// on the file menu i had open."
    ///
    /// The palette opened, but the menu stayed up and kept consuming keys,
    /// because the close-the-menu guard only covered Ctrl+LETTER and
    /// `ctrl+;` is Ctrl+punctuation.
    #[test]
    fn a_ctrl_punctuation_chord_releases_the_menu() {
        let _lk = crate::test_env_lock()
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        // Asserts the RELEASE, not what the chord goes on to do. `ctrl+;`
        // is not bound by default — the user has some route to a command
        // input on it — and the bug was never about which command ran: the
        // menu kept ownership of the keyboard afterwards either way. So
        // this pins the invariant that actually broke, for every
        // Ctrl+punctuation chord rather than one binding.
        for ch in [';', ',', '.', '-', '/', '\''] {
            let (_d, mut app) = app_in_tmp();
            app.menu_open = Some(crate::menu_bar::MenuOpenState::new_keyboard(0));
            dispatch_key(
                &mut app,
                KeyEvent::new(KeyCode::Char(ch), KeyModifiers::CONTROL),
            );
            assert!(
                app.menu_open.is_none(),
                "Ctrl+{ch} left the menu open — it keeps ownership of the \
                 keyboard, so whatever the chord opened cannot be typed into"
            );
        }
    }

    /// The alphabetic case already worked (R6 vscode-keyboard F8); the fix
    /// widened that guard, so keep it covered.
    #[test]
    fn ctrl_shift_p_still_closes_the_menu() {
        let _lk = crate::test_env_lock()
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let (_d, mut app) = app_in_tmp();
        app.menu_open = Some(crate::menu_bar::MenuOpenState::new_keyboard(0));
        dispatch_key(
            &mut app,
            KeyEvent::new(
                KeyCode::Char('p'),
                KeyModifiers::CONTROL | KeyModifiers::SHIFT,
            ),
        );
        assert!(app.picker.is_some(), "palette did not open");
        assert!(app.menu_open.is_none(), "menu stayed open");
    }

    /// A bare letter must still belong to the MENU as a mnemonic —
    /// widening the guard must not steal ordinary menu navigation.
    #[test]
    fn a_plain_letter_does_not_trip_the_global_chord_escape() {
        let _lk = crate::test_env_lock()
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let (_d, mut app) = app_in_tmp();
        app.menu_open = Some(crate::menu_bar::MenuOpenState::new_keyboard(0));
        dispatch_key(
            &mut app,
            KeyEvent::new(KeyCode::Char('x'), KeyModifiers::NONE),
        );
        assert!(
            app.picker.is_none(),
            "a bare letter opened a picker — the guard is now too wide"
        );
    }

    /// Belt-and-braces: `open_picker` is the chokepoint all 72 picker
    /// callers go through, so any other route to a picker inherits this.
    #[test]
    fn opening_any_picker_dismisses_the_menu() {
        let _lk = crate::test_env_lock()
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let (_d, mut app) = app_in_tmp();
        app.menu_open = Some(crate::menu_bar::MenuOpenState::new_keyboard(0));
        app.open_file_picker();
        assert!(
            app.menu_open.is_none(),
            "open_picker did not dismiss the menu"
        );
    }
}

#[cfg(test)]
mod nav_mode_gate_tests {
    use super::dispatch_key;
    use crate::app::App;
    use crate::config::Config;
    use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

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

    /// Two files open in vim mode, cursor on the second.
    fn two_file_vim_app() -> (tempfile::TempDir, App) {
        let d = tempfile::tempdir().unwrap();
        std::fs::write(d.path().join("a.txt"), "alpha\n").unwrap();
        std::fs::write(d.path().join("b.txt"), "beta\n").unwrap();
        let mut cfg = Config::default();
        cfg.editor.input_style = "vim".to_string();
        let mut app = App::new(d.path().to_path_buf(), cfg).unwrap();
        app.open_path(&d.path().join("a.txt"));
        app.open_path(&d.path().join("b.txt"));
        (d, app)
    }

    fn active_title(app: &App) -> String {
        app.active
            .and_then(|i| app.panes.get(i))
            .map(|p| p.title())
            .unwrap_or_default()
    }

    /// #1229 (R17 nvchad) — vim's INSERT keyword-completion pair was
    /// half-broken: `Ctrl+N` (forward) worked, `Ctrl+P` (back) opened
    /// the file picker instead, because `ctrl+p` stayed bound globally
    /// and the chord layer runs before the focused handler. `vim.rs`'s
    /// `editor.keyword_complete_back` arm had never once run.
    #[test]
    fn ctrl_p_in_insert_reaches_the_editor_not_the_file_picker() {
        let (_d, mut app) = two_file_vim_app();
        dispatch_key(&mut app, plain('i')); // NORMAL -> INSERT
        assert!(app.picker.is_none(), "picker open before the test acts");

        dispatch_key(&mut app, ctrl('p'));

        assert!(
            app.picker.is_none(),
            "Ctrl+P opened the file picker from INSERT — the global binding \
             is still shadowing vim's keyword-completion-back"
        );
        assert_eq!(
            app.editing_mode(),
            crate::input::EditingMode::Insert,
            "Ctrl+P knocked the user out of INSERT"
        );
    }

    /// The counterpart that must keep working — this is the whole reason
    /// the fix reserves the chord in INSERT instead of unbinding
    /// `ctrl+p` globally.
    #[test]
    fn ctrl_p_in_normal_still_opens_the_file_picker() {
        let (_d, mut app) = two_file_vim_app();
        assert_eq!(app.editing_mode(), crate::input::EditingMode::Normal);

        dispatch_key(&mut app, ctrl('p'));

        assert!(
            app.picker.is_some(),
            "Ctrl+P stopped opening the picker in NORMAL — nvchad muscle \
             memory regressed"
        );
    }

    /// THE TRAP. `insert_reserved` lists `'o' | 'O'` for Ctrl+O, and
    /// copying that shape for `p` would reserve `Ctrl+Shift+P` — the
    /// command palette — leaving it dead in INSERT. The fix is
    /// deliberately lowercase-only; this test is what stops someone
    /// "tidying" it into a pair.
    #[test]
    fn ctrl_shift_p_still_opens_the_palette_from_insert() {
        let (_d, mut app) = two_file_vim_app();
        dispatch_key(&mut app, plain('i')); // NORMAL -> INSERT

        dispatch_key(
            &mut app,
            KeyEvent::new(
                KeyCode::Char('p'),
                KeyModifiers::CONTROL | KeyModifiers::SHIFT,
            ),
        );

        assert!(
            app.picker.is_some(),
            "Ctrl+Shift+P no longer opens the command palette from INSERT — \
             the insert_reserved allowlist has been widened to include 'P'"
        );
    }

    /// The other wire shape for the same chord. Terminals disagree about
    /// whether `Ctrl+Shift+P` arrives as `Char('p')` + SHIFT or as
    /// `Char('P')`; `Chord::of` normalises them, but `insert_reserved`
    /// matches the RAW code, so both need covering.
    #[test]
    fn ctrl_shift_p_as_uppercase_char_also_reaches_the_palette() {
        let (_d, mut app) = two_file_vim_app();
        dispatch_key(&mut app, plain('i'));

        dispatch_key(
            &mut app,
            KeyEvent::new(
                KeyCode::Char('P'),
                KeyModifiers::CONTROL | KeyModifiers::SHIFT,
            ),
        );

        assert!(
            app.picker.is_some(),
            "Ctrl+Shift+P (uppercase wire form) was swallowed in INSERT"
        );
    }

    /// #1229 — `nav.back` is registered globally with no editing-mode
    /// gate, so `Ctrl+-` fired from INSERT: one keystroke changed which
    /// file you were editing AND dropped you to NORMAL, mid-sentence.
    #[test]
    fn nav_back_is_inert_while_typing_in_insert_mode() {
        let (_d, mut app) = two_file_vim_app();
        dispatch_key(&mut app, plain('i')); // NORMAL -> INSERT
        let before = active_title(&app);
        let mode_before = app.editing_mode();

        dispatch_key(&mut app, ctrl('-'));

        assert_eq!(
            active_title(&app),
            before,
            "Ctrl+- changed the file out from under an insert"
        );
        assert_eq!(
            app.editing_mode(),
            mode_before,
            "Ctrl+- dropped the user out of INSERT"
        );
    }

    /// Same for VISUAL — it discarded the selection along with the file.
    #[test]
    fn nav_back_is_inert_in_visual_mode() {
        let (_d, mut app) = two_file_vim_app();
        dispatch_key(&mut app, plain('v')); // NORMAL -> VISUAL
        let before = active_title(&app);
        let mode_before = app.editing_mode();

        dispatch_key(&mut app, ctrl('-'));

        assert_eq!(active_title(&app), before);
        assert_eq!(app.editing_mode(), mode_before);
    }

    /// Reviewer catch — REPLACE (`R`) is a typing mode exactly like
    /// INSERT, and the first cut of the gate said "not Normal" in a way
    /// that read as "every other mode" but actually omitted it. So
    /// `Ctrl+-` still yanked the file out from under an overwrite.
    #[test]
    fn nav_back_is_inert_in_replace_mode() {
        let (_d, mut app) = two_file_vim_app();
        dispatch_key(&mut app, plain('R')); // NORMAL -> REPLACE
        assert_eq!(
            app.editing_mode(),
            crate::input::EditingMode::Replace,
            "precondition: R enters REPLACE"
        );
        let before = active_title(&app);

        dispatch_key(&mut app, ctrl('-'));

        assert_eq!(
            active_title(&app),
            before,
            "Ctrl+- changed the file out from under an overwrite"
        );
        assert_eq!(
            app.editing_mode(),
            crate::input::EditingMode::Replace,
            "Ctrl+- dropped the user out of REPLACE"
        );
    }

    /// The complement — nav must still WORK in NORMAL, which is where an
    /// mnml user actually reaches for it. Without this the fix could be
    /// "reserve the chord everywhere" and both tests above would pass
    /// while the feature was dead.
    #[test]
    fn nav_back_still_navigates_from_normal_mode() {
        let (_d, mut app) = two_file_vim_app();
        let before = active_title(&app);
        assert_eq!(before, "b.txt", "precondition: cursor is on the 2nd file");

        dispatch_key(&mut app, ctrl('-'));

        assert_ne!(
            active_title(&app),
            before,
            "Ctrl+- should navigate back in NORMAL"
        );
    }
}

#[cfg(test)]
mod panic_hook_tests {
    use super::*;
    use std::sync::atomic::{AtomicBool, Ordering};

    static RESTORED: AtomicBool = AtomicBool::new(false);
    static PREV_RAN: AtomicBool = AtomicBool::new(false);

    fn fake_restore() {
        RESTORED.store(true, Ordering::SeqCst);
    }

    /// A panic must restore the terminal *and* still reach the previous
    /// hook, so the panic message and backtrace survive. Without the
    /// first half the user's shell is left in raw mode on the alternate
    /// screen; without the second half we would swallow the crash report.
    #[test]
    fn panic_hook_restores_terminal_then_chains() {
        // `set_hook` is process-global. Put the harness's own hook back
        // before asserting, so a failed assertion here can't leak ours
        // into the rest of the suite.
        let original = std::panic::take_hook();
        std::panic::set_hook(Box::new(|_| {
            PREV_RAN.store(true, Ordering::SeqCst);
        }));
        install_panic_hook_with(fake_restore);

        let panicked = std::panic::catch_unwind(|| panic!("boom")).is_err();
        let restored = RESTORED.load(Ordering::SeqCst);
        let chained = PREV_RAN.load(Ordering::SeqCst);

        let _ = std::panic::take_hook();
        std::panic::set_hook(original);

        assert!(panicked, "the panic must still propagate");
        assert!(restored, "terminal teardown must run on panic");
        assert!(
            chained,
            "previous hook must still run, or we lose the backtrace"
        );
    }

    /// The hook runs while the process is already unwinding, and may run
    /// when setup never completed. It must not panic a second time.
    #[test]
    fn emergency_restore_is_safe_without_a_terminal() {
        emergency_restore_terminal();
        emergency_restore_terminal();
    }
}