mnml-rs 0.2.20

A NvChad-style terminal IDE in Rust — vim or standard editing, LSP, git, and an embedded HTTP client.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
//! 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::*;

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}?")
        };
        let mut prompt =
            crate::prompt::Prompt::new(crate::prompt::PromptKind::DeleteConfirm, title);
        // Focus Cancel by default (index 1) — safety first for a
        // destructive action.
        prompt.cursor = 1;
        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) {
        match code {
            crate::ui::prompt::CONFIRM_BTN_PRIMARY => {
                if let Some(FsAction::Delete { path }) = self.pending_fs_action.take() {
                    self.execute_delete_fs_entry(&path);
                }
            }
            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();
            }
        }
    }

    pub fn execute_delete_fs_entry(&mut self, path: &Path) {
        let is_dir = path.is_dir();
        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;
        }
        // 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();
        self.toast(format!(
            "deleted {}{}",
            rel_path(&self.workspace, path),
            if is_dir { "/" } else { "" }
        ));
    }

    /// 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();
            }
        }
    }

    /// 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"
        );
    }
}