mnml-rs 0.2.13

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
//! The `.test` end-to-end format + its runner. A `.test` file is a line-based
//! script of **steps** (drive the editor) and **expectations** (assert on the
//! rendered screen / app state), run against the same `App` + `ui::draw` the real
//! terminal and headless mode use — just with a `TestBackend` and synthesized key
//! events instead of crossterm. `mnml test <path…>` runs them; `tests/e2e.rs`
//! runs `tests/e2e/**/*.test` under `cargo test`.
//!
//! Grammar (one statement per line; `#`-comments and blank lines ignored):
//! ```text
//! write <relpath> <content>      # seed a fixture file in the temp workspace ("\n" → newline)
//! open  <relpath>                # open it in an editor pane (focuses the pane)
//! key   <keyspec>                # send a key — "ctrl+s", "enter", "down", "esc", "a", …
//! type  <text>                   # type literal text, char by char ("\n" → Enter)
//! command <id>                   # run a registered command by id
//! wait  <ms>                     # sleep + tick (for async/pty steps)
//! snippet <scope> <trig> <expansion>  # seed a [snippets.<scope>] entry on app.config
//! shell <cmd>                    # run `<cmd>` via $SHELL -c in workspace (non-zero exit fails)
//! ghost <text>                   # inject an AI ghost-text suggestion on the active editor
//! click <x> <y>                  # left-click at screen cell (x,y) — 0-based
//! rightclick <x> <y>             # right-click (opens context menus)
//! doubleclick <x> <y>            # double-click (row activation in list panes)
//! scroll <x> <y> <up|down>       # mouse wheel at (x,y)
//! expect screen contains <text>  # the rendered virtual screen contains the substring
//! expect screen lacks <text>     # …does not
//! expect dirty <true|false>      # the active editor's dirty flag
//! expect pane <text>             # the active pane's title contains the substring
//! expect file <relpath> contains <text>  # the file at <relpath> (workspace-rel) contains it
//! expect file <relpath> lacks <text>     # …does not
//! ```
//! `<text>` may be wrapped in `"…"` (one layer stripped); inside it `\n` `\t` `\\`
//! `\"` are unescaped.

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

use ratatui::Terminal;
use ratatui::backend::TestBackend;
use ratatui::crossterm::event::{
    KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind,
};

use crate::app::App;
use crate::config::Config;

const SCREEN_W: u16 = 120;
const SCREEN_H: u16 = 40;

#[derive(Debug, Clone)]
enum Step {
    Write {
        rel: String,
        content: String,
    },
    Open(String),
    Key(KeyEvent),
    Type(String),
    Command(String),
    /// Run an ex command via `App::run_ex_command` — `ex bd!` runs `:bd!`.
    Ex(String),
    Wait(u64),
    Snippet {
        scope: String,
        trigger: String,
        expansion: String,
    },
    /// Run `<cmd>` via `$SHELL -c` (POSIX) / `bash -c` via Git Bash
    /// (Windows) in the workspace tempdir. Non-zero exit fails the test
    /// with stderr in the message. Useful for fixture setup that mnml
    /// itself can't do — `git init`, creating non-text files, etc.
    Shell(String),
    /// Inject an AI ghost-text suggestion onto the active editor — the
    /// real suggestion path is a worker thread (API / local model) that
    /// can't run deterministically in a test, so this seeds the state
    /// directly to exercise the accept/dismiss key handling.
    Ghost(String),
    /// A mouse interaction at `(x, y)` (0-based screen cells), dispatched
    /// through `tui::dispatch_mouse` — the same path the real event loop
    /// uses. Covers clicks, right-clicks, double-clicks, and wheel.
    Mouse {
        x: u16,
        y: u16,
        action: MouseAction,
    },
    /// A left-button drag: `Down` at `(from_x, from_y)`, then a
    /// Bresenham-style sequence of intermediate `Drag` events to
    /// `(to_x, to_y)`, then `Up`. Mirrors the IPC `drag` command's
    /// path so .test scripts can exercise drag-select / scrollbar
    /// drag / tab reorder.
    Drag {
        from_x: u16,
        from_y: u16,
        to_x: u16,
        to_y: u16,
    },
}

/// What a `Step::Mouse` does at its `(x, y)`.
#[derive(Debug, Clone, Copy)]
enum MouseAction {
    Click,
    RightClick,
    DoubleClick,
    ScrollUp,
    ScrollDown,
}

#[derive(Debug, Clone)]
enum Check {
    ScreenContains(String),
    ScreenLacks(String),
    Dirty(bool),
    PaneTitle(String),
    /// On-disk check — the file at `rel` (relative to the workspace) contains
    /// the given substring. Useful for save-path tests where the rendered
    /// screen wouldn't show the result.
    FileContains {
        rel: String,
        text: String,
    },
    /// On-disk check — the file at `rel` does **not** contain the substring.
    FileLacks {
        rel: String,
        text: String,
    },
    /// Active editor's `highlights` field has at least `min` non-trivial
    /// spans summed across all lines. Catches regressions where syntax
    /// highlighting silently breaks (e.g. a grammar's queries fail to
    /// compile and we end up emitting zero spans).
    HighlightsAtLeast {
        min: usize,
    },
}

#[derive(Debug, Clone)]
enum Stmt {
    Step(Step),
    Check(Check),
}

/// A `(line_number_1based, parsed_statement)`.
type Line = (usize, Stmt);

/// Result of running one `.test` file.
pub struct TestOutcome {
    pub name: String,
    pub passed: bool,
    /// `Some` with a human-readable reason when `!passed`.
    pub message: Option<String>,
}

/// Parse `.test` source into statements (with their 1-based line numbers).
fn parse(text: &str) -> Result<Vec<Line>, String> {
    let mut out = Vec::new();
    for (i, raw) in text.lines().enumerate() {
        let ln = i + 1;
        let line = raw.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let (head, rest) = split1(line);
        let stmt = match head {
            "write" => {
                let (rel, content) = split1(rest);
                if rel.is_empty() {
                    return Err(format!("line {ln}: `write` needs a path"));
                }
                Stmt::Step(Step::Write {
                    rel: rel.to_string(),
                    content: unescape(content.trim()),
                })
            }
            "open" => {
                if rest.is_empty() {
                    return Err(format!("line {ln}: `open` needs a path"));
                }
                Stmt::Step(Step::Open(rest.trim().to_string()))
            }
            "key" => {
                let spec = rest.trim();
                let ev = crate::input::keymap::parse_key_spec(spec)
                    .ok_or_else(|| format!("line {ln}: unrecognised key spec `{spec}`"))?;
                Stmt::Step(Step::Key(ev))
            }
            "type" => Stmt::Step(Step::Type(unescape(rest))),
            "command" => {
                if rest.is_empty() {
                    return Err(format!("line {ln}: `command` needs an id"));
                }
                Stmt::Step(Step::Command(rest.trim().to_string()))
            }
            "ex" => {
                if rest.is_empty() {
                    return Err(format!("line {ln}: `ex` needs an ex command"));
                }
                Stmt::Step(Step::Ex(rest.trim().to_string()))
            }
            "wait" => {
                let ms = rest
                    .trim()
                    .parse::<u64>()
                    .map_err(|_| format!("line {ln}: `wait` needs a millisecond count"))?;
                Stmt::Step(Step::Wait(ms))
            }
            "snippet" => {
                let (scope, rest1) = split1(rest);
                let (trigger, expansion) = split1(rest1);
                if scope.is_empty() || trigger.is_empty() {
                    return Err(format!(
                        "line {ln}: `snippet` needs <scope> <trigger> <expansion>"
                    ));
                }
                Stmt::Step(Step::Snippet {
                    scope: scope.to_string(),
                    trigger: trigger.to_string(),
                    expansion: unescape(expansion),
                })
            }
            "shell" => {
                let cmd = rest.trim();
                if cmd.is_empty() {
                    return Err(format!("line {ln}: `shell` needs a command"));
                }
                Stmt::Step(Step::Shell(cmd.to_string()))
            }
            "ghost" => {
                let text = unescape(rest);
                if text.is_empty() {
                    return Err(format!("line {ln}: `ghost` needs suggestion text"));
                }
                Stmt::Step(Step::Ghost(text))
            }
            "click" | "rightclick" | "doubleclick" | "scroll" => {
                let (x, y, rest2) = parse_xy(ln, head, rest)?;
                let action = match head {
                    "click" => MouseAction::Click,
                    "rightclick" => MouseAction::RightClick,
                    "doubleclick" => MouseAction::DoubleClick,
                    _ => match rest2.trim() {
                        "up" => MouseAction::ScrollUp,
                        "down" => MouseAction::ScrollDown,
                        _ => {
                            return Err(format!("line {ln}: `scroll X Y <up|down>`"));
                        }
                    },
                };
                Stmt::Step(Step::Mouse { x, y, action })
            }
            "drag" => {
                // Form: `drag FROM_X FROM_Y TO_X TO_Y`.
                let (from_x, from_y, r1) = parse_xy(ln, "drag", rest)?;
                let (to_x, to_y, _r2) = parse_xy(ln, "drag", &r1)?;
                Stmt::Step(Step::Drag {
                    from_x,
                    from_y,
                    to_x,
                    to_y,
                })
            }
            "expect" => parse_expect(ln, rest)?,
            other => return Err(format!("line {ln}: unknown statement `{other}`")),
        };
        out.push((ln, stmt));
    }
    Ok(out)
}

fn parse_expect(ln: usize, rest: &str) -> Result<Stmt, String> {
    let (what, arg) = split1(rest);
    let c = match what {
        "screen" => {
            let (op, text) = split1(arg);
            match op {
                "contains" => Check::ScreenContains(unescape(text)),
                "lacks" => Check::ScreenLacks(unescape(text)),
                _ => return Err(format!("line {ln}: expect screen <contains|lacks> …")),
            }
        }
        "dirty" => match arg.trim() {
            "true" => Check::Dirty(true),
            "false" => Check::Dirty(false),
            _ => return Err(format!("line {ln}: expect dirty <true|false>")),
        },
        "pane" => Check::PaneTitle(unescape(arg)),
        "highlights" => {
            // `expect highlights at_least <N>` — total spans across all
            // lines of the active editor must be ≥ N.
            let (op, num) = split1(arg);
            match op {
                "at_least" => {
                    let min: usize = num
                        .trim()
                        .parse()
                        .map_err(|_| format!("line {ln}: expect highlights at_least <usize>"))?;
                    Check::HighlightsAtLeast { min }
                }
                _ => return Err(format!("line {ln}: expect highlights at_least <N>")),
            }
        }
        "file" => {
            // `expect file <relpath> <contains|lacks> <text>`
            let (rel, rest1) = split1(arg);
            if rel.is_empty() {
                return Err(format!("line {ln}: expect file needs a path"));
            }
            let (op, text) = split1(rest1);
            match op {
                "contains" => Check::FileContains {
                    rel: rel.to_string(),
                    text: unescape(text),
                },
                "lacks" => Check::FileLacks {
                    rel: rel.to_string(),
                    text: unescape(text),
                },
                _ => return Err(format!("line {ln}: expect file <path> <contains|lacks> …")),
            }
        }
        _ => return Err(format!("line {ln}: unknown expectation `{what}`")),
    };
    Ok(Stmt::Check(c))
}

/// Split off the first whitespace-delimited token; return `(token, rest_trimmed_left)`.
fn split1(s: &str) -> (&str, &str) {
    let s = s.trim_start();
    match s.find(char::is_whitespace) {
        Some(i) => (&s[..i], s[i..].trim_start()),
        None => (s, ""),
    }
}

/// Parse a leading `X Y` cell-coordinate pair off `rest`; return
/// `(x, y, remainder)`. Used by the mouse statements.
fn parse_xy(ln: usize, kw: &str, rest: &str) -> Result<(u16, u16, String), String> {
    let (xs, r1) = split1(rest);
    let (ys, r2) = split1(r1);
    let coord_err = || format!("line {ln}: `{kw}` needs `X Y` cell coordinates");
    let x = xs.parse::<u16>().map_err(|_| coord_err())?;
    let y = ys.parse::<u16>().map_err(|_| coord_err())?;
    Ok((x, y, r2.to_string()))
}

/// Strip one optional layer of `"…"` and unescape `\n \t \\ \"`.
fn unescape(s: &str) -> String {
    let s = s.trim();
    let inner = if s.len() >= 2 && s.starts_with('"') && s.ends_with('"') {
        &s[1..s.len() - 1]
    } else {
        s
    };
    let mut out = String::with_capacity(inner.len());
    let mut chars = inner.chars();
    while let Some(c) = chars.next() {
        if c == '\\' {
            match chars.next() {
                Some('n') => out.push('\n'),
                Some('t') => out.push('\t'),
                Some('\\') => out.push('\\'),
                Some('"') => out.push('"'),
                Some(other) => {
                    out.push('\\');
                    out.push(other);
                }
                None => out.push('\\'),
            }
        } else {
            out.push(c);
        }
    }
    out
}

/// Locate a real Git-for-Windows bash on Windows. Plain `bash` on
/// windows-latest resolves to `C:\Windows\System32\bash.exe` — the
/// WSL launcher, not a POSIX shell — and every `.test` `shell:` step
/// dies with "WSL has no installed distributions". Prefer the
/// Git Bash install path (Git for Windows is preinstalled on GH
/// runners + a very common dev install). Env override wins for
/// MSYS2 / Cygwin users. Returns `None` when nothing plausible was
/// found so the caller can surface an actionable error instead of
/// silently reproducing the WSL-launcher bug.
#[cfg(windows)]
fn git_bash_path() -> Option<String> {
    if let Ok(explicit) = std::env::var("MNML_BASH") {
        return Some(explicit);
    }
    for candidate in [
        r"C:\Program Files\Git\bin\bash.exe",
        r"C:\Program Files\Git\usr\bin\bash.exe",
        r"C:\Program Files (x86)\Git\bin\bash.exe",
        r"C:\Program Files (x86)\Git\usr\bin\bash.exe",
    ] {
        if std::path::Path::new(candidate).exists() {
            return Some(candidate.to_string());
        }
    }
    None
}

/// Run one `.test` file. Never panics — a parse error / IO error / failed
/// expectation all come back as `TestOutcome { passed: false, .. }`.
pub fn run_test(path: &Path) -> TestOutcome {
    let name = path
        .file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_else(|| path.display().to_string());
    let fail = |msg: String| TestOutcome {
        name: name.clone(),
        passed: false,
        message: Some(msg),
    };

    let text = match std::fs::read_to_string(path) {
        Ok(t) => t,
        Err(e) => return fail(format!("can't read: {e}")),
    };
    let stmts = match parse(&text) {
        Ok(s) => s,
        Err(e) => return fail(e),
    };
    let dir = match tempfile::tempdir() {
        Ok(d) => d,
        Err(e) => return fail(format!("tempdir: {e}")),
    };
    let workspace = dir.path().to_path_buf();
    // E2E tests assume minimal chrome: row 0 = palette, row 1 = bufferline,
    // rows 2..N = editor body. The breadcrumb row (default-on 2026-08-14)
    // shifts everything down by 1 and breaks all mouse coordinate math in
    // the .test files. Force it off so tests stay legible + coordinate math
    // stays stable.
    let mut cfg = Config::default();
    cfg.editor.breadcrumb = false;
    let mut app = match App::new(workspace.clone(), cfg) {
        Ok(a) => a,
        Err(e) => return fail(format!("App::new: {e}")),
    };
    let mut term = match Terminal::new(TestBackend::new(SCREEN_W, SCREEN_H)) {
        Ok(t) => t,
        Err(e) => return fail(format!("TestBackend: {e}")),
    };

    macro_rules! render {
        () => {{
            // Async ops (git loader, lsp client, ai chat, chord-chain
            // timeout fallback) need a tick to drain after their
            // queueing step. Today's loader-thread refactor turned
            // operations that used to be synchronous (e.g. `git blame`)
            // into channel round-trips, so one tick + a 50ms sleep
            // (enough for a small-repo `git` to complete in worst-case
            // CI under load) + another tick to drain catches the
            // common case without bloating the suite.
            app.tick();
            std::thread::sleep(Duration::from_millis(50));
            // Force-expire any in-flight chord-chain pending and
            // fire the fallback. Real users get 1 second to type the
            // next chord; tests don't simulate that wait — when the
            // .test stops sending keys, the fallback should fire
            // immediately so the assertion can observe the popup.
            if !app.pending_chord_seq.is_empty() {
                app.pending_chord_deadline =
                    Some(std::time::Instant::now() - std::time::Duration::from_millis(1));
                crate::tui::tick_chord_chain(&mut app);
            }
            app.tick();
            if let Err(e) = term.draw(|f| crate::ui::draw(f, &mut app)) {
                return fail(format!("render: {e}"));
            }
        }};
    }
    render!();

    for (ln, stmt) in &stmts {
        match stmt {
            Stmt::Step(step) => {
                if let Err(e) = run_step(&mut app, &workspace, step) {
                    return fail(format!("line {ln}: {e}"));
                }
                render!();
            }
            Stmt::Check(check) => {
                // qa-sweep 2026-06-29: expect-poll with bounded
                // retry. The Step::Wait fix earlier (ticks app
                // every 25ms during sleep) addressed the root
                // cause — async work didn't progress during a
                // bare wait. But macOS CI under load can STILL
                // lag a frame or two between the last `type` and
                // the screen reflecting the result (highlights
                // idle gate is 120ms; if the harness's 50ms
                // render sleep doesn't catch it, the expect runs
                // before the screen settles). Polling for up to
                // 3000ms on FAILURE absorbs that residual jitter.
                // Successful checks pass immediately — no slowdown.
                // Bumped from 750 → 3000 on 2026-07-11 after the
                // snippet-expand tests kept flaking through
                // multiple `wait <ms>` bumps in the callsites.
                let deadline = std::time::Instant::now() + std::time::Duration::from_millis(3000);
                let last_err: Option<String> = loop {
                    let screen = screen_text(term.backend().buffer());
                    match run_check(&app, &screen, check) {
                        Ok(()) => break None,
                        Err(e) => {
                            if std::time::Instant::now() >= deadline {
                                break Some(e);
                            }
                            app.tick();
                            std::thread::sleep(std::time::Duration::from_millis(40));
                            if let Err(re) = term.draw(|f| crate::ui::draw(f, &mut app)) {
                                return fail(format!("render: {re}"));
                            }
                        }
                    }
                };
                if let Some(e) = last_err {
                    return fail(format!("line {ln}: {e}"));
                }
            }
        }
    }

    TestOutcome {
        name,
        passed: true,
        message: None,
    }
}

fn run_step(app: &mut App, workspace: &Path, step: &Step) -> Result<(), String> {
    // `.test` script paths must be workspace-relative. Without this
    // guard, `write /etc/passwd "..."` would land verbatim because
    // `Path::join` short-circuits on absolute input. Same hazard for
    // `open` and any other future fs-touching step. Untouched-
    // surfaces hunt SEV-2 (2026-06-08).
    let reject_unsafe_path = |rel: &str, kw: &str| -> Result<(), String> {
        let p = std::path::Path::new(rel);
        if p.is_absolute() {
            return Err(format!("{kw} {rel}: absolute paths are not allowed"));
        }
        if p.components()
            .any(|c| matches!(c, std::path::Component::ParentDir))
        {
            return Err(format!(
                "{kw} {rel}: `..` components are not allowed (would escape workspace)"
            ));
        }
        Ok(())
    };
    match step {
        Step::Write { rel, content } => {
            reject_unsafe_path(rel, "write")?;
            let p = workspace.join(rel);
            if let Some(parent) = p.parent() {
                std::fs::create_dir_all(parent).map_err(|e| format!("mkdir: {e}"))?;
            }
            std::fs::write(&p, content).map_err(|e| format!("write {rel}: {e}"))
        }
        Step::Open(rel) => {
            reject_unsafe_path(rel, "open")?;
            // `App::open_path` is the explicit-open path — pinned by
            // default. (The tree-click preview behavior lives on
            // `open_path_preview` and is only invoked by the tree
            // click handler.) So no extra `is_preview = false` cleanup
            // is needed here.
            app.open_path(&workspace.join(rel));
            Ok(())
        }
        Step::Key(ev) => {
            crate::tui::dispatch_key(app, *ev);
            Ok(())
        }
        Step::Type(s) => {
            for c in s.chars() {
                let ev = if c == '\n' {
                    KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)
                } else {
                    KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE)
                };
                crate::tui::dispatch_key(app, ev);
            }
            Ok(())
        }
        Step::Command(id) => {
            if crate::command::run(id, app) {
                Ok(())
            } else {
                Err(format!("no such command `{id}`"))
            }
        }
        Step::Ex(cmd) => {
            app.run_ex_command(cmd);
            Ok(())
        }
        Step::Wait(ms) => {
            // qa-sweep 2026-06-29: Wait used to be a bare sleep, so
            // async work (highlights-idle 120ms gate, LSP, snippet
            // edits_consumed counter, git loader thread) didn't
            // advance DURING the wait. Tests that needed a real
            // settle-time had to bump the literal `wait <ms>`
            // value, and the macOS CI flake recurred. Now tick the
            // app every ~25ms throughout the sleep so async ops
            // make progress while time passes — same wall-clock,
            // useful work.
            let deadline = std::time::Instant::now() + Duration::from_millis(*ms);
            while std::time::Instant::now() < deadline {
                app.tick();
                let remaining = deadline.saturating_duration_since(std::time::Instant::now());
                std::thread::sleep(remaining.min(Duration::from_millis(25)));
            }
            // Final tick after the deadline so any work queued by
            // the last sleep gets drained before the next step.
            app.tick();
            Ok(())
        }
        Step::Snippet {
            scope,
            trigger,
            expansion,
        } => {
            app.config
                .snippets
                .entry(scope.clone())
                .or_default()
                .insert(trigger.clone(), expansion.clone());
            Ok(())
        }
        Step::Shell(cmd) => {
            // SECURITY: `shell <cmd>` runs arbitrary shell in the user's
            // account in the workspace cwd. Default-deny: a cloned
            // untrusted repo with `tests/e2e/*.test` + `cargo test`
            // discovery (`tests/e2e.rs`) would otherwise be arbitrary
            // RCE on the user's machine.
            //
            // Opt-in via `MNML_E2E_ALLOW_SHELL=1`. Real CI / the project's
            // own `cargo test` runs already set this. For ad-hoc local
            // exploration the user adds it explicitly:
            //   MNML_E2E_ALLOW_SHELL=1 cargo test --test e2e
            // untouched-surfaces-hunt-2026-06-08 SEV-2 #5.
            if std::env::var("MNML_E2E_ALLOW_SHELL").as_deref() != Ok("1") {
                return Err(format!(
                    "shell `{cmd}`: refused. .test `shell` steps run unsandboxed; \
                     set MNML_E2E_ALLOW_SHELL=1 to opt in (only for trusted repos)."
                ));
            }
            // POSIX shells go through `$SHELL -c`; Windows uses Git Bash
            // (see below). Workspace is cwd so paths in `<cmd>` resolve
            // naturally.
            //
            // Windows uses Git Bash, not `cmd /C` — .test scripts are
            // written in Unix shell syntax (`mkdir -p`, pipes, `sort`)
            // which `cmd` can't parse. Plain `bash` on Windows resolves
            // to `C:\Windows\System32\bash.exe`, which is the WSL
            // launcher — WSL isn't installed on `windows-latest` runners
            // so every shell step dies with "WSL has no installed
            // distributions". Point at the Git-for-Windows bash directly.
            #[cfg(windows)]
            let bash = git_bash_path().ok_or_else(|| {
                format!(
                    "shell `{cmd}`: no Git-for-Windows bash found at the usual \
                     install paths. Install Git for Windows or set \
                     MNML_BASH=<path to bash.exe>. (Plain `bash` on Windows \
                     resolves to the WSL launcher, which won't work here.)"
                )
            })?;
            #[cfg(windows)]
            let mut shell = std::process::Command::new(bash);
            #[cfg(windows)]
            shell.args(["-c", cmd]);
            #[cfg(not(windows))]
            let shell_path = std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string());
            #[cfg(not(windows))]
            let mut shell = std::process::Command::new(shell_path);
            #[cfg(not(windows))]
            shell.args(["-c", cmd]);
            let out = shell
                .current_dir(workspace)
                .output()
                .map_err(|e| format!("shell spawn: {e}"))?;
            if !out.status.success() {
                let stderr = String::from_utf8_lossy(&out.stderr);
                let stdout = String::from_utf8_lossy(&out.stdout);
                return Err(format!(
                    "shell `{cmd}` exited {}: {}{}",
                    out.status,
                    stderr.trim(),
                    if stderr.trim().is_empty() {
                        stdout.trim().to_string()
                    } else {
                        String::new()
                    }
                ));
            }
            Ok(())
        }
        Step::Ghost(text) => match app.active.and_then(|i| app.panes.get_mut(i)) {
            Some(crate::pane::Pane::Editor(b)) => {
                b.editor.ghost_suggestion = Some(text.clone());
                Ok(())
            }
            _ => Err("ghost: no active editor pane".to_string()),
        },
        Step::Mouse { x, y, action } => {
            let ev = |kind| MouseEvent {
                kind,
                column: *x,
                row: *y,
                modifiers: KeyModifiers::NONE,
            };
            let mut click = |btn| {
                crate::tui::dispatch_mouse(app, ev(MouseEventKind::Down(btn)));
                crate::tui::dispatch_mouse(app, ev(MouseEventKind::Up(btn)));
            };
            match action {
                MouseAction::Click => click(MouseButton::Left),
                MouseAction::RightClick => click(MouseButton::Right),
                MouseAction::DoubleClick => {
                    click(MouseButton::Left);
                    click(MouseButton::Left);
                }
                MouseAction::ScrollUp => {
                    crate::tui::dispatch_mouse(app, ev(MouseEventKind::ScrollUp));
                }
                MouseAction::ScrollDown => {
                    crate::tui::dispatch_mouse(app, ev(MouseEventKind::ScrollDown));
                }
            }
            Ok(())
        }
        Step::Drag {
            from_x,
            from_y,
            to_x,
            to_y,
        } => {
            // Same path as the IPC `drag` command in `src/ipc/mod.rs`:
            // Down at source, Bresenham-style interpolated `Drag`
            // events ~1 per cell, Up at destination.
            let ev = |kind, col, row| MouseEvent {
                kind,
                column: col,
                row,
                modifiers: KeyModifiers::NONE,
            };
            crate::tui::dispatch_mouse(
                app,
                ev(MouseEventKind::Down(MouseButton::Left), *from_x, *from_y),
            );
            let steps = (to_x.abs_diff(*from_x)).max(to_y.abs_diff(*from_y)) as usize;
            for s in 1..=steps {
                let t = s as f32 / steps as f32;
                let cx = (*from_x as f32 + (*to_x as f32 - *from_x as f32) * t).round() as u16;
                let cy = (*from_y as f32 + (*to_y as f32 - *from_y as f32) * t).round() as u16;
                crate::tui::dispatch_mouse(
                    app,
                    ev(MouseEventKind::Drag(MouseButton::Left), cx, cy),
                );
            }
            crate::tui::dispatch_mouse(
                app,
                ev(MouseEventKind::Up(MouseButton::Left), *to_x, *to_y),
            );
            Ok(())
        }
    }
}

fn run_check(app: &App, screen: &str, check: &Check) -> Result<(), String> {
    match check {
        Check::ScreenContains(t) => {
            if screen.contains(t.as_str()) {
                Ok(())
            } else {
                Err(format!(
                    "screen does not contain {t:?}\n── rendered screen ──\n{screen}"
                ))
            }
        }
        Check::ScreenLacks(t) => {
            if screen.contains(t.as_str()) {
                Err(format!(
                    "screen unexpectedly contains {t:?}\n── rendered screen ──\n{screen}"
                ))
            } else {
                Ok(())
            }
        }
        Check::Dirty(want) => {
            let got = matches!(app.active_pane(), Some(crate::pane::Pane::Editor(b)) if b.dirty);
            if got == *want {
                Ok(())
            } else {
                Err(format!("active editor dirty == {got}, expected {want}"))
            }
        }
        Check::PaneTitle(t) => match app.active_pane() {
            Some(p) if p.title().contains(t.as_str()) => Ok(()),
            Some(p) => Err(format!(
                "active pane title {:?} does not contain {t:?}",
                p.title()
            )),
            None => Err(format!(
                "no active pane (expected one whose title contains {t:?})"
            )),
        },
        Check::FileContains { rel, text } => {
            let path = app.workspace.join(rel);
            let body = std::fs::read_to_string(&path)
                .map_err(|e| format!("can't read {}: {e}", path.display()))?;
            if body.contains(text.as_str()) {
                Ok(())
            } else {
                // Show the actual content (up to 200 chars) so
                // debugging is a one-shot rather than requiring a
                // second run with a `shell` step.
                let preview: String = body.chars().take(200).collect();
                Err(format!(
                    "file {rel} does not contain {text:?}\n    actual: {preview:?}"
                ))
            }
        }
        Check::FileLacks { rel, text } => {
            let path = app.workspace.join(rel);
            let body = std::fs::read_to_string(&path)
                .map_err(|e| format!("can't read {}: {e}", path.display()))?;
            if body.contains(text.as_str()) {
                Err(format!("file {rel} unexpectedly contains {text:?}"))
            } else {
                Ok(())
            }
        }
        Check::HighlightsAtLeast { min } => {
            let count = match app.active_pane() {
                Some(crate::pane::Pane::Editor(b)) => {
                    b.highlights.iter().map(|line| line.len()).sum::<usize>()
                }
                _ => {
                    return Err("expect highlights: no active editor pane".to_string());
                }
            };
            if count >= *min {
                Ok(())
            } else {
                Err(format!(
                    "expected ≥ {min} highlight spans, got {count} (highlighting may be broken)"
                ))
            }
        }
    }
}

/// Flatten a `TestBackend` buffer to text (rows joined by `\n`, no trailing one).
fn screen_text(buf: &ratatui::buffer::Buffer) -> String {
    let area = buf.area;
    let mut s =
        String::with_capacity(area.width as usize * area.height as usize + area.height as usize);
    for y in 0..area.height {
        for x in 0..area.width {
            s.push_str(buf[(x, y)].symbol());
        }
        if y + 1 < area.height {
            s.push('\n');
        }
    }
    s
}

/// Run every `*.test` under `root` (recursively), or `root` itself if it's a file.
/// Returns `(outcomes, all_passed)`.
///
/// Each file runs on its own worker thread guarded by a 120-second
/// deadline (override via `MNML_E2E_FILE_TIMEOUT_SECS`). If a test
/// hangs — e.g. a Windows `bash -c` subprocess that never returns —
/// the worker is abandoned, a failing outcome is synthesized, and
/// the suite continues instead of blocking the whole CI job. Each
/// file's name is printed before it runs so `--nocapture` reveals
/// which file was in flight when a hang or panic occurred.
pub fn run_path(root: &Path) -> (Vec<TestOutcome>, bool) {
    let mut files: Vec<PathBuf> = Vec::new();
    if root.is_file() {
        files.push(root.to_path_buf());
    } else {
        for entry in ignore::WalkBuilder::new(root).build().flatten() {
            let p = entry.path();
            if p.is_file() && p.extension().is_some_and(|e| e == "test") {
                files.push(p.to_path_buf());
            }
        }
    }
    files.sort();

    // Network opt-in gate (#1042). A `.test` file whose top-of-file
    // comment block contains `# requires: network` is skipped unless
    // MNML_E2E_NETWORK=1. Reason: CI runners (especially GH Actions
    // macOS) drop external HTTPS often enough that a single httpbin
    // fetch flakes the whole suite. Devs running the full suite
    // locally can `MNML_E2E_NETWORK=1 cargo test`; project CI sets
    // this in the workflow when we want it. See MNML_E2E_ALLOW_SHELL
    // (same idiom, different resource).
    let network_ok = std::env::var("MNML_E2E_NETWORK").as_deref() == Ok("1");
    if !network_ok {
        files.retain(|p| {
            if requires_network(p) {
                println!("⊘ e2e SKIP (network opt-in): {}", p.display());
                false
            } else {
                true
            }
        });
    }
    let per_file_timeout = std::env::var("MNML_E2E_FILE_TIMEOUT_SECS")
        .ok()
        .and_then(|v| v.parse::<u64>().ok())
        .map(Duration::from_secs)
        .unwrap_or_else(|| Duration::from_secs(120));
    let outcomes: Vec<TestOutcome> = files
        .iter()
        .map(|p| run_test_with_timeout(p, per_file_timeout))
        .collect();
    let all_passed = outcomes.iter().all(|o| o.passed);
    (outcomes, all_passed)
}

/// True when `path`'s top-of-file comment block declares the test
/// as requiring external network access. Format:
///
/// ```text
/// # requires: network
/// # (rest of file)
/// ```
///
/// Only lines before the first non-comment, non-blank line are
/// consulted — the marker MUST be in the file header, not buried
/// mid-script. See #1042 for context.
fn requires_network(path: &Path) -> bool {
    let Ok(text) = std::fs::read_to_string(path) else {
        return false;
    };
    for line in text.lines() {
        let trimmed = line.trim();
        if trimmed.is_empty() {
            continue;
        }
        if !trimmed.starts_with('#') {
            // First real statement — header block ended.
            return false;
        }
        // Compare after stripping `#` + any whitespace.
        let after_hash = trimmed.trim_start_matches('#').trim();
        if after_hash.eq_ignore_ascii_case("requires: network") {
            return true;
        }
    }
    false
}

/// Wrap [`run_test`] with a hard wall-clock deadline. On timeout the
/// worker thread is abandoned (Rust has no safe way to cancel it) and
/// a synthesized failing outcome is returned so the surrounding suite
/// can keep going. The abandoned thread will die with the process.
fn run_test_with_timeout(path: &Path, timeout: Duration) -> TestOutcome {
    let name = path
        .file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_else(|| path.display().to_string());
    println!("▶ e2e: {name}");
    let owned = path.to_path_buf();
    let (tx, rx) = std::sync::mpsc::channel();
    std::thread::spawn(move || {
        let outcome = run_test(&owned);
        let _ = tx.send(outcome);
    });
    match rx.recv_timeout(timeout) {
        Ok(outcome) => outcome,
        Err(_) => TestOutcome {
            name,
            passed: false,
            message: Some(format!(
                "TIMEOUT after {}s (worker abandoned — a step never returned; \
                 override via MNML_E2E_FILE_TIMEOUT_SECS)",
                timeout.as_secs()
            )),
        },
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_a_basic_script() {
        let src = "\
# a comment
write foo.txt hello
open foo.txt
type \" world\"
key ctrl+s
expect screen contains \"hello world\"
expect dirty false
";
        let stmts = parse(src).unwrap();
        assert_eq!(stmts.len(), 6);
        assert!(matches!(stmts[0].1, Stmt::Step(Step::Write { .. })));
        assert!(matches!(stmts[3].1, Stmt::Step(Step::Key(_))));
        assert!(matches!(stmts[5].1, Stmt::Check(Check::Dirty(false))));
    }

    #[test]
    fn unescape_strips_quotes_and_escapes() {
        assert_eq!(unescape(r#""a\nb""#), "a\nb");
        assert_eq!(unescape("plain"), "plain");
        assert_eq!(unescape(r#""tab\there""#), "tab\there");
    }

    #[test]
    fn rejects_bad_key_spec() {
        assert!(parse("key ctrl+nope+x").is_err());
    }

    #[test]
    fn parses_shell_step() {
        let stmts = parse("shell echo hi\n").unwrap();
        match &stmts[0].1 {
            Stmt::Step(Step::Shell(cmd)) => assert_eq!(cmd, "echo hi"),
            other => panic!("expected Shell, got {other:?}"),
        }
    }

    #[test]
    fn rejects_empty_shell_command() {
        assert!(parse("shell   \n").is_err());
    }

    #[test]
    fn parses_ghost_step() {
        let stmts = parse("ghost \"a + b\"\n").unwrap();
        match &stmts[0].1 {
            Stmt::Step(Step::Ghost(text)) => assert_eq!(text, "a + b"),
            other => panic!("expected Ghost, got {other:?}"),
        }
        assert!(parse("ghost   \n").is_err());
    }

    #[test]
    fn parses_mouse_steps() {
        let stmts =
            parse("click 12 5\nrightclick 3 1\ndoubleclick 8 8\nscroll 40 20 down\n").unwrap();
        assert!(matches!(
            stmts[0].1,
            Stmt::Step(Step::Mouse {
                x: 12,
                y: 5,
                action: MouseAction::Click
            })
        ));
        assert!(matches!(
            stmts[1].1,
            Stmt::Step(Step::Mouse {
                action: MouseAction::RightClick,
                ..
            })
        ));
        assert!(matches!(
            stmts[2].1,
            Stmt::Step(Step::Mouse {
                action: MouseAction::DoubleClick,
                ..
            })
        ));
        assert!(matches!(
            stmts[3].1,
            Stmt::Step(Step::Mouse {
                x: 40,
                y: 20,
                action: MouseAction::ScrollDown
            })
        ));
        // Non-numeric coords + a bad scroll direction are rejected.
        assert!(parse("click x y\n").is_err());
        assert!(parse("scroll 1 2 sideways\n").is_err());
    }

    #[test]
    fn runs_a_tiny_edit_script() {
        // Exercise the full pipeline without a .test file on disk.
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("t.test");
        std::fs::write(
            &file,
            "\
write hello.txt seedtext
open hello.txt
expect screen contains seedtext
expect dirty false
type ZZZ
expect dirty true
expect screen contains ZZZseedtext
",
        )
        .unwrap();
        let o = run_test(&file);
        assert!(o.passed, "{:?}", o.message);
    }
}