mnml-rs 0.2.21

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
//! Local filesystem actions on `App` — the New / Rename / Delete /
//! Cut / Copy / Paste / Duplicate / Move-to file operations, the
//! confirm/discard prompt handlers that gate destructive ops, and the
//! at-revision open (git blame → open the historical file). Matches
//! the Finder / VS Code file-clipboard convention (see local file
//! actions pack, 2026-07-07).
//!
//! Extracted from `app/mod.rs` (file-split refactor — Task #963).
//! Pure non-destructive move; no API change.

use super::*;

/// One `"key":"value"` field out of a flat JSON line, unescaped.
///
/// The trash index is written right here and its shape is fixed, so a
/// full parser would be out of proportion — the same reasoning as
/// `message_persist`'s reader. `origin` is last on the line, so a path
/// containing `"entry":"` cannot be found ahead of the real field.
fn json_str_field(line: &str, key: &str) -> Option<String> {
    let pat = format!("\"{key}\":\"");
    let start = line.find(&pat)? + pat.len();
    let rest = &line[start..];
    let mut out = String::new();
    let mut esc = false;
    for c in rest.chars() {
        if esc {
            out.push(c);
            esc = false;
        } else if c == '\\' {
            esc = true;
        } else if c == '"' {
            return Some(out);
        } else {
            out.push(c);
        }
    }
    None
}

impl App {
    /// Open the "type the filename to confirm" prompt for the
    /// "Discard changes" menu entry. Stashes `rel` in
    /// `pending_discard_file`; the prompt accept calls
    /// `accept_discard_file`.
    pub fn open_discard_file_prompt(&mut self, rel: std::path::PathBuf) {
        let basename = rel
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_else(|| rel.to_string_lossy().into_owned());
        self.pending_discard_file = Some(rel);
        let title = format!("Discard uncommitted changes to `{basename}`?");
        let mut p = crate::prompt::Prompt::new(crate::prompt::PromptKind::GitDiscardFile, title);
        p.cursor = 1;
        self.prompt = Some(p);
    }

    /// Accept handler for [`PromptKind::GitDiscardFile`]. Requires the
    /// typed text to equal the file's basename; on match, runs
    /// `git restore -- <rel>`.
    pub fn accept_discard_file(&mut self, typed: &str) {
        let Some(rel) = self.pending_discard_file.take() else {
            return;
        };
        let basename = rel
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_default();
        if typed.trim() != basename {
            self.toast("discard cancelled");
            return;
        }
        let rel_str = rel.to_string_lossy().into_owned();
        match crate::git::stage::discard_file(self.active_repo_path(), &rel_str) {
            Ok(()) => {
                self.toast(format!("discarded {basename}"));
                self.after_git_change();
            }
            Err(e) => self.toast(format!("git restore: {e}")),
        }
    }

    /// `git show <hash>:<rel>` into a scratch buffer titled
    /// `<rel> @ <short>`. Useful from the diff context menu when
    /// the user wants to read the file's full contents at the
    /// chosen revision (rather than just the changed lines).
    pub fn open_file_at_revision(&mut self, hash: &str, rel: &std::path::Path) {
        use std::process::Command;
        let spec = format!("{}:{}", hash, rel.to_string_lossy());
        let out = Command::new("git")
            .args(["show", &spec])
            .current_dir(self.active_repo_path())
            .output();
        let text = match out {
            Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).into_owned(),
            Ok(o) => {
                self.toast(format!(
                    "git show: {}",
                    String::from_utf8_lossy(&o.stderr).trim()
                ));
                return;
            }
            Err(e) => {
                self.toast(format!("git show: {e}"));
                return;
            }
        };
        let short = hash.chars().take(7).collect::<String>();
        let title = format!("{} @ {}", rel.to_string_lossy(), short);
        self.open_scratch_with_text(title, text);
    }

    // A-3: open_ex_command_prompt + no_pane_cmdline_* methods moved
    // to src/app/cmdline_methods.rs.

    pub fn open_new_file_prompt(&mut self, parent: PathBuf) {
        self.pending_fs_action = Some(FsAction::NewFile {
            parent: parent.clone(),
        });
        let title = format!("New file in {}/", rel_path(&self.workspace, &parent));
        self.prompt = Some(crate::prompt::Prompt::new(
            crate::prompt::PromptKind::NewFile,
            title,
        ));
    }

    /// Open the "New folder…" prompt — captures `parent`.
    pub fn open_new_folder_prompt(&mut self, parent: PathBuf) {
        self.pending_fs_action = Some(FsAction::NewFolder {
            parent: parent.clone(),
        });
        let title = format!("New folder in {}/", rel_path(&self.workspace, &parent));
        self.prompt = Some(crate::prompt::Prompt::new(
            crate::prompt::PromptKind::NewFolder,
            title,
        ));
    }

    /// Open the FS rename prompt — captures `path`, seeds with its filename.
    pub fn open_fs_rename_prompt(&mut self, path: PathBuf) {
        let seed = path
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_default();
        self.pending_fs_action = Some(FsAction::Rename { path: path.clone() });
        let title = format!("Rename {}", rel_path(&self.workspace, &path));
        self.prompt = Some(crate::prompt::Prompt::seeded(
            crate::prompt::PromptKind::Rename,
            title,
            seed,
        ));
    }

    /// Create an empty file at `parent / name` and open it. `name` may include
    /// `/` separators — any missing intermediate dirs are created. Empty name
    /// is a no-op; an existing target toasts and bails.
    pub fn create_new_file(&mut self, parent: &Path, name: &str) {
        let name = name.trim();
        if name.is_empty() {
            return;
        }
        let target = parent.join(name);
        if target.exists() {
            self.toast(format!(
                "already exists: {}",
                rel_path(&self.workspace, &target)
            ));
            return;
        }
        if let Some(p) = target.parent()
            && let Err(e) = std::fs::create_dir_all(p)
        {
            self.toast(format!("cannot create dirs for {}: {e}", p.display()));
            return;
        }
        if let Err(e) = std::fs::write(&target, "") {
            self.toast(format!("create failed: {e}"));
            return;
        }
        self.refresh_after_fs_change();
        self.toast(format!("created {}", rel_path(&self.workspace, &target)));
        self.open_path(&target);
    }

    /// `mkdir -p parent/name` (then refresh the tree).
    pub fn create_new_folder(&mut self, parent: &Path, name: &str) {
        let name = name.trim();
        if name.is_empty() {
            return;
        }
        let target = parent.join(name);
        if target.exists() {
            self.toast(format!(
                "already exists: {}",
                rel_path(&self.workspace, &target)
            ));
            return;
        }
        if let Err(e) = std::fs::create_dir_all(&target) {
            self.toast(format!("mkdir failed: {e}"));
            return;
        }
        self.refresh_after_fs_change();
        self.toast(format!("created {}/", rel_path(&self.workspace, &target)));
    }

    /// Open the FS delete prompt — captures `path`. Renders as a
    /// two-button `[ Delete ] [ Cancel ]` confirm dialog (Cancel is
    /// the default focus for safety). Was: text-input asking the
    /// user to type the filename verbatim; user feedback 2026-07-06
    /// flagged the pattern as goofy compared to the quit dialog.
    pub fn open_fs_delete_prompt(&mut self, path: PathBuf) {
        self.pending_fs_action = Some(FsAction::Delete { path: path.clone() });
        // #20 v4 — surface the recursive-delete case explicitly.
        // Also count how many entries would be removed so the user
        // sees the blast radius before confirming.
        let is_dir = path.is_dir();
        let rel = rel_path(&self.workspace, &path);
        let title = if is_dir {
            let count = walk_entry_count(&path, 0, 500);
            let count_hint = if count >= 500 {
                "500+ entries".to_string()
            } else {
                format!("{count} entr{}", if count == 1 { "y" } else { "ies" })
            };
            format!("Delete {rel} recursively? ({count_hint})")
        } else {
            format!("Delete {rel}?")
        };
        // The alternate is a BUTTON now, not a hint appended here — see
        // `prompt::delete_buttons`. Inside the trash there is nothing to
        // defer to, so the question says so.
        let title = if path.parent() == Some(self.trash_dir().as_path()) {
            format!("{title}  (permanent — already in the trash)")
        } else {
            title
        };
        let mut prompt =
            crate::prompt::Prompt::new(crate::prompt::PromptKind::DeleteConfirm, title);
        // Focus Cancel by default — safety first for a destructive
        // action. Resolved by CODE, not by a hardcoded index: adding
        // the "Delete permanently" button shifted Cancel from 1 to 2,
        // and a stale literal here would have default-focused the
        // IRREVERSIBLE button.
        prompt.cursor = crate::ui::prompt::delete_buttons()
            .iter()
            .position(|(_, code, _)| *code == crate::ui::prompt::CONFIRM_BTN_CANCEL)
            .unwrap_or(0);
        self.prompt = Some(prompt);
    }

    /// Stage `path` on `file_clipboard`. `cut = true` marks paste as
    /// move; `cut = false` marks paste as copy. Multi-select support
    /// slots in here (push multiple; for now v1 is single-path).
    pub fn file_stage_clipboard(&mut self, path: PathBuf, cut: bool) {
        self.file_clipboard = vec![path.clone()];
        self.file_clipboard_cut = cut;
        let name = path
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_else(|| path.display().to_string());
        self.toast(format!("{} {}", if cut { "cut" } else { "copied" }, name));
    }

    /// Paste the clipboard into `target`. If `target` is a file, its
    /// parent dir is used. Cut = rename() the source; Copy = fs::copy
    /// (recursive for dirs). Refresh the tree; clear the clipboard on
    /// cut, keep it on copy so the same set can paste elsewhere.
    pub fn file_paste_into(&mut self, target: PathBuf) {
        if self.file_clipboard.is_empty() {
            self.toast("clipboard empty");
            return;
        }
        let target_dir = if target.is_dir() {
            target.clone()
        } else {
            target
                .parent()
                .map(|p| p.to_path_buf())
                .unwrap_or_else(|| self.workspace.clone())
        };
        if !target_dir.is_dir() {
            self.toast(format!("not a directory: {}", target_dir.display()));
            return;
        }
        let sources = self.file_clipboard.clone();
        let cut = self.file_clipboard_cut;
        // Resolve every (source, destination) pair FIRST — collision
        // bumping, same-directory rules, skips — then hand the whole set
        // to one background transfer. The worker never re-derives a
        // destination name, so this stays the single place those rules
        // live.
        let mut items: Vec<(PathBuf, PathBuf)> = Vec::new();
        for src in &sources {
            let Some(name) = src.file_name() else {
                self.toast(format!("skip (no filename): {}", src.display()));
                continue;
            };
            let mut dest = target_dir.join(name);
            // Same-dir copy: bump the filename so we don't clobber
            // the source. Cut into the same dir is a no-op (toast).
            if dest == *src {
                if cut {
                    continue;
                }
                dest = collision_free_copy_name(&dest);
            } else if dest.exists() {
                self.toast(format!(
                    "already exists: {}",
                    rel_path(&self.workspace, &dest)
                ));
                continue;
            }
            items.push((src.clone(), dest));
        }
        if items.is_empty() {
            // Nothing resolved — every source was skipped (a cut pasted
            // back into its own directory is the easy way to get here,
            // one "Paste here" on the source's own row). The clipboard
            // must SURVIVE: clearing it before this check meant the cut
            // silently evaporated with no operation and no toast, and
            // there was no way to get it back.
            self.toast("nothing to paste here");
            return;
        }
        // A destination already being written by a running transfer is
        // refused rather than raced. Two workers targeting one tree each
        // track their own "I created this" list, so a cancel or failure
        // in one can delete the other's finished output.
        if let Some(clash) = self.transfer_target_clash(&items) {
            self.toast(format!(
                "already {} — wait for it to finish",
                rel_path(&self.workspace, &clash)
            ));
            return;
        }
        if cut {
            self.file_clipboard.clear();
            self.file_clipboard_cut = false;
        }
        let n = items.len();
        let kind = if cut {
            crate::transfer::TransferKind::Move
        } else {
            crate::transfer::TransferKind::Copy
        };
        self.start_transfer(kind, items);
        // The listing refreshes when the transfer reports Done, a tick
        // or more from now — the cost of running off the render thread,
        // and the reason the toast says "started".
        self.toast(format!(
            "{} {n} item{} into {}",
            if cut { "moving" } else { "copying" },
            if n == 1 { "" } else { "s" },
            rel_path(&self.workspace, &target_dir)
        ));
    }

    /// Duplicate `path` in place with a `-copy` suffix; falls back to
    /// `-copy-2`, `-copy-3`, ... on collision.
    pub fn file_duplicate(&mut self, path: PathBuf) {
        let dest = collision_free_copy_name(&path);
        match copy_recursively(&path, &dest) {
            Ok(()) => {
                self.refresh_after_fs_change();
                self.toast(format!(
                    "duplicated {} \u{2192} {}",
                    rel_path(&self.workspace, &path),
                    rel_path(&self.workspace, &dest)
                ));
            }
            Err(e) => self.toast(format!("duplicate failed: {e}")),
        }
    }

    /// Open the "Move to..." prompt — the user types a destination
    /// directory (workspace-relative or absolute). Path suggestions
    /// come from the standard `is_path_kind` autocomplete path.
    pub fn file_open_move_to_picker(&mut self, path: PathBuf) {
        self.pending_fs_action = Some(FsAction::MoveTo {
            source: path.clone(),
        });
        let title = format!("Move {} to…", rel_path(&self.workspace, &path));
        let seed = path
            .parent()
            .map(|p| rel_path(&self.workspace, p))
            .unwrap_or_default();
        self.prompt = Some(crate::prompt::Prompt::seeded(
            crate::prompt::PromptKind::FileMoveTo,
            title,
            seed,
        ));
    }

    /// Resolve the "Move to..." prompt — moves the pending source
    /// into the typed destination directory.
    pub fn file_finish_move_to(&mut self, dest_text: &str) {
        let Some(FsAction::MoveTo { source }) = self.pending_fs_action.take() else {
            return;
        };
        let dest_dir_raw = dest_text.trim();
        if dest_dir_raw.is_empty() {
            self.toast("move: empty destination");
            return;
        }
        let dest_dir = expand_tilde_and_resolve(&self.workspace, dest_dir_raw);
        if let Err(e) = std::fs::create_dir_all(&dest_dir) {
            self.toast(format!("mkdir failed: {e}"));
            return;
        }
        let Some(name) = source.file_name() else {
            self.toast(format!("no filename in {}", source.display()));
            return;
        };
        let dest = dest_dir.join(name);
        if dest == source {
            self.toast("move: source and destination are the same");
            return;
        }
        if dest.exists() {
            self.toast(format!(
                "already exists: {}",
                rel_path(&self.workspace, &dest)
            ));
            return;
        }
        match std::fs::rename(&source, &dest) {
            Ok(()) => {
                self.refresh_after_fs_change();
                self.toast(format!(
                    "moved {} \u{2192} {}",
                    rel_path(&self.workspace, &source),
                    rel_path(&self.workspace, &dest)
                ));
            }
            Err(e) => self.toast(format!("move failed: {e}")),
        }
    }

    /// Dispatch handler for the generic destructive confirm-button
    /// dialogs (git delete branch / stash drop / worktree remove /
    /// tag delete / hunk discard / claude kill / merge / rebase).
    ///
    /// Rather than have N specialized `run_*_button` methods, this
    /// synthesizes the "magic string" each kind's accept handler
    /// expected (dynamic for `<name>`-style, static for `"drop"` /
    /// `"kill"` / etc.), writes it into `Prompt.input`, then calls
    /// the shared `accept_prompt` path. On cancel it writes an empty
    /// string so the else-branch fires and each kind's cancel logic
    /// runs unchanged.
    pub fn run_confirm_button(&mut self, primary: bool) {
        use crate::prompt::PromptKind::*;
        let Some(kind) = self.prompt.as_ref().map(|p| p.kind) else {
            return;
        };
        // Kinds where the accept handler doesn't check `Prompt.input`
        // at all (pure yes/no dispatch) get a direct routing rather
        // than a synthesized-input pass through `prompt_accept`.
        match kind {
            TreeMoveConfirm => {
                self.prompt = None;
                if primary {
                    self.accept_tree_move();
                } else {
                    self.pending_tree_move = None;
                    self.toast("move cancelled");
                }
                return;
            }
            AiToolConfirm => {
                self.prompt = None;
                self.resolve_tool_confirm(primary);
                return;
            }
            _ => {}
        }
        let synth = if primary {
            match kind {
                GitDeleteBranchConfirm => "delete".into(),
                WorktreeRemoveConfirm => "remove".into(),
                GitStashDrop => "drop".into(),
                GitTagDelete => self.pending_tag_delete.clone().unwrap_or_default(),
                DiffDiscardHunk => "discard".into(),
                GitDiscardFile => self
                    .pending_discard_file
                    .as_ref()
                    .and_then(|p| p.file_name())
                    .map(|n| n.to_string_lossy().into_owned())
                    .unwrap_or_default(),
                ClaudeKillConfirm => "kill".into(),
                GitMergeConfirm => "merge".into(),
                GitRebaseConfirm => "rebase".into(),
                // Both install-confirm handlers just check `input.starts_with('y')`.
                ToolInstallConfirm | MarketplaceInstallConfirm => "y".into(),
                IntegrationRemoveConfirm => "uninstall".into(),
                ResetToDefaultsConfirm => "reset".into(),
                WorkspaceTrustConfirm => "trust".into(),
                // Cancel side ("Keep trusted") synthesizes "" and the
                // accept handler treats anything but "revoke" as keep,
                // so Esc — which routes here with primary=false — is
                // inert. That's why Revoke is the primary label.
                WorkspaceTrustReview => "revoke".into(),
                // NB: this arm only ever runs with `primary == true` —
                // the whole `match` is inside `if primary`. It used to
                // carry an `else { "normal" }` branch that could never
                // execute; the cancel side lands on `String::new()`
                // below, which `dispatch_portable_choice` maps to
                // normal via its `_` arm. Same outcome, but the dead
                // branch read as if the cancel verb were wired up.
                PortableChoicePrompt => "portable".into(),
                _ => return,
            }
        } else {
            String::new()
        };
        if let Some(p) = self.prompt.as_mut() {
            p.input = synth;
        }
        self.prompt_accept();
    }

    /// Dispatch handler for the DeleteConfirm button dialog. Delete
    /// = execute, Cancel = drop the pending FsAction.
    pub fn run_delete_button(&mut self, code: u8) {
        self.run_delete_button_opts(code, false);
    }

    /// `permanent` skips the trash — the Option-held path.
    ///
    /// macOS's alternate-menu-item convention: holding Option turns a
    /// reversible action into its irreversible sibling. A terminal
    /// cannot see a HELD modifier (there is no event until a key or
    /// click arrives), so this hangs off the modifier on the confirming
    /// event rather than on hold-state, which is the same gesture from
    /// the user's side.
    pub fn run_delete_button_opts(&mut self, code: u8, permanent: bool) {
        let permanent = permanent || code == crate::ui::prompt::CONFIRM_BTN_PERMANENT;
        match code {
            crate::ui::prompt::CONFIRM_BTN_PRIMARY | crate::ui::prompt::CONFIRM_BTN_PERMANENT => {
                if let Some(FsAction::Delete { path }) = self.pending_fs_action.take() {
                    self.execute_delete_fs_entry_opts(&path, permanent);
                }
            }
            crate::ui::prompt::CONFIRM_BTN_CANCEL => {
                self.pending_fs_action = None;
                self.toast("delete cancelled");
            }
            _ => {}
        }
    }

    /// Execute the delete unconditionally — the caller (button
    /// dialog / test) is responsible for the confirmation gate.
    /// Removes any open editor buffer for the file; for a directory,
    /// removes every editor buffer under it. `rm` for a file,
    /// `rm -rf` for a dir.
    /// Refresh the primary file tree PLUS every extra workspace whose
    /// root is an ancestor of `path`. Use this after any filesystem
    /// mutation (delete / rename / paste / duplicate) so a change
    /// inside an extra workspace refreshes THAT extra's tree, not
    /// just the primary one. 2026-07-12 fix for stale row after
    /// delete-in-extra-workspace.
    pub fn refresh_trees_for_path(&mut self, path: &Path) {
        self.refresh_after_fs_change();
        for extra in self.extra_workspaces.iter_mut() {
            if path.starts_with(&extra.root) {
                extra.tree.refresh();
            }
        }
    }

    /// Workspace trash directory. A delete moves here rather than
    /// unlinking, so `pending_undo` has something to restore.
    pub fn trash_dir(&self) -> std::path::PathBuf {
        self.workspace.join(".mnml").join("trash")
    }

    /// Open the workspace trash as a Files pane.
    ///
    /// The 10-second undo toast was the ONLY way back; after it expired
    /// the entry sat in `.mnml/trash/` for a week reachable only from a
    /// terminal. Keeping a file for seven days and offering ten seconds
    /// to use it is a strange half-feature — this makes the seven days
    /// real, and it costs nothing new because a directory listing is
    /// already a pane.
    pub fn open_trash_pane(&mut self) {
        self.migrate_legacy_trash_index();
        let trash = self.trash_dir();
        if std::fs::create_dir_all(&trash).is_err() {
            self.toast("could not open the trash");
            return;
        }
        let empty = std::fs::read_dir(&trash)
            .map(|r| r.flatten().next().is_none())
            .unwrap_or(true);
        if empty {
            self.toast("trash is empty");
            return;
        }
        self.open_files_pane(Some(trash));
    }

    /// Put the selected trash entry back where it came from.
    ///
    /// Refuses rather than clobbers if something has taken the path
    /// since, and says so when the origin was never recorded — an entry
    /// trashed before the index existed has nowhere to go back to.
    pub fn restore_from_trash(&mut self) {
        let Some(from) = self.target_path() else {
            self.toast("nothing selected");
            return;
        };
        if from.parent() != Some(self.trash_dir().as_path()) {
            self.toast("not a trash entry");
            return;
        }
        let Some(entry) = from
            .file_name()
            .and_then(|n| n.to_str())
            .map(str::to_string)
        else {
            return;
        };
        let Some(to) = self.trash_origin_of(&entry) else {
            self.toast("no record of where this came from — move it by hand");
            return;
        };
        if to.exists() {
            self.toast(format!("{} already exists", rel_path(&self.workspace, &to)));
            return;
        }
        if let Some(parent) = to.parent() {
            let _ = std::fs::create_dir_all(parent);
        }
        match std::fs::rename(&from, &to) {
            Ok(()) => {
                self.refresh_trees_for_path(&to);
                self.toast(format!("restored {}", rel_path(&self.workspace, &to)));
            }
            Err(e) => self.toast(format!("restore failed: {e}")),
        }
    }

    /// Move a pre-existing `.mnml/trash/index.jsonl` out of the trash.
    ///
    /// The index used to live INSIDE the trash, where it rendered as a
    /// row beside the user's deleted files. Relocating it only changed
    /// where NEW writes go — an existing file kept sitting there
    /// (user: "i still see the index"). This carries it across once and
    /// removes the old one.
    fn migrate_legacy_trash_index(&self) {
        let legacy = self.trash_dir().join("index.jsonl");
        let Ok(old_body) = std::fs::read_to_string(&legacy) else {
            return;
        };
        let dest = self.trash_index_path();
        let mut merged = std::fs::read_to_string(&dest).unwrap_or_default();
        if !merged.is_empty() && !merged.ends_with('\n') {
            merged.push('\n');
        }
        merged.push_str(&old_body);
        if let Some(parent) = dest.parent() {
            let _ = std::fs::create_dir_all(parent);
        }
        // Only drop the old file once the merged copy is safely written,
        // or a failure here loses every recorded origin.
        if std::fs::write(&dest, merged).is_ok() {
            let _ = std::fs::remove_file(&legacy);
        }
    }

    /// Where the trash records what each entry used to be.
    ///
    /// The trash filename carries only a stamp and a BASENAME, so it
    /// cannot say where the entry came from. Without this, the 7-day
    /// retention is close to useless: you can see that `doomed.txt` is
    /// in there, but not which of four directories it belongs in. The
    /// 10-second undo toast held the original path in memory and lost it
    /// on expiry.
    pub fn trash_index_path(&self) -> std::path::PathBuf {
        // BESIDE the trash, not inside it. Kept inside, it showed up as
        // a row in the trash pane next to the entries — bookkeeping
        // masquerading as one of the user's deleted files (user: "why is
        // it visible here?"). Out here there is nothing to filter and
        // the emptiness check is just "is the directory empty".
        self.workspace.join(".mnml").join("trash-index.jsonl")
    }

    /// Record `trashed` (a path inside the trash) as having come from
    /// `origin`.
    fn record_trash_origin(&self, trashed: &Path, origin: &Path) {
        use std::io::Write;
        let Some(entry) = trashed.file_name().and_then(|n| n.to_str()) else {
            return;
        };
        let esc = |v: &str| v.replace('\\', r"\\").replace('"', "\\\"");
        let line = format!(
            "{{\"entry\":\"{}\",\"origin\":\"{}\"}}\n",
            esc(entry),
            esc(&origin.to_string_lossy())
        );
        if let Ok(mut f) = std::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(self.trash_index_path())
        {
            let _ = f.write_all(line.as_bytes());
        }
    }

    /// Where the trash entry named `entry` came from, if recorded.
    pub fn trash_origin_of(&self, entry: &str) -> Option<std::path::PathBuf> {
        let body = std::fs::read_to_string(self.trash_index_path()).ok()?;
        // Last match wins: the same basename can be trashed repeatedly,
        // and the newest record is the one that matches this entry.
        let mut found = None;
        for line in body.lines() {
            let e = json_str_field(line, "entry")?;
            if e == entry {
                found = json_str_field(line, "origin").map(std::path::PathBuf::from);
            }
        }
        found
    }

    /// An unused path in the trash for `name`.
    ///
    /// The stamp alone is NOT enough: `now_unix()` is second-resolution
    /// and `fs::rename` REPLACES an existing destination file. Deleting
    /// two files with the same basename inside one second therefore
    /// destroyed the first one's bytes — the precise outcome this
    /// feature exists to prevent, and silent, since the toast reads the
    /// same either way. A counter suffix makes the name unique.
    fn free_trash_path(trash: &Path, name: &str) -> std::path::PathBuf {
        let stamp = crate::app::now_unix();
        let first = trash.join(format!("{stamp}-{name}"));
        if !first.exists() {
            return first;
        }
        for n in 2..10_000u32 {
            let p = trash.join(format!("{stamp}-{n}-{name}"));
            if !p.exists() {
                return p;
            }
        }
        let nanos = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.subsec_nanos())
            .unwrap_or(0);
        trash.join(format!("{stamp}-{nanos}-{name}"))
    }

    /// When `entry` entered the trash, from the stamp encoded in its
    /// name.
    ///
    /// NOT the filesystem mtime. `rename` does not update mtime, so a
    /// file untouched for over a week was pruned on the very tick it was
    /// trashed, and the undo then pointed at nothing seconds after the
    /// toast promised it. Deleting an old file is the COMMON case, so
    /// that broke the feature for most of its uses.
    fn trashed_at(entry: &Path) -> Option<u64> {
        let name = entry.file_name()?.to_str()?;
        let digits: String = name.chars().take_while(|c| c.is_ascii_digit()).collect();
        if digits.is_empty() {
            return None;
        }
        digits.parse().ok()
    }

    /// Ceiling on the trash's total size.
    ///
    /// Age alone was not enough: deleting a large directory to reclaim
    /// disk space did not reclaim it for a week, and the trash sits on
    /// the same filesystem being cleaned up. Above this, the oldest
    /// entries go until it fits.
    const TRASH_MAX_BYTES: u64 = 512 * 1024 * 1024;

    /// Anything at least this big skips the trash entirely and is
    /// deleted outright.
    ///
    /// Moving a 4 GB directory into the trash only to evict it moments
    /// later is worse than not trashing it: the space is not freed, and
    /// the undo it offers is one the size cap is about to invalidate.
    /// The toast says the delete is not undoable, which the fallback
    /// path already words.
    const TRASH_SKIP_ABOVE_BYTES: u64 = 256 * 1024 * 1024;

    /// Drop trashed entries older than a week.
    ///
    /// Without this the directory grows forever — the delete is only
    /// deferred, not avoided. A week is long enough that "I deleted that
    /// yesterday" is still recoverable by hand.
    fn prune_trash(&self) {
        const MAX_AGE_SECS: u64 = 7 * 24 * 60 * 60;
        let Ok(rd) = std::fs::read_dir(self.trash_dir()) else {
            return;
        };
        let cutoff = crate::app::now_unix().saturating_sub(MAX_AGE_SECS);
        for e in rd.flatten() {
            // No stamp in the name ⇒ not ours; leave it rather than guess.
            let Some(at) = Self::trashed_at(&e.path()) else {
                continue;
            };
            if at > cutoff {
                continue;
            }
            let p = e.path();
            let _ = if p.is_dir() {
                std::fs::remove_dir_all(&p)
            } else {
                std::fs::remove_file(&p)
            };
        }
        self.evict_trash_over_budget();
        self.prune_trash_index();
    }

    /// Drop index lines whose trash entry no longer exists.
    ///
    /// Otherwise the index outlives everything it describes and grows
    /// for the life of the workspace — one line per delete, forever.
    fn prune_trash_index(&self) {
        let path = self.trash_index_path();
        let Ok(body) = std::fs::read_to_string(&path) else {
            return;
        };
        let trash = self.trash_dir();
        let kept: Vec<&str> = body
            .lines()
            .filter(|l| json_str_field(l, "entry").is_some_and(|e| trash.join(e).exists()))
            .collect();
        if kept.len() != body.lines().count() {
            let mut out = kept.join("\n");
            if !out.is_empty() {
                out.push('\n');
            }
            let _ = std::fs::write(&path, out);
        }
    }

    /// Evict oldest-first until the trash fits under
    /// [`Self::TRASH_MAX_BYTES`].
    fn evict_trash_over_budget(&self) {
        let trash = self.trash_dir();
        let Ok(rd) = std::fs::read_dir(&trash) else {
            return;
        };
        let cancel = std::sync::atomic::AtomicBool::new(false);
        let mut entries: Vec<(u64, std::path::PathBuf, u64)> = rd
            .flatten()
            .filter_map(|e| {
                let p = e.path();
                let at = Self::trashed_at(&p)?;
                let (bytes, _) = crate::transfer::measure(std::slice::from_ref(&p), &cancel);
                Some((at, p, bytes))
            })
            .collect();
        let mut total: u64 = entries.iter().map(|(_, _, b)| *b).sum();
        if total <= Self::TRASH_MAX_BYTES {
            return;
        }
        entries.sort_by_key(|(at, _, _)| *at); // oldest first
        for (_, p, bytes) in entries {
            if total <= Self::TRASH_MAX_BYTES {
                break;
            }
            let removed = if p.is_dir() {
                std::fs::remove_dir_all(&p).is_ok()
            } else {
                std::fs::remove_file(&p).is_ok()
            };
            if removed {
                total = total.saturating_sub(bytes);
            }
        }
    }

    pub fn execute_delete_fs_entry(&mut self, path: &Path) {
        self.execute_delete_fs_entry_opts(path, false);
    }

    /// `force_permanent` bypasses the trash entirely.
    pub fn execute_delete_fs_entry_opts(&mut self, path: &Path, force_permanent: bool) {
        let is_dir = path.is_dir();
        // Move to the workspace trash instead of unlinking, so the
        // delete is undoable. The app has had `pending_undo` all along;
        // a Files-pane delete simply never offered it, which made it the
        // one operation you could not take back.
        //
        // Falls back to a hard delete when the move fails — a trash on a
        // different filesystem, or an unwritable workspace. Better to
        // still delete than to refuse, but no undo is offered then,
        // because there would be nothing to restore.
        let name = path
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_else(|| "entry".to_string());
        // Something huge skips the trash: moving it there would not free
        // the space the user is trying to reclaim, and the undo it
        // offered would be evicted by the size cap moments later.
        let cancel = std::sync::atomic::AtomicBool::new(false);
        let (bytes, _) =
            crate::transfer::measure(std::slice::from_ref(&path.to_path_buf()), &cancel);
        let too_big = bytes >= Self::TRASH_SKIP_ABOVE_BYTES;

        let trash = self.trash_dir();
        // Already IN the trash ⇒ delete for real. Moving it to a fresh
        // stamped name in the same directory produced absurdities like
        // `1788195310-1788195284-CHANGELOG-copy.md` and never actually
        // removed anything (user report). The trash is the end of the
        // line; there is nowhere further to defer to.
        let already_trashed = force_permanent || path.parent() == Some(trash.as_path());
        let made_trash = !too_big && !already_trashed && std::fs::create_dir_all(&trash).is_ok();
        let dest = Self::free_trash_path(&trash, &name);
        let moved = made_trash && std::fs::rename(path, &dest).is_ok();

        if !moved {
            let res = if is_dir {
                std::fs::remove_dir_all(path)
            } else {
                std::fs::remove_file(path)
            };
            if let Err(e) = res {
                self.toast(format!("delete failed: {e}"));
                return;
            }
        } else {
            self.record_trash_origin(&dest, path);
            self.set_pending_undo(
                format!("deleted {name}"),
                crate::app::UndoAction::RestoreDeletedPath {
                    from: dest,
                    to: path.to_path_buf(),
                },
            );
            self.prune_trash();
        }
        // Always, not only on the trashed path: a PERMANENT delete of a
        // trash entry also orphans its index line, and that path never
        // reaches `prune_trash`.
        self.prune_trash_index();
        // Force-close any editor buffer for the deleted file (or dir contents).
        let affected: Vec<usize> = self
            .panes
            .iter()
            .enumerate()
            .filter_map(|(i, p)| match p {
                Pane::Editor(b) => b.path.as_deref().and_then(|bp| {
                    if bp == path || (is_dir && bp.starts_with(path)) {
                        Some(i)
                    } else {
                        None
                    }
                }),
                _ => None,
            })
            .collect();
        for i in affected.into_iter().rev() {
            self.force_close_pane(i);
        }
        self.lsp.did_close(path);
        // Trim out of recent_files.
        self.recent_files
            .retain(|p| p != path && !(is_dir && p.starts_with(path)));
        // 2026-07-12 — refresh the extra workspace's tree too if
        // the deleted path lived inside one; previously only the
        // primary tree rescanned, so extra-workspace rows for the
        // deleted file hung around until a manual refresh.
        self.refresh_trees_for_path(path);
        // Bug 2026-07-06: right-click Delete on an HTTP-sidebar file
        // row was refreshing the file tree but NOT the HTTP panel's
        // own cache — the row stayed visible until the user closed +
        // reopened the section. Refresh the HTTP cache whenever a
        // path the panel might display gets deleted. Cheap to run
        // unconditionally (walks `.http` / `.curl` / `.rest` in the
        // workspace + `.mnml/` subdirs).
        self.http_panel_refresh();
        // Says so when it is NOT recoverable. The two paths read
        // identically otherwise, so the user could not tell afterwards
        // whether a given delete could be taken back.
        self.toast(format!(
            "deleted {}{}{}",
            rel_path(&self.workspace, path),
            if is_dir { "/" } else { "" },
            match (moved, too_big, already_trashed) {
                (true, _, _) => "",
                (false, _, true) => " — permanently",
                (false, true, _) => " (no undo — too large to keep)",
                (false, false, _) => " (no undo — trash unavailable)",
            }
        ));
    }

    /// Rename `from` → `<from.parent()>/new_name`. If `from` is open as an
    /// editor buffer, the buffer is repointed at the new path (LSP gets a
    /// close/open pair). Refuses an existing target.
    pub fn rename_fs_entry(&mut self, from: &Path, new_name: &str) {
        let new_name = new_name.trim();
        if new_name.is_empty() {
            return;
        }
        let Some(parent) = from.parent() else {
            self.toast("can't rename — no parent dir");
            return;
        };
        let to = parent.join(new_name);
        if to == from {
            return;
        }
        if to.exists() {
            self.toast(format!(
                "already exists: {}",
                rel_path(&self.workspace, &to)
            ));
            return;
        }
        if let Err(e) = std::fs::rename(from, &to) {
            self.toast(format!("rename failed: {e}"));
            return;
        }
        // Repoint any open buffer for `from` at `to`.
        for pane in &mut self.panes {
            if let Pane::Editor(b) = pane
                && b.path.as_deref() == Some(from)
            {
                b.path = Some(to.clone());
            }
        }
        self.lsp.did_close(from);
        // If still open as an editor, notify the LSP about the new path.
        let new_text = self.panes.iter().find_map(|p| match p {
            Pane::Editor(b) if b.is_at(&to) => Some(b.editor.text().to_string()),
            _ => None,
        });
        if let Some(t) = new_text {
            self.lsp.did_open(&to, &t);
        }
        // Update recent_files too.
        for p in &mut self.recent_files {
            if p == from {
                *p = to.clone();
            }
        }
        // 2026-07-12 — refresh whichever tree owns the source /
        // destination path so an extra-workspace rename doesn't leave
        // a stale row. `from` and `to` share a parent, so refreshing
        // either root is enough — refresh from `from` to cover the
        // "source moves out" case.
        self.refresh_trees_for_path(from);
        self.toast(format!(
            "renamed {}{}",
            rel_path(&self.workspace, from),
            rel_path(&self.workspace, &to),
        ));
    }
}

impl App {
    /// The path the user means RIGHT NOW, for a file operation.
    ///
    /// #files — every `file.*` command used to read
    /// `app.tree.selected_file()` directly, so a `Pane::Files` was
    /// read-only: no cut, copy, paste, rename, delete or right-click,
    /// however many rows it showed. The underlying methods already take
    /// paths, so the whole gap was this resolver not existing.
    ///
    /// Precedence is FOCUS, not pane existence: a Files pane only wins
    /// while it has focus. Otherwise having one open anywhere would
    /// silently retarget the tree's own Ctrl+X, and a delete aimed at the
    /// wrong file is the worst outcome in this whole area.
    pub fn target_path(&self) -> Option<std::path::PathBuf> {
        if self.focus == crate::focus::Focus::Pane
            && let Some(i) = self.active
            && let Some(crate::pane::Pane::Files(f)) = self.panes.get(i)
        {
            return f.selected_entry().map(|e| e.path.clone());
        }
        self.tree.selected_file()
    }

    /// Every path an operation should act on.
    ///
    /// #files item 2 — the marked set when a focused Files pane has one,
    /// otherwise whatever [`Self::target_path`] resolves to. This is what
    /// makes marking mean anything: without it `Space` would decorate rows
    /// and Ctrl+C would still copy one file.
    pub fn target_paths(&self) -> Vec<std::path::PathBuf> {
        if self.focus == crate::focus::Focus::Pane
            && let Some(i) = self.active
            && let Some(crate::pane::Pane::Files(f)) = self.panes.get(i)
        {
            return f.action_paths();
        }
        self.target_path().into_iter().collect()
    }

    /// Stage several paths on the file clipboard.
    ///
    /// `file_clipboard` was always a `Vec` — `file_stage_clipboard` simply
    /// only ever put one path in it, so paste already handles a set.
    /// The paths a Files-pane menu item should act on — the mark set when
    /// there is one, else the row under the cursor.
    ///
    /// #files — delegates to `action_paths` so the mouse menu and the
    /// keyboard chords cannot disagree about the subject of an operation.
    pub fn files_pane_marked_paths(&self, pane_id: crate::layout::PaneId) -> Vec<PathBuf> {
        match self.panes.get(pane_id) {
            Some(crate::pane::Pane::Files(f)) => f.action_paths(),
            _ => Vec::new(),
        }
    }

    pub fn file_stage_clipboard_many(&mut self, paths: Vec<std::path::PathBuf>, cut: bool) {
        if paths.is_empty() {
            return;
        }
        if paths.len() == 1 {
            let p = paths.into_iter().next().unwrap();
            self.file_stage_clipboard(p, cut);
            return;
        }
        let n = paths.len();
        self.file_clipboard = paths;
        self.file_clipboard_cut = cut;
        self.toast(format!("{} {n} items", if cut { "cut" } else { "copied" }));
    }

    /// The DIRECTORY a new file / paste should land in.
    ///
    /// Distinct from [`Self::target_path`] because "paste here" means the
    /// current directory when a file is selected, not a sibling of it.
    pub fn target_dir(&self) -> Option<std::path::PathBuf> {
        if self.focus == crate::focus::Focus::Pane
            && let Some(i) = self.active
            && let Some(crate::pane::Pane::Files(f)) = self.panes.get(i)
        {
            return Some(f.cwd.clone());
        }
        self.tree.selected_file().map(|p| {
            if p.is_dir() {
                p
            } else {
                p.parent().map(|q| q.to_path_buf()).unwrap_or(p)
            }
        })
    }

    /// Re-read the tree AND every Files pane after a filesystem change.
    ///
    /// #files — the single place a mutation announces itself. The mouse
    /// tester's headline finding was that the pane "does not refresh after
    /// its own operations": deleting a file through the pane's own
    /// Delete… left the row painted, and clicking that ghost row opened an
    /// empty DIRTY buffer for the deleted path, offering to save it back.
    /// Duplicate, Paste-here and New file… were the same — "the effect is
    /// on disk, the listing is a lie until you re-navigate".
    ///
    /// Every Files pane reloads, not just one showing a given directory.
    /// A move changes TWO directories (source and destination), so the
    /// earlier per-directory variant was wrong by construction: it
    /// refreshed where the file landed and left the place it came from
    /// still showing it. Panes are few and `reload()` is one `read_dir`,
    /// so refreshing all of them is both simpler and correct.
    pub fn refresh_after_fs_change(&mut self) {
        self.tree.refresh();
        for p in self.panes.iter_mut() {
            if let crate::pane::Pane::Files(f) = p {
                f.reload();
            }
        }
        // The sidebar list panels keep their OWN file caches, which a
        // create / delete / rename left stale: the new note was absent,
        // or the deleted row lingered, until the user clicked the panel's
        // refresh chip (user report 2026-09-01). The same class of bug
        // was already fixed once for the HTTP panel, in the delete path
        // only — this is the shared chokepoint, so fixing it here covers
        // create, delete, rename and background transfers at once.
        //
        // Only the DIRECTORY-SCOPED caches are refreshed. `todos` is
        // deliberately excluded: `todos_panel_refresh` is a synchronous
        // walk of the whole workspace, and running that on every file
        // operation would be exactly the kind of per-frame full scan
        // that caused this editor's previous freezes. A TODO marker
        // also cannot appear from a file operation the way a note or a
        // finding can — it needs an edit, which has its own trigger.
        self.notes_panel_refresh();
        self.findings_panel_refresh();
    }

    /// Enter the selected directory, or open the selected file.
    ///
    /// The two are one gesture (`Enter` / `l` / double-click) because that
    /// is how every file manager behaves — the user is saying "go to this
    /// thing", and whether that means descend or open is the pane's
    /// problem, not theirs.
    pub fn files_pane_activate(&mut self, pane_idx: usize) {
        let Some(crate::pane::Pane::Files(f)) = self.panes.get_mut(pane_idx) else {
            return;
        };
        if f.enter_selected() {
            return;
        }
        // Not a directory — open it. `open_path` already routes by
        // extension (Request panes for .http, image panes for images,
        // editor otherwise), so a Files pane inherits all of that.
        let Some(path) = f.selected_entry().map(|e| e.path.clone()) else {
            return;
        };
        self.open_path(&path);
    }

    /// Two Files panes side by side — the commander layout.
    ///
    /// #files — the first version ran `open_files_pane` then
    /// `view.split_right` then `open_files_pane`, and `split_active`
    /// creates a PLACEHOLDER pane for the new side (a scratch buffer)
    /// when it has nothing to move there. The second Files pane then
    /// landed as a TAB beside that placeholder, so the right leaf opened
    /// showing `[scratch]` next to the browser. User report, with a
    /// screenshot: "whenever i open the dual browser the right side one
    /// gets a scratch tab, why?"
    ///
    /// `split_leaf_with` takes the pane to put on the new side, so the
    /// second browser IS the new side and no placeholder is ever created.
    pub fn open_dual_files_panes(&mut self) {
        let dir = self.workspace.clone();
        self.open_files_pane(Some(dir.clone()));
        let Some(left) = self.active else { return };
        let right = crate::pane::Pane::Files(crate::file_browser::FileBrowserPane::open(&dir));
        let id = self.split_leaf_with(left, crate::layout::SplitDir::Horizontal, right);
        self.active = Some(id);
        self.focus = crate::focus::Focus::Pane;
    }

    /// Preview the selected file WITHOUT leaving the Files pane.
    ///
    /// #files item 4. The flow this exists for is "arrow down a listing
    /// glancing at each file", so two things matter: the preview must
    /// REPLACE the previous one rather than stacking tabs, and focus must
    /// stay in the browser so the next arrow keeps working.
    ///
    /// Reuses `open_path_preview`, whose docstring said only the
    /// tree-click handler should call it — that comment is now updated,
    /// because this IS the same gesture: "show me this, I am still
    /// browsing". Everything it routes by extension comes free (images to
    /// the image pane, markdown to MdPreview, the rest to an editor).
    ///
    /// A directory previews as nothing. Descending is what Enter is for,
    /// and opening a directory in an editor pane is not a preview.
    pub fn files_pane_preview(&mut self, pane_idx: usize) {
        let Some(crate::pane::Pane::Files(f)) = self.panes.get(pane_idx) else {
            return;
        };
        let Some(e) = f.selected_entry() else { return };
        if e.is_dir {
            return;
        }
        let path = e.path.clone();
        let prev = f.preview_pane;

        // The preview must land in a DIFFERENT LEAF from the browser.
        //
        // The first version let it open into the browser's own leaf and
        // then restored `App::active` to the browser. That set input focus
        // and the leaf's visible tab to DIFFERENT panes: the leaf showed
        // the preview while every keystroke drove the now-invisible
        // listing. A second `p` then replaced that preview in place and
        // evicted the browser from the layout entirely — in the dual-pane
        // layout it collapsed both halves into one editor. Found by the
        // vim tester, who could still fire `Ctrl+D` and duplicate a file
        // the screen gave no indication was selected.
        //
        // A preview that covers the listing is not a preview; netrw and
        // oil.nvim both open into a split for the same reason.
        let browser_leaf: Vec<crate::layout::PaneId> = self
            .layout()
            .leaf_containing(pane_idx)
            .map(|t| t.to_vec())
            .unwrap_or_default();
        let reusable = prev.filter(|&id| {
            self.layout().contains(id)
                && !browser_leaf.contains(&id)
                && matches!(self.panes.get(id), Some(crate::pane::Pane::Editor(b)) if b.is_preview)
        });
        match reusable {
            // Previous preview still lives in its own leaf — replace it
            // there.
            Some(id) => self.active = Some(id),
            None => {
                // Give the preview a leaf of its own. Seeded with a
                // preview-marked scratch so `open_path_preview` REPLACES
                // it rather than leaving a `[scratch]` tab behind — the
                // same trap that produced a stray scratch pane in
                // `open_dual_files_panes`.
                let mut b = crate::buffer::Buffer::scratch(&self.config);
                b.is_preview = true;
                let new_id = self.split_leaf_with(
                    pane_idx,
                    crate::layout::SplitDir::Horizontal,
                    crate::pane::Pane::Editor(b),
                );
                self.active = Some(new_id);
            }
        }
        self.open_path_preview(&path);
        let opened = self.active;
        if let Some(crate::pane::Pane::Files(f)) = self.panes.get_mut(pane_idx) {
            f.preview_pane = opened;
        }
        // Hand focus back to the browser — and via `reveal_pane`, so the
        // browser's LEAF shows it too. Setting `App::active` alone is what
        // caused the invisible-cursor bug above.
        self.reveal_pane(pane_idx);
        self.focus = crate::focus::Focus::Pane;
    }

    /// Open a Files pane at `dir` (defaults to the workspace root).
    pub fn open_files_pane(&mut self, dir: Option<std::path::PathBuf>) {
        let dir = dir.unwrap_or_else(|| self.workspace.clone());
        let pane = crate::pane::Pane::Files(crate::file_browser::FileBrowserPane::open(&dir));
        self.panes.push(pane);
        let id = self.panes.len() - 1;
        self.reveal_pane(id);
        self.focus = crate::focus::Focus::Pane;
    }
}

#[cfg(test)]
mod target_path_tests {
    use crate::app::App;
    use crate::config::Config;
    use crate::focus::Focus;

    fn fixture() -> (tempfile::TempDir, App) {
        let d = tempfile::tempdir().unwrap();
        std::fs::create_dir(d.path().join("sub")).unwrap();
        std::fs::write(d.path().join("sub").join("inner.txt"), "x").unwrap();
        std::fs::write(d.path().join("root.txt"), "y").unwrap();
        let app = App::new(d.path().to_path_buf(), Config::default()).unwrap();
        (d, app)
    }

    /// #files — the resolver is why a Files pane can do anything at all.
    /// Every `file.*` command read `tree.selected_file()` directly, so the
    /// pane was read-only however many rows it showed.
    #[test]
    fn a_focused_files_pane_owns_the_target() {
        let _lk = crate::test_env_lock()
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let (d, mut app) = fixture();
        app.open_files_pane(Some(d.path().join("sub")));
        assert_eq!(app.focus, Focus::Pane, "open_files_pane should focus it");

        let got = app.target_path().expect("no target");
        assert_eq!(
            got.file_name().unwrap(),
            "inner.txt",
            "target should be the Files pane's selection, got {got:?}"
        );
    }

    /// Precedence is FOCUS, not existence. An open-but-unfocused Files
    /// pane must not retarget the tree's own Ctrl+X — a delete aimed at
    /// the wrong file is the worst outcome in this area.
    #[test]
    fn an_unfocused_files_pane_does_not_steal_the_target() {
        let _lk = crate::test_env_lock()
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let (d, mut app) = fixture();
        app.open_files_pane(Some(d.path().join("sub")));
        // User moves focus back to the tree.
        app.focus = Focus::Tree;

        let got = app.target_path();
        assert!(
            got.is_none_or(|p| p.file_name().unwrap() != "inner.txt"),
            "an unfocused Files pane hijacked the tree's target"
        );
    }

    /// "Paste here" means the current directory, not a sibling of the
    /// selected file.
    #[test]
    fn target_dir_is_the_panes_cwd_not_the_selections_parent() {
        let _lk = crate::test_env_lock()
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let (d, mut app) = fixture();
        app.open_files_pane(Some(d.path().join("sub")));
        let got = app.target_dir().expect("no target dir");
        assert_eq!(got.file_name().unwrap(), "sub", "got {got:?}");
    }

    /// An operation that changes a directory must be reflected without the
    /// user pressing `r` — in EVERY Files pane, not just the one whose cwd
    /// matches.
    ///
    /// This replaces an earlier test that asserted the opposite (refresh
    /// only the panes showing the touched directory). That scoping is
    /// wrong by construction: a move changes two directories at once, so
    /// the destination pane kept showing a stale listing. `refresh_files_panes_for`
    /// went with it rather than stay as an API that looks scoped and
    /// silently ignores its argument.
    #[test]
    fn a_refresh_reaches_every_files_pane_not_just_the_touched_directory() {
        let _lk = crate::test_env_lock()
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let (d, mut app) = fixture();
        app.open_files_pane(Some(d.path().join("sub")));
        let pid = app.active.unwrap();
        let before = match app.panes.get(pid) {
            Some(crate::pane::Pane::Files(f)) => f.entries.len(),
            _ => panic!(),
        };

        std::fs::write(d.path().join("sub").join("added.txt"), "z").unwrap();
        app.refresh_after_fs_change();
        let after = match app.panes.get(pid) {
            Some(crate::pane::Pane::Files(f)) => f.entries.len(),
            _ => panic!(),
        };
        assert_eq!(
            after,
            before + 1,
            "the pane did not re-read its directory after an fs change"
        );
    }
}

#[cfg(test)]
mod open_split_tests {
    use crate::app::App;
    use crate::config::Config;

    /// `files.open_split` is the commander shape. Never tested when it
    /// shipped — verify it really produces TWO Files panes side by side
    /// rather than two tabs of one leaf.
    #[test]
    fn open_split_yields_exactly_two_panes_and_nothing_else() {
        let _lk = crate::test_env_lock()
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let d = tempfile::tempdir().unwrap();
        std::fs::write(d.path().join("a.txt"), "a").unwrap();
        let mut app = App::new(d.path().to_path_buf(), Config::default()).unwrap();

        crate::command::run("files.open_split", &mut app);

        let ids = app.layout().all_panes();
        let files = ids
            .iter()
            .filter(|&&i| matches!(app.panes.get(i), Some(crate::pane::Pane::Files(_))))
            .count();
        assert_eq!(files, 2, "expected two Files panes, got {files}");

        // THE ASSERTION THAT WAS MISSING. The first version of this test
        // checked only "two Files panes exist in a split" and passed while
        // the right leaf also carried a `[scratch]` placeholder tab —
        // `split_active` creates one when it has nothing to move to the new
        // side. Counting Files panes could never see it; counting EVERY
        // pane in the layout can.
        assert_eq!(
            ids.len(),
            2,
            "the layout holds {} panes, not 2 — something extra came along: {:?}",
            ids.len(),
            ids.iter()
                .map(|&i| app.panes.get(i).map(|p| p.title()))
                .collect::<Vec<_>>()
        );

        // Every leaf must hold exactly ONE tab, or a browser is hidden
        // behind a tab strip instead of being visible side by side.
        for &id in &ids {
            let tabs = app
                .layout()
                .leaf_containing(id)
                .map(|t| t.len())
                .unwrap_or(0);
            assert_eq!(
                tabs, 1,
                "leaf containing pane {id} has {tabs} tabs; the second pane \
                 is a tab rather than a split side"
            );
        }

        assert!(
            matches!(app.layout(), crate::layout::Layout::Split { .. }),
            "the two panes are not in a split"
        );
    }
}

#[cfg(test)]
mod entry_point_tests {
    use crate::app::App;
    use crate::config::Config;

    /// #files — every advertised route must actually resolve to a
    /// registered command. mnml has shipped menu rows pointing at
    /// non-existent command ids twice (#1226 View/Go menus, and the
    /// palette-bar `+` chip), and both times the label promised something
    /// the wiring could not deliver.
    #[test]
    fn every_files_entry_point_names_a_registered_command() {
        for id in ["files.open", "files.open_split"] {
            assert!(
                crate::command::registry().all().iter().any(|c| c.id == id),
                "`{id}` is advertised in a menu but is not registered"
            );
        }
    }

    /// The View menu rows specifically — a menu label is a promise.
    #[test]
    fn the_view_menu_offers_both_file_pane_rows() {
        let _lk = crate::test_env_lock()
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let d = tempfile::tempdir().unwrap();
        let app = App::new(d.path().to_path_buf(), Config::default()).unwrap();
        let menus = crate::menu_bar::bar(&app);
        let view = menus
            .iter()
            .find(|m| m.label == "View")
            .expect("no View menu");
        let ids: Vec<&str> = view
            .items
            .iter()
            .filter_map(|i| match i {
                crate::menu_bar::MenuItem::Action { command_id, .. } => Some(command_id.as_str()),
                _ => None,
            })
            .collect();
        assert!(
            ids.contains(&"files.open"),
            "View menu has no file-browser row: {ids:?}"
        );
        assert!(
            ids.contains(&"files.open_split"),
            "View menu has no dual-pane row: {ids:?}"
        );
    }

    /// A folder's right-click must offer to open it AS a browser, at that
    /// folder — not at the workspace root, which would make the user
    /// navigate back down to where they already were.
    #[test]
    fn a_folder_right_click_opens_the_browser_at_that_folder() {
        let _lk = crate::test_env_lock()
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let d = tempfile::tempdir().unwrap();
        std::fs::create_dir(d.path().join("deep")).unwrap();
        let mut app = App::new(d.path().to_path_buf(), Config::default()).unwrap();
        let dir = d.path().join("deep");
        app.open_tree_context_menu(dir.clone(), true, (2, 2));
        let menu = app.context_menu.take().expect("no menu");
        let action = menu
            .items
            .iter()
            .find(|i| i.label.contains("file browser"))
            .map(|i| i.action.clone())
            .expect("no 'Open in file browser' row on a folder");
        // The action must CARRY the right-clicked directory. Asserted on
        // the payload rather than by firing it, because opening at the
        // workspace root instead would still produce a Files pane — the
        // failure this guards against is a pane at the WRONG place.
        match action {
            crate::context_menu::MenuAction::OpenFilesPane(p) => assert_eq!(
                p.canonicalize().unwrap(),
                dir.canonicalize().unwrap(),
                "the row carries the wrong directory"
            ),
            other => panic!("wrong action on the row: {other:?}"),
        }
    }
}

#[cfg(test)]
mod multi_select_tests {
    use crate::app::App;
    use crate::config::Config;

    fn fixture() -> (tempfile::TempDir, App, usize) {
        let d = tempfile::tempdir().unwrap();
        for n in ["one.txt", "two.txt", "three.txt"] {
            std::fs::write(d.path().join(n), n).unwrap();
        }
        std::fs::create_dir(d.path().join("dest")).unwrap();
        let mut app = App::new(d.path().to_path_buf(), Config::default()).unwrap();
        app.open_files_pane(None);
        let pid = app.active.unwrap();
        (d, app, pid)
    }

    /// #files item 2 — the whole point: Ctrl+C must stage the MARKED SET,
    /// not one file. Without this, `Space` would just decorate rows.
    #[test]
    fn copy_stages_every_marked_path() {
        let _lk = crate::test_env_lock()
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let (_d, mut app, pid) = fixture();
        if let Some(crate::pane::Pane::Files(f)) = app.panes.get_mut(pid) {
            f.selected = 0;
            f.toggle_mark(); // marks + advances
            f.toggle_mark();
        }
        crate::command::run("file.copy", &mut app);
        assert_eq!(
            app.file_clipboard.len(),
            2,
            "clipboard holds {:?}, expected the two marked paths",
            app.file_clipboard
        );
        assert!(!app.file_clipboard_cut, "copy must not be a cut");
    }

    /// And with nothing marked it still stages the cursor row, so every
    /// operation works without ever pressing Space.
    #[test]
    fn copy_without_marks_stages_the_cursor_row() {
        let _lk = crate::test_env_lock()
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let (_d, mut app, pid) = fixture();
        if let Some(crate::pane::Pane::Files(f)) = app.panes.get_mut(pid) {
            f.selected = 1;
        }
        crate::command::run("file.copy", &mut app);
        assert_eq!(app.file_clipboard.len(), 1, "{:?}", app.file_clipboard);
    }

    /// Review finding — the clipboard was cleared in the `cut` branch
    /// BEFORE checking whether anything resolved. A cut pasted back into
    /// its own directory (one "Paste here" on the source's own row)
    /// skipped every source, returned with no toast, and wiped the cut.
    /// The user's clipboard silently evaporated with nothing done.
    #[test]
    fn a_cut_pasted_into_its_own_directory_keeps_the_clipboard() {
        let _lk = crate::test_env_lock()
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let (d, mut app, pid) = fixture();
        if let Some(crate::pane::Pane::Files(f)) = app.panes.get_mut(pid) {
            f.selected = f.entries.iter().position(|e| e.name == "one.txt").unwrap();
            f.toggle_mark();
        }
        crate::command::run("file.cut", &mut app);
        assert_eq!(app.file_clipboard.len(), 1, "setup: one staged");
        assert!(app.file_clipboard_cut, "setup: staged as a cut");

        // Paste back into the directory it already lives in.
        app.file_paste_into(d.path().to_path_buf());

        assert_eq!(
            app.file_clipboard.len(),
            1,
            "the cut clipboard was wiped by a paste that did nothing"
        );
        assert!(app.file_clipboard_cut, "the cut flag was cleared too");
        assert!(
            app.transfers.is_empty(),
            "a no-op paste still started a transfer"
        );
    }

    /// A marked set must actually paste — the clipboard being a Vec is not
    /// proof that paste iterates it.
    #[test]
    fn pasting_a_marked_set_copies_every_file() {
        let _lk = crate::test_env_lock()
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let (d, mut app, pid) = fixture();
        // Mark the three FILES explicitly.
        //
        // The first version started at index 0 and toggled three times,
        // which silently included `dest` — directories sort first — so it
        // pasted `dest` INTO `dest`. That recursed until the stack ran out
        // and CI aborted with `fatal runtime error: stack overflow`. The
        // crash was a real product bug (now guarded in `copy_recursively`),
        // but this test should be deliberate about what it marks rather
        // than depending on sort order.
        if let Some(crate::pane::Pane::Files(f)) = app.panes.get_mut(pid) {
            for name in ["one.txt", "two.txt", "three.txt"] {
                f.selected = f.entries.iter().position(|e| e.name == name).unwrap();
                f.toggle_mark();
            }
            assert!(
                f.marked.iter().all(|p| p.is_file()),
                "a directory got marked: {:?}",
                f.marked
            );
        }
        crate::command::run("file.copy", &mut app);
        assert_eq!(app.file_clipboard.len(), 3, "setup: three staged");

        let dest = d.path().join("dest");
        app.file_paste_into(dest.clone());

        // Paste is ASYNC now (#files item 6 — every file operation goes
        // through the background worker, so a large copy can never freeze
        // the editor). The test drives the tick the event loop would.
        let t0 = std::time::Instant::now();
        while !app.transfers.is_empty() && t0.elapsed() < std::time::Duration::from_secs(10) {
            app.poll_transfers();
            std::thread::sleep(std::time::Duration::from_millis(5));
        }
        assert!(
            app.transfers.is_empty(),
            "the paste transfer never finished"
        );

        let landed = std::fs::read_dir(&dest).unwrap().count();
        assert_eq!(
            landed, 3,
            "only {landed} of 3 marked files were pasted — paste does not \
             iterate the clipboard"
        );
    }

    /// An unfocused Files pane must not contribute its marks — same
    /// reasoning as `target_path`: a bulk delete aimed at the wrong set is
    /// the worst outcome in this area.
    #[test]
    fn an_unfocused_panes_marks_are_ignored() {
        let _lk = crate::test_env_lock()
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let (_d, mut app, pid) = fixture();
        if let Some(crate::pane::Pane::Files(f)) = app.panes.get_mut(pid) {
            f.selected = 0;
            f.toggle_mark();
            f.toggle_mark();
        }
        app.focus = crate::focus::Focus::Tree;
        let paths = app.target_paths();
        assert!(
            paths.len() <= 1,
            "an unfocused pane's marks leaked into the target set: {paths:?}"
        );
    }
}

#[cfg(test)]
mod preview_tests {
    use crate::app::App;
    use crate::config::Config;
    use crate::focus::Focus;

    fn fixture(style: &str) -> (tempfile::TempDir, App, usize) {
        let d = tempfile::tempdir().unwrap();
        for n in ["one.txt", "two.txt", "three.txt"] {
            std::fs::write(d.path().join(n), n).unwrap();
        }
        std::fs::create_dir(d.path().join("adir")).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();
        // Cursor onto the first FILE. Directories sort first, so index 0
        // is `adir` — an earlier version of these tests previewed a
        // directory and then asserted about panes that were never opened.
        if let Some(crate::pane::Pane::Files(f)) = app.panes.get_mut(pid) {
            f.selected = f.entries.iter().position(|e| !e.is_dir).unwrap();
        }
        (d, app, pid)
    }

    /// #files item 4 — the flow is "arrow down glancing at each file", so
    /// focus must STAY in the browser. `open_path_preview` focuses what it
    /// opens, which is right for a tree click and wrong here.
    #[test]
    fn previewing_keeps_focus_in_the_files_pane() {
        let _lk = crate::test_env_lock()
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let (_d, mut app, pid) = fixture("standard");
        app.files_pane_preview(pid);
        assert_eq!(
            app.active,
            Some(pid),
            "preview moved focus out of the listing; the next `j` would \
             scroll the previewed file instead"
        );
        assert_eq!(app.focus, Focus::Pane);
    }

    /// SEV-1 from the vim tester — the invariant they proposed, and it
    /// is the right one: after a preview, the pane that owns the keyboard
    /// must still be IN the layout, and must be the visible tab of its
    /// leaf. Otherwise keystrokes drive an invisible pane, and `Ctrl+D`
    /// duplicates a file nothing on screen says is selected.
    #[test]
    fn the_browser_stays_visible_and_in_the_layout_after_previews() {
        let _lk = crate::test_env_lock()
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let (_d, mut app, pid) = fixture("standard");
        for _ in 0..3 {
            app.files_pane_preview(pid);
            if let Some(crate::pane::Pane::Files(f)) = app.panes.get_mut(pid) {
                f.move_selection(1);
            }

            let active = app.active.expect("no active pane");
            assert!(
                app.layout().contains(active),
                "active pane {active} is not in the layout — keystrokes are \
                 driving something invisible"
            );
            assert_eq!(active, pid, "focus left the browser");
            // And the browser must be its leaf's VISIBLE tab, not just
            // the input target.
            let leaf_active = app.layout().leaf_active_for(pid);
            assert_eq!(
                leaf_active,
                Some(pid),
                "the browser owns the keyboard but its leaf is showing a \
                 different pane"
            );
            assert!(
                app.layout().contains(pid),
                "the browser was evicted from the layout by a preview"
            );
        }
    }

    /// And the preview has to be somewhere you can actually see — its own
    /// leaf, beside the listing.
    #[test]
    fn the_preview_lands_in_a_different_leaf_from_the_browser() {
        let _lk = crate::test_env_lock()
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let (_d, mut app, pid) = fixture("standard");
        app.files_pane_preview(pid);
        let preview = match app.panes.get(pid) {
            Some(crate::pane::Pane::Files(f)) => f.preview_pane.expect("no preview recorded"),
            _ => panic!(),
        };
        let browser_leaf = app
            .layout()
            .leaf_containing(pid)
            .map(|t| t.to_vec())
            .unwrap_or_default();
        assert!(
            !browser_leaf.contains(&preview),
            "the preview opened INTO the browser's leaf, so it covers the \
             listing it is supposed to preview from"
        );
        assert!(app.layout().contains(preview), "preview not in the layout");
    }

    /// And it must actually open something.
    #[test]
    fn previewing_opens_the_selected_file() {
        let _lk = crate::test_env_lock()
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let (_d, mut app, pid) = fixture("standard");
        let before = app.panes.len();
        app.files_pane_preview(pid);
        assert!(app.panes.len() > before, "no pane opened");
    }

    /// Previewing several files in a row must REPLACE, not stack — the
    /// whole point of using the preview-tab mechanism.
    #[test]
    fn previewing_several_files_reuses_one_tab() {
        let _lk = crate::test_env_lock()
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let (_d, mut app, pid) = fixture("standard");
        app.files_pane_preview(pid);
        let after_first = app.panes.len();
        for _ in 0..3 {
            if let Some(crate::pane::Pane::Files(f)) = app.panes.get_mut(pid) {
                f.move_selection(1);
            }
            app.files_pane_preview(pid);
        }
        assert_eq!(
            app.panes.len(),
            after_first,
            "each preview opened a new pane — arrowing through a directory \
             would bury the browser in tabs"
        );
    }

    /// A directory is not previewable — Enter descends into it, and
    /// opening a folder in an editor pane is not a preview.
    #[test]
    fn previewing_a_directory_does_nothing() {
        let _lk = crate::test_env_lock()
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let (_d, mut app, pid) = fixture("standard");
        // Back onto the directory (`adir` sorts first).
        if let Some(crate::pane::Pane::Files(f)) = app.panes.get_mut(pid) {
            f.selected = 0;
            assert!(f.selected_entry().unwrap().is_dir, "setup: cursor on a dir");
        }
        let before = app.panes.len();
        app.files_pane_preview(pid);
        assert_eq!(
            app.panes.len(),
            before,
            "a directory was opened as a preview"
        );
    }
}

#[cfg(test)]
mod refresh_after_ops_tests {
    use crate::app::App;
    use crate::config::Config;

    /// Mouse tester SEV-2 (headline) — "the effect is on disk, the
    /// listing is a lie until you re-navigate". Deleting through the
    /// pane's own menu left the row painted, and clicking that ghost row
    /// opened an empty DIRTY buffer for the deleted path, offering to save
    /// it back.
    #[test]
    fn deleting_a_file_removes_its_row_without_a_manual_refresh() {
        let _lk = crate::test_env_lock()
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let d = tempfile::tempdir().unwrap();
        std::fs::write(d.path().join("doomed.txt"), "x").unwrap();
        std::fs::write(d.path().join("keeper.txt"), "y").unwrap();
        let mut app = App::new(d.path().to_path_buf(), Config::default()).unwrap();
        app.open_files_pane(None);
        let pid = app.active.unwrap();

        std::fs::remove_file(d.path().join("doomed.txt")).unwrap();
        app.refresh_after_fs_change();

        let names: Vec<String> = match app.panes.get(pid) {
            Some(crate::pane::Pane::Files(f)) => f.entries.iter().map(|e| e.name.clone()).collect(),
            _ => panic!(),
        };
        assert!(
            !names.contains(&"doomed.txt".to_string()),
            "the deleted file is still listed — clicking it opens a dirty \
             buffer for a path that no longer exists: {names:?}"
        );
        assert!(names.contains(&"keeper.txt".to_string()), "{names:?}");
    }

    /// A MOVE changes two directories. The earlier per-directory refresh
    /// was wrong by construction: it updated where the file landed and
    /// left the place it came from still showing it.
    #[test]
    fn a_move_refreshes_both_the_source_and_destination_panes() {
        let _lk = crate::test_env_lock()
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let d = tempfile::tempdir().unwrap();
        let src = d.path().join("src");
        let dst = d.path().join("dst");
        std::fs::create_dir_all(&src).unwrap();
        std::fs::create_dir_all(&dst).unwrap();
        std::fs::write(src.join("moving.txt"), "x").unwrap();

        let mut app = App::new(d.path().to_path_buf(), Config::default()).unwrap();
        app.open_files_pane(Some(src.clone()));
        let src_pane = app.active.unwrap();
        app.open_files_pane(Some(dst.clone()));
        let dst_pane = app.active.unwrap();

        std::fs::rename(src.join("moving.txt"), dst.join("moving.txt")).unwrap();
        app.refresh_after_fs_change();

        let listed = |app: &App, pid: usize| -> Vec<String> {
            match app.panes.get(pid) {
                Some(crate::pane::Pane::Files(f)) => {
                    f.entries.iter().map(|e| e.name.clone()).collect()
                }
                _ => panic!(),
            }
        };
        assert!(
            !listed(&app, src_pane).contains(&"moving.txt".to_string()),
            "the SOURCE pane still lists the file it no longer holds"
        );
        assert!(
            listed(&app, dst_pane).contains(&"moving.txt".to_string()),
            "the destination pane did not pick up the arrival"
        );
    }
}

#[cfg(test)]
mod delete_undo_tests {
    use crate::app::App;
    use crate::config::Config;
    /// Deleting a SYMLINK to a directory must not touch the target.
    ///
    /// Review flagged this as unverified: the hard-delete fallback picks
    /// `remove_dir_all` vs `remove_file` from `path.is_dir()`, which
    /// FOLLOWS symlinks — so a symlink-to-directory takes the
    /// `remove_dir_all` branch. Verified rather than assumed:
    /// `remove_dir_all` does not follow symlinks, it unlinks the link
    /// itself. This test pins that, since the whole fallback rests on it.
    #[test]
    #[cfg(unix)]
    fn deleting_a_symlink_to_a_directory_leaves_the_target_alone() {
        let (_d, mut app, _f) = app_with_file();
        let outside = tempfile::tempdir().unwrap();
        let real = outside.path().join("real");
        std::fs::create_dir(&real).unwrap();
        std::fs::write(real.join("precious.txt"), b"do not delete").unwrap();

        let link = app.workspace.join("link");
        std::os::unix::fs::symlink(&real, &link).unwrap();

        app.execute_delete_fs_entry(&link);

        assert!(
            std::fs::symlink_metadata(&link).is_err(),
            "the symlink itself survived the delete"
        );
        assert!(
            real.join("precious.txt").exists(),
            "deleting a symlink wiped the directory it pointed at"
        );
    }

    /// ...and the same on the HARD-DELETE fallback, which is the path
    /// the review was actually worried about — the trash move never
    /// happens there.
    #[test]
    #[cfg(unix)]
    fn the_fallback_delete_also_spares_a_symlink_target() {
        let (_d, mut app, _f) = app_with_file();
        let outside = tempfile::tempdir().unwrap();
        let real = outside.path().join("real");
        std::fs::create_dir(&real).unwrap();
        std::fs::write(real.join("precious.txt"), b"do not delete").unwrap();
        let link = app.workspace.join("link");
        std::os::unix::fs::symlink(&real, &link).unwrap();

        // Force the trash move to fail: a FILE where the directory goes.
        std::fs::create_dir_all(app.workspace.join(".mnml")).unwrap();
        std::fs::write(app.trash_dir(), b"not a directory").unwrap();

        app.execute_delete_fs_entry(&link);

        assert!(
            app.pending_undo.is_none(),
            "setup: expected the fallback path"
        );
        assert!(
            real.join("precious.txt").exists(),
            "the fallback delete wiped the symlink's target"
        );
    }

    fn app_with_file() -> (tempfile::TempDir, App, std::path::PathBuf) {
        let d = tempfile::tempdir().unwrap();
        let app = App::new(d.path().to_path_buf(), Config::default()).unwrap();
        let f = app.workspace.join("doomed.txt");
        std::fs::write(&f, b"precious").unwrap();
        (d, app, f)
    }

    /// A Files-pane delete was the one operation with no way back — the
    /// app has had `pending_undo` all along and this path never offered
    /// it. It is now a move into `.mnml/trash/`, so undo is a rename.
    #[test]
    fn deleting_offers_an_undo_that_restores_the_file() {
        let (_d, mut app, f) = app_with_file();
        app.execute_delete_fs_entry(&f);
        assert!(!f.exists(), "the file is still in place");
        assert!(
            app.pending_undo.is_some(),
            "a delete offered no undo affordance"
        );

        app.commit_pending_undo();
        assert!(f.is_file(), "undo did not bring the file back");
        assert_eq!(std::fs::read(&f).unwrap(), b"precious", "content changed");
    }

    /// Directories too — `remove_dir_all` was the truly unrecoverable
    /// one, and a rename handles a tree as cheaply as a file.
    #[test]
    fn deleting_a_directory_is_also_undoable() {
        let (_d, mut app, _f) = app_with_file();
        let dir = app.workspace.join("adir");
        std::fs::create_dir_all(dir.join("nested")).unwrap();
        std::fs::write(dir.join("nested/x.txt"), b"deep").unwrap();

        app.execute_delete_fs_entry(&dir);
        assert!(!dir.exists());
        assert!(app.pending_undo.is_some(), "no undo for a directory");
        app.commit_pending_undo();
        assert_eq!(
            std::fs::read(dir.join("nested/x.txt")).unwrap(),
            b"deep",
            "the tree did not come back intact"
        );
    }

    /// Undo must refuse rather than clobber something that has taken the
    /// path back in the meantime.
    #[test]
    fn undo_does_not_overwrite_a_file_recreated_at_the_same_path() {
        let (_d, mut app, f) = app_with_file();
        app.execute_delete_fs_entry(&f);
        std::fs::write(&f, b"newer").unwrap();

        app.commit_pending_undo();
        assert_eq!(
            std::fs::read(&f).unwrap(),
            b"newer",
            "undo clobbered a file that had been recreated"
        );
    }

    /// REVIEW CRITICAL 1 — `now_unix()` is second-resolution and
    /// `fs::rename` REPLACES an existing destination file. Two deletes
    /// of the same basename inside one second destroyed the first file's
    /// bytes outright, with an identical success toast either way.
    #[test]
    fn two_deletes_of_the_same_name_in_one_second_both_survive() {
        let (_d, mut app, _f) = app_with_file();
        std::fs::create_dir_all(app.workspace.join("a")).unwrap();
        std::fs::create_dir_all(app.workspace.join("b")).unwrap();
        let one = app.workspace.join("a/same.txt");
        let two = app.workspace.join("b/same.txt");
        std::fs::write(&one, b"FIRST").unwrap();
        std::fs::write(&two, b"SECOND").unwrap();

        app.execute_delete_fs_entry(&one);
        app.execute_delete_fs_entry(&two);

        let bodies: Vec<Vec<u8>> = std::fs::read_dir(app.trash_dir())
            .unwrap()
            .flatten()
            .filter(|e| e.path().is_file() && e.file_name() != "index.jsonl")
            .map(|e| std::fs::read(e.path()).unwrap())
            .collect();
        assert_eq!(
            bodies.len(),
            2,
            "one delete overwrote the other in the trash: {bodies:?}"
        );
        assert!(bodies.contains(&b"FIRST".to_vec()), "FIRST was destroyed");
        assert!(bodies.contains(&b"SECOND".to_vec()), "SECOND was destroyed");
    }

    /// REVIEW CRITICAL 2 — pruning aged entries by filesystem mtime, and
    /// `rename` does not update mtime. Any file untouched for over a week
    /// was pruned on the very tick it was trashed, so the undo pointed at
    /// nothing seconds after the toast promised it. Deleting an OLD file
    /// is the common case, which broke the feature for most of its uses.
    ///
    /// The first version of the prune test aged a PRE-EXISTING trash
    /// entry, so it never exercised this at all.
    #[test]
    fn deleting_a_file_older_than_the_retention_window_is_still_undoable() {
        let (_d, mut app, f) = app_with_file();
        // Back-date the file itself well past the 7-day window.
        let ancient = std::time::SystemTime::now() - std::time::Duration::from_secs(60 * 86400);
        std::fs::File::options()
            .write(true)
            .open(&f)
            .unwrap()
            .set_modified(ancient)
            .unwrap();

        app.execute_delete_fs_entry(&f);
        let undo = app.pending_undo.as_ref().expect("no undo offered");
        let crate::app::UndoAction::RestoreDeletedPath { from, .. } = &undo.action else {
            panic!("wrong undo action");
        };
        assert!(
            from.exists(),
            "the trashed copy was pruned on the same tick it was created — \
             undo points at nothing"
        );

        app.commit_pending_undo();
        assert!(f.is_file(), "undo could not restore an old file");
    }

    /// A delete that could NOT be trashed must say so — the two paths
    /// read identically before, so the user had no way to tell whether a
    /// given delete was recoverable.
    #[test]
    fn a_delete_without_undo_says_so() {
        let (_d, mut app, f) = app_with_file();
        // Make the trash path unusable: a FILE where the directory goes.
        std::fs::create_dir_all(app.workspace.join(".mnml")).unwrap();
        std::fs::write(app.trash_dir(), b"not a directory").unwrap();

        app.execute_delete_fs_entry(&f);
        assert!(!f.exists(), "the file survived a fallback delete");
        assert!(
            app.pending_undo.is_none(),
            "offered an undo with nothing to restore"
        );
        let toast = app
            .toast
            .as_ref()
            .map(|(t, _)| t.clone())
            .unwrap_or_default();
        assert!(
            toast.contains("no undo"),
            "the toast does not say the delete was unrecoverable: {toast:?}"
        );
    }

    /// The trash must be bounded by SIZE, not only age. Deleting a large
    /// directory to reclaim space did not reclaim it for a week, and the
    /// trash sits on the same filesystem being cleaned up.
    #[test]
    fn the_trash_evicts_oldest_first_when_over_budget() {
        let (_d, mut app, f) = app_with_file();
        let trash = app.trash_dir();
        std::fs::create_dir_all(&trash).unwrap();

        // Three stamped entries, oldest first, together over budget.
        let now = crate::app::now_unix();
        let big = vec![0u8; (App::TRASH_MAX_BYTES / 2) as usize + 1];
        for (i, age) in [(0u32, 300u64), (1, 200), (2, 100)] {
            std::fs::write(trash.join(format!("{}-old{i}.bin", now - age)), &big).unwrap();
        }

        app.execute_delete_fs_entry(&f);

        let names: Vec<String> = std::fs::read_dir(&trash)
            .unwrap()
            .flatten()
            .map(|e| e.file_name().to_string_lossy().into_owned())
            .collect();
        assert!(
            !names.iter().any(|n| n.contains("old0")),
            "the OLDEST entry was not evicted first: {names:?}"
        );
        assert!(
            names.iter().any(|n| n.contains("doomed.txt")),
            "the entry just deleted was evicted: {names:?}"
        );
    }

    /// Something very large skips the trash entirely — moving it there
    /// would not free the space, and the undo would be evicted by the
    /// size cap moments later. The toast has to say so.
    #[test]
    fn a_very_large_delete_skips_the_trash_and_says_so() {
        let (_d, mut app, _f) = app_with_file();
        let big_dir = app.workspace.join("huge");
        std::fs::create_dir_all(&big_dir).unwrap();
        std::fs::write(
            big_dir.join("blob.bin"),
            vec![0u8; App::TRASH_SKIP_ABOVE_BYTES as usize + 1],
        )
        .unwrap();

        app.execute_delete_fs_entry(&big_dir);

        assert!(!big_dir.exists(), "the directory was not deleted");
        assert!(
            app.pending_undo.is_none(),
            "offered an undo for something it did not keep"
        );
        let toast = app
            .toast
            .as_ref()
            .map(|(t, _)| t.clone())
            .unwrap_or_default();
        assert!(
            toast.contains("too large"),
            "the toast does not explain why there is no undo: {toast:?}"
        );
        // ...and the space really is free: nothing landed in the trash.
        let trashed = std::fs::read_dir(app.trash_dir())
            .map(|r| r.count())
            .unwrap_or(0);
        assert_eq!(trashed, 0, "it went to the trash anyway");
    }

    /// The trash is bounded — a deferred delete that is never collected
    /// is just a disk leak.
    ///
    /// Ages by the STAMP IN THE NAME, which is when the entry was
    /// trashed. The earlier version of this test set a filesystem mtime,
    /// which `rename` never updates — so it tested a mechanism the prune
    /// no longer uses, and never covered the case that actually broke
    /// (an old file trashed and immediately pruned).
    #[test]
    fn stale_trash_entries_are_pruned() {
        let (_d, mut app, f) = app_with_file();
        let trash = app.trash_dir();
        std::fs::create_dir_all(&trash).unwrap();
        let old_stamp = crate::app::now_unix() - (30 * 86400);
        let old = trash.join(format!("{old_stamp}-ancient.txt"));
        std::fs::write(&old, b"x").unwrap();
        // An entry with no stamp is not ours and must be left alone.
        let foreign = trash.join("someone-elses-file.txt");
        std::fs::write(&foreign, b"y").unwrap();

        app.execute_delete_fs_entry(&f);

        assert!(!old.exists(), "a month-old trash entry survived the prune");
        assert!(foreign.exists(), "pruned an entry that was not ours");
        let entries = std::fs::read_dir(&trash)
            .unwrap()
            .flatten()
            .filter(|e| e.file_name() != "index.jsonl")
            .count();
        assert_eq!(entries, 2, "expected the fresh entry + the foreign one");
    }
}

#[cfg(test)]
mod trash_view_tests {
    use crate::app::App;
    use crate::config::Config;

    fn app_with(files: &[&str]) -> (tempfile::TempDir, App) {
        let d = tempfile::tempdir().unwrap();
        let app = App::new(d.path().to_path_buf(), Config::default()).unwrap();
        for f in files {
            let p = app.workspace.join(f);
            std::fs::create_dir_all(p.parent().unwrap()).unwrap();
            std::fs::write(&p, f.as_bytes()).unwrap();
        }
        (d, app)
    }

    /// The trash filename carries a stamp and a BASENAME only, so it
    /// cannot say where the entry came from. Without the index, a
    /// week of retention is close to useless: you can see `x.txt` is in
    /// there, not which of four directories it belongs in.
    #[test]
    fn restoring_puts_the_entry_back_where_it_came_from() {
        let (_d, mut app) = app_with(&["deep/nested/x.txt"]);
        let orig = app.workspace.join("deep/nested/x.txt");
        app.execute_delete_fs_entry(&orig);
        assert!(!orig.exists(), "setup: not deleted");

        // Open the trash and select the entry, as the user would.
        app.open_trash_pane();
        let pid = app.active.expect("no pane opened");
        if let Some(crate::pane::Pane::Files(f)) = app.panes.get_mut(pid) {
            f.selected = f
                .entries
                .iter()
                .position(|e| e.name.ends_with("x.txt"))
                .expect("the trashed entry is not listed");
        }
        app.restore_from_trash();

        assert!(
            orig.is_file(),
            "restore did not put the file back at its original path"
        );
        assert_eq!(std::fs::read(&orig).unwrap(), b"deep/nested/x.txt");
    }

    /// Two files with the same basename from different directories must
    /// each go back to their OWN directory — the whole point of
    /// recording the origin rather than guessing from the name.
    #[test]
    fn same_named_files_restore_to_their_own_directories() {
        let (_d, mut app) = app_with(&["a/dup.txt", "b/dup.txt"]);
        let a = app.workspace.join("a/dup.txt");
        let b = app.workspace.join("b/dup.txt");
        app.execute_delete_fs_entry(&a);
        app.execute_delete_fs_entry(&b);

        // Restore whichever entry maps to `b`.
        let entries: Vec<String> = std::fs::read_dir(app.trash_dir())
            .unwrap()
            .flatten()
            .map(|e| e.file_name().to_string_lossy().into_owned())
            .filter(|n| n != "index.jsonl")
            .collect();
        let for_b = entries
            .iter()
            .find(|n| app.trash_origin_of(n).as_deref() == Some(b.as_path()))
            .expect("no index record points at b/dup.txt");
        assert!(
            app.trash_origin_of(for_b).unwrap().ends_with("b/dup.txt"),
            "the origin index confused two same-named files"
        );
    }

    /// USER ASK — "can we do a keypress while this is open to get
    /// alternate option Delete Permanently so we can skip trash, on mac
    /// it's like option."
    ///
    /// macOS's alternate-menu-item convention. A terminal cannot see a
    /// HELD modifier — there is no event until a key or click arrives —
    /// so this hangs off the modifier on the CONFIRMING event, which is
    /// the same gesture from the user's side.
    #[test]
    fn option_on_the_confirm_skips_the_trash() {
        let (_d, mut app) = app_with(&["doomed.txt"]);
        let f = app.workspace.join("doomed.txt");
        app.open_fs_delete_prompt(f.clone());
        app.run_delete_button_opts(crate::ui::prompt::CONFIRM_BTN_PRIMARY, true);

        assert!(!f.exists(), "the file was not deleted");
        let trashed = std::fs::read_dir(app.trash_dir())
            .map(|r| r.count())
            .unwrap_or(0);
        assert_eq!(trashed, 0, "Option-delete still went through the trash");
        assert!(
            app.pending_undo.is_none(),
            "offered an undo for something it did not keep"
        );
    }

    /// ...and WITHOUT Option it still trashes, or the modifier would be
    /// meaningless.
    #[test]
    fn a_plain_confirm_still_uses_the_trash() {
        let (_d, mut app) = app_with(&["doomed.txt"]);
        let f = app.workspace.join("doomed.txt");
        app.open_fs_delete_prompt(f.clone());
        app.run_delete_button_opts(crate::ui::prompt::CONFIRM_BTN_PRIMARY, false);

        assert!(!f.exists());
        let trashed = std::fs::read_dir(app.trash_dir())
            .map(|r| r.count())
            .unwrap_or(0);
        assert_eq!(trashed, 1, "a plain delete did not reach the trash");
        assert!(app.pending_undo.is_some(), "no undo offered");
    }

    /// The alternate has to be VISIBLE. It started as text appended to
    /// the question ("⌥ to skip the trash"); the user asked for it to be
    /// an option on the modal instead, so it is a button.
    #[test]
    fn the_delete_dialog_offers_a_permanent_button() {
        let labels: Vec<&str> = crate::ui::prompt::delete_buttons()
            .iter()
            .map(|(l, _, _)| *l)
            .collect();
        assert!(
            labels.iter().any(|l| l.contains("permanently")),
            "no permanent-delete button: {labels:?}"
        );
    }

    /// Cancel must stay the DEFAULT focus. Adding the permanent button
    /// shifted Cancel from index 1 to 2 — a hardcoded `cursor = 1` would
    /// have default-focused the irreversible action.
    #[test]
    fn cancel_is_still_the_default_focus() {
        let (_d, mut app) = app_with(&["doomed.txt"]);
        app.open_fs_delete_prompt(app.workspace.join("doomed.txt"));
        let cursor = app.prompt.as_ref().unwrap().cursor;
        let buttons = crate::ui::prompt::delete_buttons();
        assert_eq!(
            buttons[cursor].1,
            crate::ui::prompt::CONFIRM_BTN_CANCEL,
            "default focus is {:?}, not Cancel",
            buttons[cursor].0
        );
    }

    /// The permanent BUTTON skips the trash, same as the modifier.
    #[test]
    fn the_permanent_button_skips_the_trash() {
        let (_d, mut app) = app_with(&["doomed.txt"]);
        let f = app.workspace.join("doomed.txt");
        app.open_fs_delete_prompt(f.clone());
        app.run_delete_button_opts(crate::ui::prompt::CONFIRM_BTN_PERMANENT, false);

        assert!(!f.exists());
        let trashed = std::fs::read_dir(app.trash_dir())
            .map(|r| r.count())
            .unwrap_or(0);
        assert_eq!(trashed, 0, "the permanent button still trashed the file");
    }

    /// Inside the trash there is no alternate to offer — it says the
    /// delete is permanent instead of promising a modifier that would
    /// change nothing.
    #[test]
    fn inside_the_trash_the_dialog_says_permanent_instead() {
        let (_d, mut app) = app_with(&["doomed.txt"]);
        app.execute_delete_fs_entry(&app.workspace.join("doomed.txt"));
        let entry = std::fs::read_dir(app.trash_dir())
            .unwrap()
            .flatten()
            .map(|e| e.path())
            .next()
            .unwrap();
        app.open_fs_delete_prompt(entry);
        let title = app
            .prompt
            .as_ref()
            .map(|p| p.title.clone())
            .unwrap_or_default();
        assert!(title.contains("permanent"), "title was {title:?}");
        assert!(
            !title.contains("skip the trash"),
            "promised an alternate that does nothing here: {title:?}"
        );
    }

    /// USER REPORT — deleting something already IN the trash re-trashed
    /// it: a fresh stamped name in the same directory, producing
    /// `1788195310-1788195284-CHANGELOG-copy.md` and never removing
    /// anything. The trash is the end of the line.
    #[test]
    fn deleting_an_entry_already_in_the_trash_removes_it_for_real() {
        let (_d, mut app) = app_with(&["gone.txt"]);
        let orig = app.workspace.join("gone.txt");
        app.execute_delete_fs_entry(&orig);

        let entry = std::fs::read_dir(app.trash_dir())
            .unwrap()
            .flatten()
            .map(|e| e.path())
            .next()
            .expect("nothing in the trash");

        app.execute_delete_fs_entry(&entry);

        assert!(!entry.exists(), "the trash entry survived a second delete");
        let left = std::fs::read_dir(app.trash_dir()).unwrap().count();
        assert_eq!(
            left,
            0,
            "re-trashed instead of deleting: {:?}",
            std::fs::read_dir(app.trash_dir())
                .unwrap()
                .flatten()
                .map(|e| e.file_name())
                .collect::<Vec<_>>()
        );
        let toast = app
            .toast
            .as_ref()
            .map(|(t, _)| t.clone())
            .unwrap_or_default();
        assert!(
            toast.contains("permanently"),
            "did not say the delete was permanent: {toast:?}"
        );
    }

    /// USER REPORT — the origin index sat INSIDE the trash directory, so
    /// it rendered as a row beside the real entries: bookkeeping
    /// masquerading as one of the user's deleted files.
    #[test]
    fn the_origin_index_is_not_inside_the_trash_directory() {
        let (_d, mut app) = app_with(&["x.txt"]);
        app.execute_delete_fs_entry(&app.workspace.join("x.txt"));

        let names: Vec<String> = std::fs::read_dir(app.trash_dir())
            .unwrap()
            .flatten()
            .map(|e| e.file_name().to_string_lossy().into_owned())
            .collect();
        assert_eq!(
            names.len(),
            1,
            "the trash holds more than the entry: {names:?}"
        );
        assert!(
            !names.iter().any(|n| n.contains("index")),
            "the index is listed as a trash entry: {names:?}"
        );
        assert!(
            app.trash_index_path().is_file(),
            "the index was not written at all"
        );
    }

    /// USER REPORT — "i still see the index". Relocating the index only
    /// changed where NEW writes go; a file already sitting inside the
    /// trash stayed there and kept rendering as a row.
    #[test]
    fn a_legacy_index_inside_the_trash_is_migrated_out() {
        let (_d, mut app) = app_with(&[]);
        let trash = app.trash_dir();
        std::fs::create_dir_all(&trash).unwrap();
        let legacy = trash.join("index.jsonl");
        std::fs::write(
            &legacy,
            "{\"entry\":\"1-old.txt\",\"origin\":\"/tmp/old.txt\"}\n",
        )
        .unwrap();
        // Something else in the trash so the pane actually opens.
        std::fs::write(trash.join("1-old.txt"), b"x").unwrap();

        app.open_trash_pane();

        assert!(
            !legacy.exists(),
            "the legacy index is still inside the trash"
        );
        let moved = std::fs::read_to_string(app.trash_index_path()).unwrap();
        assert!(
            moved.contains("1-old.txt"),
            "migration dropped the recorded origins:\n{moved}"
        );
    }

    /// Migration must not lose records already at the new location.
    #[test]
    fn migration_merges_rather_than_overwrites() {
        let (_d, mut app) = app_with(&["keep.txt"]);
        app.execute_delete_fs_entry(&app.workspace.join("keep.txt"));
        let before = std::fs::read_to_string(app.trash_index_path()).unwrap();
        assert!(before.contains("keep.txt"), "setup");

        let legacy = app.trash_dir().join("index.jsonl");
        std::fs::write(
            &legacy,
            "{\"entry\":\"1-old.txt\",\"origin\":\"/tmp/old.txt\"}\n",
        )
        .unwrap();
        std::fs::write(app.trash_dir().join("1-old.txt"), b"x").unwrap();

        app.open_trash_pane();

        let after = std::fs::read_to_string(app.trash_index_path()).unwrap();
        assert!(
            after.contains("keep.txt"),
            "migration clobbered existing records"
        );
        assert!(
            after.contains("1-old.txt"),
            "migration dropped the legacy records"
        );
    }

    /// The index must not outlive what it describes — one line per
    /// delete, forever, otherwise.
    #[test]
    fn index_lines_are_dropped_when_their_entry_is_gone() {
        let (_d, mut app) = app_with(&["a.txt", "b.txt"]);
        app.execute_delete_fs_entry(&app.workspace.join("a.txt"));
        app.execute_delete_fs_entry(&app.workspace.join("b.txt"));
        assert_eq!(
            std::fs::read_to_string(app.trash_index_path())
                .unwrap()
                .lines()
                .count(),
            2
        );

        // Permanently remove one, then trigger a prune with another delete.
        let first = std::fs::read_dir(app.trash_dir())
            .unwrap()
            .flatten()
            .map(|e| e.path())
            .next()
            .unwrap();
        app.execute_delete_fs_entry(&first);

        let lines = std::fs::read_to_string(app.trash_index_path()).unwrap();
        assert_eq!(
            lines.lines().count(),
            1,
            "the index still names an entry that is gone:\n{lines}"
        );
    }

    /// An entry trashed before the index existed has nowhere to go back
    /// to — say so rather than guessing a destination.
    #[test]
    fn an_entry_with_no_recorded_origin_is_refused() {
        let (_d, mut app) = app_with(&[]);
        let trash = app.trash_dir();
        std::fs::create_dir_all(&trash).unwrap();
        let orphan = trash.join(format!("{}-orphan.txt", crate::app::now_unix()));
        std::fs::write(&orphan, b"x").unwrap();

        app.open_trash_pane();
        let pid = app.active.expect("no pane");
        if let Some(crate::pane::Pane::Files(f)) = app.panes.get_mut(pid) {
            f.selected = f
                .entries
                .iter()
                .position(|e| e.name.contains("orphan"))
                .unwrap();
        }
        app.restore_from_trash();

        assert!(orphan.exists(), "moved an entry with no known origin");
        let toast = app
            .toast
            .as_ref()
            .map(|(t, _)| t.clone())
            .unwrap_or_default();
        assert!(
            toast.contains("no record"),
            "did not explain why it refused: {toast:?}"
        );
    }

    /// An empty trash should say so rather than opening a blank pane.
    #[test]
    fn opening_an_empty_trash_says_so() {
        let (_d, mut app) = app_with(&[]);
        app.open_trash_pane();
        let toast = app
            .toast
            .as_ref()
            .map(|(t, _)| t.clone())
            .unwrap_or_default();
        assert!(toast.contains("empty"), "toast was {toast:?}");
        assert!(
            !app.panes
                .iter()
                .any(|p| matches!(p, crate::pane::Pane::Files(_))),
            "opened a pane on an empty trash"
        );
    }
}