rustimal 0.8.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
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
//! Headless tests that start a real Git Bash the way a pane does, with the shell
//! integration, and type into it. They need Git for Windows and take a few seconds each,
//! so they only run on request: `cargo test pty -- --ignored --nocapture`.

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use alacritty_terminal::event::{Event, EventListener, WindowSize};
use alacritty_terminal::event_loop::{EventLoop, EventLoopSender, Msg};
use alacritty_terminal::grid::Dimensions;
use alacritty_terminal::index::Line;
use alacritty_terminal::sync::FairMutex;
use alacritty_terminal::term::{Config as TermConfig, Term};
use alacritty_terminal::tty::{self, Options, Shell};

use crate::config::Config;
use crate::terminal::editing::{self, Move};
use crate::terminal::inject::{Injector, Outcome};
use crate::terminal::links::Target;
use crate::terminal::pane::GridSize;
use crate::terminal::prompt::{awaiting_more, command_line, cursor_at_prompt, show_selection, typed_text};
use crate::terminal::search::row_chars;

/// Answers the terminal's own queries (cursor position and so on), like a pane does.
#[derive(Clone, Default)]
struct Replies(Arc<Mutex<Option<EventLoopSender>>>, Arc<Mutex<Vec<String>>>);

impl EventListener for Replies {
    fn send_event(&self, event: Event) {
        if let Event::Title(title) = &event {
            self.1.lock().unwrap().push(title.clone());
        }
        if let Event::PtyWrite(s) = event
            && let Some(sender) = self.0.lock().unwrap().as_ref()
        {
            let _ = sender.send(Msg::Input(s.into_bytes().into()));
        }
    }
}

struct Session {
    titles: Arc<Mutex<Vec<String>>>,
    term: Arc<FairMutex<Term<Replies>>>,
    sender: EventLoopSender,
}

impl Session {
    fn start(dir: &Path) -> Self {
        let config = Config::default();
        let (program, args) = config.shell_program();
        let mut env: HashMap<String, String> = [
            ("TERM", "xterm-256color"),
            ("COLORTERM", "truecolor"),
            ("TERM_PROGRAM", "rustimal"),
            ("CHERE_INVOKING", "1"),
        ]
        .into_iter()
        .map(|(k, v)| (k.to_string(), v.to_string()))
        .collect();
        for (k, v) in crate::platform::winenv::fresh() {
            env.entry(k).or_insert(v);
        }
        env.extend(config.shell_env());
        env.insert("RUSTIMAL_PANE".into(), format!("test-{}", std::process::id()));
        env.insert("RUSTIMAL_REVIEW_TOKEN".into(), "tok".into());
        let opts = Options {
            shell: Some(Shell::new(program, args)),
            working_directory: Some(dir.to_path_buf()),
            drain_on_exit: false,
            env,
            escape_args: true,
        };
        let grid = GridSize { cols: 100, rows: 30 };
        let size = WindowSize { num_lines: 30, num_cols: 100, cell_width: 9, cell_height: 20 };
        let replies = Replies::default();
        let pty = tty::new(&opts, size, 1).expect("start Git Bash");
        let term = Arc::new(FairMutex::new(Term::new(TermConfig::default(), &grid, replies.clone())));
        let event_loop = EventLoop::new(term.clone(), replies.clone(), pty, false, false).expect("event loop");
        let sender = event_loop.channel();
        *replies.0.lock().unwrap() = Some(sender.clone());
        let _ = event_loop.spawn();
        Self { titles: replies.1, term, sender }
    }

    fn send(&self, bytes: &[u8]) {
        let _ = self.sender.send(Msg::Input(bytes.to_vec().into()));
    }

    fn at_prompt(&self) -> bool {
        cursor_at_prompt(&self.term.lock())
    }

    fn screen(&self) -> String {
        let term = self.term.lock();
        let mut out = String::new();
        for line in term.topmost_line().0..=term.bottommost_line().0 {
            let text: String = row_chars(&term, Line(line)).iter().map(|&(_, c, _)| c).collect();
            let text = text.trim_end();
            if !text.is_empty() {
                out.push_str(text);
                out.push('\n');
            }
        }
        out
    }

    fn wait_until(&self, what: &str, secs: u64, done: impl Fn(&Session) -> bool) {
        let start = Instant::now();
        while !done(self) {
            assert!(
                start.elapsed() < Duration::from_secs(secs),
                "timed out waiting for {what}; screen:\n{}",
                self.screen()
            );
            std::thread::sleep(Duration::from_millis(5));
        }
    }
}

impl Drop for Session {
    fn drop(&mut self) {
        let _ = self.sender.send(Msg::Shutdown);
    }
}

/// Start a session and resize it the way a window settling at startup does.
fn noisy_session(dir: &Path) -> Session {
    let session = Session::start(dir);
    for (after_ms, cols, rows) in [(150, 103, 28), (350, 129, 36), (700, 127, 33)] {
        std::thread::sleep(Duration::from_millis(after_ms));
        session.term.lock().resize(GridSize { cols, rows });
        let size = WindowSize { num_lines: rows as u16, num_cols: cols as u16, cell_width: 9, cell_height: 20 };
        let _ = session.sender.send(Msg::Resize(size));
    }
    session
}

/// Drive an `Injector` against the session until it finishes, like a pane does every frame.
fn inject(session: &Session, cmd: &str) -> Outcome {
    let mut injector = Injector::new(cmd.to_string(), Some(Target::Path(PathBuf::from("unused"))), Instant::now());
    loop {
        let (writes, outcome) = injector.tick(&session.term.lock(), Instant::now());
        for bytes in writes {
            session.send(&bytes);
        }
        if outcome != Outcome::Pending {
            return outcome;
        }
        std::thread::sleep(Duration::from_millis(10));
    }
}

/// Click `name` in `dir` right after startup. Returns whether the command ran exactly as typed.
fn click_scenario(label: &str, dir: &Path, name: &str, ls_first: bool) -> bool {
    let session = noisy_session(dir);
    session.wait_until("the first prompt", 30, |s| s.at_prompt());
    if ls_first {
        assert_eq!(inject(&session, "ls"), Outcome::Done);
        session.wait_until("ls to finish", 30, |s| s.screen().contains(name) && s.at_prompt());
    }
    let cmd = crate::terminal::links::entry_command(&dir.join(name), name).expect("a folder");
    let outcome = inject(&session, &cmd);
    // Wait for the command to run and the next prompt (in the new folder) to appear.
    session.wait_until(&format!("{cmd:?} to finish"), 30, |s| {
        s.at_prompt() && s.screen().trim_end().lines().last().is_some_and(|l| l.contains(name))
    });
    std::thread::sleep(Duration::from_millis(200));
    let screen = session.screen();
    let ok = outcome == Outcome::Done
        && screen.contains(&format!("\u{276f} {cmd}"))
        && !screen.contains("command not found");
    println!("{} {label} (dir {}, ls first: {ls_first}, {outcome:?})", if ok { "ok  " } else { "FAIL" }, dir.display());
    if !ok {
        println!("{screen}");
    }
    ok
}

#[test]
#[ignore]
fn clicking_a_folder_types_the_whole_command() {
    let repo = std::env::current_dir().unwrap();
    let home = dirs::home_dir().unwrap();
    let root = PathBuf::from("C:\\");
    let mut failures = Vec::new();
    // Typing straight after a noisy startup lost characters in about a third of runs, so
    // repeat the scenarios until a repeat of the old way would almost surely have failed.
    for round in 0..3 {
        for (label, dir, name, ls_first) in [
            ("repo: first click at start", &repo, "src", false),
            ("repo: click after ls", &repo, "src", true),
            ("home: first click at start", &home, "Music", false),
            ("home: click after ls", &home, "Music", true),
            ("drive root: first click at start", &root, "Users", false),
        ] {
            if !click_scenario(&format!("{label} #{round}"), dir, name, ls_first) {
                failures.push(label);
            }
        }
    }
    assert!(failures.is_empty(), "clicks that went wrong: {failures:?}");
}

/// The case behind the bug: while a command runs, and before its prompt is back, the app
/// must not consider the shell ready, or text typed for it gets lost.
#[test]
#[ignore]
fn no_prompt_while_a_command_runs_or_text_is_typed() {
    let session = Session::start(&std::env::current_dir().unwrap());
    session.wait_until("the first prompt", 30, |s| s.at_prompt());

    session.send(b"sleep 3\r");
    std::thread::sleep(Duration::from_millis(100));
    for _ in 0..8 {
        assert!(!session.at_prompt(), "a command is running; screen:\n{}", session.screen());
        std::thread::sleep(Duration::from_millis(200));
    }
    session.wait_until("the prompt after sleep", 20, |s| s.at_prompt());

    session.send(b"abc");
    session.wait_until("typed text to show", 10, |s| s.screen().contains("abc"));
    assert!(!session.at_prompt(), "something is typed on the line; screen:\n{}", session.screen());
}

/// A long completion list paused at `--More--` swallows what is typed. The injector must
/// dismiss it first.
#[test]
#[ignore]
fn a_click_dismisses_a_paused_listing_first() {
    let home = dirs::home_dir().unwrap();
    let session = Session::start(&home);
    session.wait_until("the first prompt", 30, |s| s.at_prompt());
    // Page long completion lists (the shell integration turns this off), then list the folder.
    assert_eq!(inject(&session, "bind 'set page-completions on'"), Outcome::Done);
    session.wait_until("the prompt", 20, |s| s.at_prompt());
    session.send(b"\t\t");
    session.wait_until("--More--", 20, |s| awaiting_more(&s.term.lock()));
    assert!(!session.at_prompt());

    let cmd = crate::terminal::links::entry_command(&home.join("Music"), "Music").expect("a folder");
    assert_eq!(inject(&session, &cmd), Outcome::Done, "screen:\n{}", session.screen());
    session.wait_until("the command to finish", 30, |s| {
        s.at_prompt() && s.screen().trim_end().lines().last().is_some_and(|l| l.contains("Music"))
    });
    let screen = session.screen();
    assert!(screen.contains(&format!("\u{276f} {cmd}")), "screen:\n{screen}");
    assert!(!screen.contains("command not found"), "screen:\n{screen}");
}

/// Typing just a name: a folder is entered and listed, a text file printed, a program run, and
/// a real command always wins over a file or folder of the same name.
#[test]
#[ignore]
fn typing_a_bare_name_does_the_obvious_thing() {
    let dir = std::env::temp_dir().join(format!("rustimal-names-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    for sub in ["sub", "echo", "weird name"] {
        std::fs::create_dir_all(dir.join(sub)).unwrap();
    }
    std::fs::write(dir.join("sub").join("inner_file.txt"), "inner\n").unwrap();
    std::fs::write(dir.join("weird name").join("in_weird.txt"), "w\n").unwrap();
    std::fs::write(dir.join("notes.txt"), "the notes say hello\n").unwrap();
    std::fs::write(dir.join("hello.sh"), "#!/bin/bash\necho hello from the script\n").unwrap();
    std::fs::write(dir.join("echo").join("not_listed.txt"), "x\n").unwrap();

    let session = Session::start(&dir);
    session.wait_until("the first prompt", 30, |s| s.at_prompt());
    let here = dir.file_name().unwrap().to_string_lossy().into_owned();

    // Type `line`, then wait until the prompt is back and `expect` is on screen.
    let run = |line: &str, expect: &str| {
        assert_eq!(inject(&session, line), Outcome::Done, "typing {line:?}");
        session.wait_until(&format!("{line:?} to show {expect:?}"), 30, |s| {
            s.at_prompt()
                && s.screen().rsplit_once(&format!("\u{276f} {line}")).is_some_and(|(_, after)| after.contains(expect))
        });
    };
    let last_prompt = |session: &Session| session.screen().trim_end().lines().last().unwrap_or("").to_string();

    run("sub", "inner_file.txt");
    assert!(last_prompt(&session).contains("/sub"), "should be inside sub: {}", last_prompt(&session));

    run("..", "notes.txt");
    assert!(
        last_prompt(&session).contains(&here) && !last_prompt(&session).contains("/sub"),
        "{}",
        last_prompt(&session)
    );

    run("notes.txt", "the notes say hello");
    run("hello.sh", "hello from the script");

    // A folder named like a command: the command wins, nothing is entered.
    run("echo", "\u{276f}");
    assert!(!last_prompt(&session).contains("/echo"), "echo is a command: {}", last_prompt(&session));

    run("'weird name'", "in_weird.txt");
    assert!(last_prompt(&session).contains("weird name"), "{}", last_prompt(&session));
    run("..", "notes.txt");

    // No such command, folder or file.
    run("no_such_thing", "command not found");

    let _ = std::fs::remove_dir_all(&dir);
}

/// Type text at the prompt without pressing Enter, checking it arrived (input can be lost
/// right after startup) and trying again if not.
fn type_text(session: &Session, text: &str) {
    for _ in 0..4 {
        session.send(text.as_bytes());
        let start = Instant::now();
        while start.elapsed() < Duration::from_millis(1200) {
            if typed_text(&session.term.lock()).as_deref() == Some(text) {
                return;
            }
            std::thread::sleep(Duration::from_millis(10));
        }
        session.send(&[0x05, 0x15]); // clear the line and try again
        std::thread::sleep(Duration::from_millis(200));
    }
    panic!("could not type {text:?}; screen:\n{}", session.screen());
}

/// The whole command line, not just the part before the cursor.
fn command_text(session: &Session) -> String {
    command_line(&session.term.lock()).map(|cl| cl.text()).unwrap_or_default()
}

fn wait_command(session: &Session, expected: &str) {
    session.wait_until(&format!("the command line to be {expected:?}"), 10, |s| command_text(s) == expected);
}

/// The keys behind Shift+arrows, Ctrl+Shift+arrows, Ctrl+A and typing over a selection, run
/// against a real readline: select by word or all, delete or replace it, and see the line.
#[test]
#[ignore]
fn selecting_and_replacing_on_the_command_line_works_in_a_real_shell() {
    let session = Session::start(&std::env::current_dir().unwrap());
    session.wait_until("the first prompt", 30, |s| s.at_prompt());
    std::thread::sleep(Duration::from_millis(400));

    // Select the last word (Ctrl+Shift+Left) and replace it by typing.
    type_text(&session, "alpha beta gamma");
    let cl = command_line(&session.term.lock()).unwrap();
    let chars = cl.chars();
    let to = editing::target(&chars, cl.cursor, Move::WordLeft);
    assert_eq!((cl.cursor, to), (16, 11));
    session.send(&editing::move_keys(cl.cursor, to, false));
    show_selection(&mut session.term.lock(), &cl, to, cl.cursor);
    assert_eq!(session.term.lock().selection_to_string().as_deref(), Some("gamma"));
    session.send(&editing::delete_keys(to, cl.cursor, to, false));
    wait_command(&session, "alpha beta ");
    session.send(b"delta");
    wait_command(&session, "alpha beta delta");

    // Select from the middle to the start (Shift+Home) and delete it: the cursor was moved
    // back into the line first.
    let cl = command_line(&session.term.lock()).unwrap();
    let mid = 6; // before "beta"
    session.send(&editing::move_keys(cl.cursor, mid, false));
    std::thread::sleep(Duration::from_millis(150));
    let cl = command_line(&session.term.lock()).unwrap();
    assert_eq!(cl.cursor, mid, "the shell's cursor followed the keys");
    session.send(&editing::delete_keys(0, mid, cl.cursor, false));
    wait_command(&session, "beta delta");

    // Select all (Ctrl+A) and delete it.
    let cl = command_line(&session.term.lock()).unwrap();
    let n = cl.cells.len();
    session.send(&editing::move_keys(cl.cursor, n, false));
    show_selection(&mut session.term.lock(), &cl, 0, n);
    assert_eq!(session.term.lock().selection_to_string().as_deref(), Some("beta delta"));
    session.send(&editing::delete_keys(0, n, n, false));
    wait_command(&session, "");

    // Words stop at separators: select "src" then "/" then "main" of a path, going right.
    type_text(&session, "cat src/main.rs");
    let cl = command_line(&session.term.lock()).unwrap();
    let chars = cl.chars();
    let mut at = 0;
    let mut stops = Vec::new();
    for _ in 0..4 {
        at = editing::target(&chars, at, Move::WordRight);
        stops.push(at);
    }
    assert_eq!(stops, vec![3, 7, 8, 12], "cat, src, /, main");
    session.send(&[0x05, 0x15]);
    wait_command(&session, "");
}

/// `review` and `pr` ask the window to open the panel; any other use of `pr` is coreutils'.
#[test]
#[ignore]
fn review_and_pr_ask_for_the_panel() {
    let session = Session::start(&std::env::current_dir().unwrap());
    session.wait_until("the first prompt", 30, |s| s.at_prompt());
    let request = |s: &Session| {
        s.titles.lock().unwrap().iter().find_map(|t| t.strip_prefix("__rustimal_review__:tok:").map(str::to_string))
    };
    // Repeated, because a request lost between two titles shows up only now and then.
    for round in 0..3 {
        for (typed, args) in [
            ("review", ""),
            ("review demo", "demo"),
            ("review --uncommitted", "--uncommitted"),
            ("pr", ""),
            ("pr 12", "#12"),
            ("pr '#7'", "#7"),
            ("pr new", "--new"),
            ("pr new topic", "--new topic"),
        ] {
            session.titles.lock().unwrap().clear();
            session.send(format!("{typed}\r").as_bytes());
            session.wait_until(&format!("{typed} #{round}"), 15, |s| request(s).is_some());
            let asked = request(&session).unwrap();
            let (dir, given) = asked.split_once('|').expect("a folder and arguments");
            assert!(dir.starts_with('/') && dir.ends_with("rustimal"), "{dir}");
            assert_eq!(given, args, "{typed}");
            // The window's answer; the next prompt follows it.
            session.send(b"\r");
            session.wait_until("the prompt after the answer", 2, |s| s.at_prompt());
        }
    }
    assert!(!session.screen().contains("did not answer"), "{}", session.screen());

    // With no answer it gives up and says so.
    session.send(b"pr\r");
    session.wait_until("giving up", 10, |s| s.screen().contains("did not answer") && s.at_prompt());

    session.titles.lock().unwrap().clear();
    session.send(b"pr -t -l 1000 Cargo.toml | head -n 1\r");
    session.wait_until("coreutils pr", 15, |s| s.screen().lines().any(|l| l.starts_with("[package]")) && s.at_prompt());
    assert!(request(&session).is_none());
}

/// `do` is a reserved word, so Enter rewrites a line starting with it, and only that.
#[test]
#[ignore]
fn pty_do_is_handed_to_rustimal_and_loops_still_work() {
    let s = Session::start(&std::env::temp_dir());
    s.wait_until("prompt", 30, |s| s.at_prompt());
    let step = |line: &str| {
        s.send(line.as_bytes());
        std::thread::sleep(Duration::from_millis(700));
    };
    let asked = || {
        s.titles
            .lock()
            .unwrap()
            .iter()
            .filter_map(|t| t.strip_prefix("__rustimal_do__:tok:").map(str::to_string))
            .collect::<Vec<_>>()
    };
    let task_file = crate::config::state_dir().unwrap().join(format!("do-test-{}.txt", std::process::id()));

    step("do why doesn't \"this\" work? (see $HOME & `x`)\r");
    s.wait_until("the request", 10, |_| asked().len() == 1);
    assert!(asked()[0].ends_with("|claude"), "{:?}", asked());
    assert_eq!(std::fs::read_to_string(&task_file).unwrap(), "why doesn't \"this\" work? (see $HOME & `x`)");
    // The app answers with Enter once it has the task.
    step("\r");

    step("do -x árvíztűrő\r");
    s.wait_until("the second request", 10, |_| asked().len() == 2);
    assert!(asked()[1].ends_with("|codex"), "{:?}", asked());
    assert_eq!(std::fs::read_to_string(&task_file).unwrap(), "árvíztűrő");
    step("\r");

    step("do\r");
    s.wait_until("a bare do", 10, |_| asked().len() == 3);
    assert_eq!(std::fs::read_to_string(&task_file).unwrap(), "");
    step("\r");
    let _ = std::fs::remove_file(&task_file);

    step("for i in 1 2\r");
    step("do echo loop-$i\r");
    step("done\r");
    s.wait_until("the loop", 10, |s| s.screen().contains("loop-2"));
    step("for i in 3\r");
    step("do\r");
    step("echo bare-$i; done\r");
    s.wait_until("a loop with do on its own line", 10, |s| s.screen().contains("bare-3"));
    // A loop dropped with Ctrl+C doesn't disarm the next `do`.
    step("while true\r");
    step("\x03");
    step("do after\r");
    s.wait_until("do after Ctrl+C", 10, |_| asked().len() == 4);
    step("\r");
    let _ = std::fs::remove_file(&task_file);
    assert_eq!(asked().len(), 4, "the loops asked for nothing:\n{}", s.screen());
    // rustimal hears which command was typed, not what the Enter key or Ctrl+C ran. (It
    // has to last a moment: the console drops a title that another one follows at once.)
    step("sleep 0.4\r");
    let ran: Vec<String> = s
        .titles
        .lock()
        .unwrap()
        .iter()
        .filter_map(|t| t.strip_prefix("__rustimal_cmd__:").map(str::to_string))
        .collect();
    assert!(ran.iter().any(|c| c.starts_with("sleep")), "{ran:?}");
    assert!(!ran.iter().any(|c| c.starts_with("__rustimal_")), "{ran:?}");
}

/// `vscode` asks about the license before anything else, and then it and `open` hand text
/// files to rustimal. Uses a state folder of its own, so nothing is accepted for real.
#[test]
#[ignore]
fn pty_vscode_asks_first_and_then_hands_files_to_rustimal() {
    let state = std::env::temp_dir().join(format!("rustimal-code-test-{}", std::process::id()));
    std::fs::create_dir_all(&state).unwrap();
    let s = Session::start(&std::env::current_dir().unwrap());
    s.wait_until("prompt", 30, |s| s.at_prompt());
    let step = |line: &str| {
        s.send(line.as_bytes());
        std::thread::sleep(Duration::from_millis(900));
    };
    let asked = || {
        let titles = s.titles.lock().unwrap();
        titles.iter().filter_map(|t| t.strip_prefix("__rustimal_code__:tok:").map(str::to_string)).collect::<Vec<_>>()
    };
    let request = state.join(format!("code-test-{}.txt", std::process::id()));
    let read = || std::fs::read_to_string(&request).unwrap_or_default().replace(std::path::MAIN_SEPARATOR, "/");
    step(&format!("RUSTIMAL_STATE=$(cygpath -u '{}')\r", state.display()));

    step("vscode .\r");
    s.wait_until("the license question", 10, |s| s.screen().contains("Do you accept them? [y/N]"));
    assert!(s.screen().contains("https://aka.ms/vscode-server-license"), "{}", s.screen());
    step("\r");
    s.wait_until("no is the default", 10, |s| s.screen().contains("Not accepted"));
    assert!(asked().is_empty() && !state.join("vscode-license-accepted").exists());

    step("vscode Cargo.toml:3:2\r");
    step("y\r");
    s.wait_until("the first request", 10, |_| asked().len() == 1);
    assert!(asked()[0].ends_with("|vscode"), "{:?}", asked());
    assert!(read().ends_with("/Cargo.toml\n3:2\n"), "{}", read());
    step("\r");
    assert!(state.join("vscode-license-accepted").exists(), "remembered");

    step("vscode\r");
    s.wait_until("no argument is this folder", 10, |_| asked().len() == 2);
    assert!(read().trim_end().ends_with("rustimal"), "{}", read());
    step("\r");

    step("open README.md\r");
    s.wait_until("open a text file", 10, |_| asked().len() == 3);
    assert!(asked()[2].ends_with("|open") && read().ends_with("/README.md\n\n"), "{}", read());
    step("\r");

    step("open src/main.rs:5\r");
    s.wait_until("open at a line", 10, |_| asked().len() == 4);
    assert!(read().ends_with("/src/main.rs\n5\n"), "{}", read());
    step("\r");

    step("vscode no-such-thing\r");
    s.wait_until("a missing file", 10, |s| s.screen().contains("no such file or folder"));
    assert_eq!(asked().len(), 4);
    let _ = std::fs::remove_dir_all(&state);
}

/// `browser`, `zen`, `search` and `embed` tell rustimal which shell to look below for the
/// window, and wait to be answered. They run the program out of the way and give the prompt
/// back at once (`embed -f` waits for it); when rustimal says the browser is already in the
/// pane, the page is handed to it.
#[test]
#[ignore]
fn pty_embed_asks_rustimal_and_then_runs_the_command() {
    let dir = std::env::temp_dir().join(format!("rustimal-embed-test-{}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    let log = dir.join("ran.log");
    let log_for_bash = log.display().to_string().replace('\\', "/");
    let fake = dir.join("fake-rustimal.sh");
    let script = format!(
        "#!/bin/bash\necho \"RAN:$*\" >>'{log_for_bash}'\n[ -n \"$FAKE_SLEEP\" ] && sleep \"$FAKE_SLEEP\"\nexit 0\n"
    );
    std::fs::write(&fake, script).unwrap();
    let s = Session::start(&dir);
    s.wait_until("prompt", 30, |s| s.at_prompt());
    let step = |line: &str| {
        s.send(line.as_bytes());
        std::thread::sleep(Duration::from_millis(900));
    };
    let asked = || {
        let titles = s.titles.lock().unwrap();
        titles.iter().filter_map(|t| t.strip_prefix("__rustimal_embed__:tok:").map(str::to_string)).collect::<Vec<_>>()
    };
    let ran = || std::fs::read_to_string(&log).unwrap_or_default();
    step(&format!("RUSTIMAL_EXE=$(cygpath -u '{}')\r", fake.display()));

    step("search rust window embedding\r");
    s.wait_until("the first request", 10, |_| asked().len() == 1);
    let request = &asked()[0];
    let (_, args) = request.split_once('|').unwrap();
    let pid = args.strip_prefix("start:").and_then(|a| a.strip_suffix(":browser")).expect(request);
    assert!(pid.parse::<u32>().is_ok_and(|p| p > 0), "{request}");
    // Not run until rustimal has answered.
    assert!(ran().is_empty(), "{}", ran());
    step("\r");
    s.wait_until("the command", 10, |_| ran().contains("RAN:--browser --search rust window embedding"));
    s.wait_until("the prompt", 10, |s| s.at_prompt());

    // The browser keeps running and the prompt is back at once: the shell is not held up.
    step("export FAKE_SLEEP=8\r");
    let before = asked().len();
    step("zen localhost:3000\r");
    s.wait_until("a request", 10, |_| asked().len() == before + 1);
    step("\r");
    s.wait_until("the command", 10, |_| ran().contains("RAN:--browser localhost:3000"));
    s.wait_until("the prompt back while the browser runs", 4, |s| s.at_prompt());
    step("unset FAKE_SLEEP\r");

    // Rustimal says the browser is already there: the page goes to that one.
    let before = asked().len();
    step("zen asd\r");
    s.wait_until("a request", 10, |_| asked().len() == before + 1);
    s.send(b"reuse\r");
    s.wait_until("the page handed over", 10, |_| ran().contains("RAN:--browser --reuse asd"));
    s.wait_until("the prompt", 10, |s| s.at_prompt());

    // Fork is asked for the same way, as a program of its own kind, and reused the same way.
    let before = asked().len();
    step("fork\r");
    s.wait_until("a request", 10, |_| asked().len() == before + 1);
    assert!(asked()[before].ends_with(":fork"), "{:?}", asked());
    step("\r");
    s.wait_until("the command", 10, |_| ran().lines().any(|l| l == "RAN:--fork"));
    step("fork some-folder\r");
    s.wait_until("a request", 10, |_| asked().len() == before + 2);
    s.send(b"reuse\r");
    s.wait_until("the folder handed over", 10, |_| ran().contains("RAN:--fork --reuse some-folder"));
    s.wait_until("the prompt", 10, |s| s.at_prompt());

    let requests = asked().len();
    step("search\r");
    s.wait_until("usage", 10, |s| s.screen().contains("usage: search TERMS"));
    step("embed\r");
    s.wait_until("usage", 10, |s| s.screen().contains("usage: embed [-f] COMMAND"));
    assert_eq!(asked().len(), requests, "nothing is asked for when nothing is run");

    // `embed` gives the prompt back too, and says where the output went...
    step("embed echo quiet-output\r");
    s.wait_until("a request", 10, |_| asked().len() == requests + 1);
    step("\r");
    s.wait_until("the note", 10, |s| s.screen().contains("running in the background"));
    s.wait_until("the prompt", 10, |s| s.at_prompt());
    assert_eq!(s.screen().matches("quiet-output").count(), 1, "only the typed command: {}", s.screen());
    // ... unless it is told to wait, and then its output is here.
    step("embed -f echo hello world\r");
    s.wait_until("a request", 10, |_| asked().len() == requests + 2);
    step("\r");
    s.wait_until("the command", 10, |s| s.screen().contains("hello world"));
    let _ = std::fs::remove_dir_all(&dir);
}

/// What `ls` prints for names with spaces and apostrophes is all clickable, however the
/// quotes fall, and clicking a folder with a space in its name types the whole command.
#[test]
#[ignore]
fn names_with_spaces_are_links_and_clicks() {
    use alacritty_terminal::index::{Column, Line, Point};
    let dir = std::env::temp_dir().join(format!("rustimal-spaces-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    for folder in ["my folder", "plain", "it's here"] {
        std::fs::create_dir_all(dir.join(folder)).unwrap();
    }
    std::fs::write(dir.join("a b.txt"), "x").unwrap();
    std::fs::write(dir.join("c.txt"), "x").unwrap();
    let session = noisy_session(&dir);
    session.wait_until("the first prompt", 30, |s| s.at_prompt());
    assert_eq!(inject(&session, "ls"), Outcome::Done);
    session.wait_until("ls", 30, |s| s.screen().contains("plain") && s.at_prompt());
    let mut found = Vec::new();
    {
        let term = session.term.lock();
        for line in 0..term.screen_lines() as i32 {
            for column in 0..term.columns() {
                let at = Point::new(Line(line), Column(column));
                if let Some(link) = crate::terminal::links::find(&term, at, Some(&dir))
                    && let crate::terminal::links::Target::Entry { name, .. } = link.target
                    && !found.contains(&name)
                {
                    found.push(name);
                }
            }
        }
    }
    found.sort();
    assert_eq!(found, ["a b.txt", "c.txt", "it's here", "my folder", "plain"], "{}", session.screen());
    drop(session);
    for (name, ls_first) in [("my folder", false), ("my folder", true), ("it's here", true)] {
        assert!(click_scenario(&format!("spaced {name}"), &dir, name, ls_first), "{name}");
    }
    let _ = std::fs::remove_dir_all(&dir);
}

/// Typing a folder's name changes into it and lists it, the way the person's own `ls` does:
/// with the markers and colors of their alias, not a plain listing.
#[test]
#[ignore]
fn pty_a_folder_name_lists_it_like_the_users_ls() {
    use alacritty_terminal::index::{Column, Line};
    use alacritty_terminal::vte::ansi::{Color, NamedColor};
    let dir = std::env::temp_dir().join(format!("rustimal-autocd-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(dir.join("sub").join("inner")).unwrap();
    std::fs::write(dir.join("sub").join("f.txt"), "x").unwrap();
    let session = Session::start(&dir);
    session.wait_until("the first prompt", 30, |s| s.at_prompt());
    // An alias set up after the shell integration was loaded (a profile may do that late):
    // only an `ls` that is looked up when it runs, not when the prompt hook was read, sees it.
    session.send(b"alias ls='ls -1F --color=auto'\r");
    std::thread::sleep(Duration::from_millis(600));
    session.send(b"sub\r");
    session.wait_until("the listing", 30, |s| s.screen().contains("f.txt") && s.at_prompt());
    std::thread::sleep(Duration::from_millis(400));
    let term = session.term.lock();
    let mut inner = None;
    for line in 0..term.screen_lines() as i32 {
        let text: String = (0..term.columns()).map(|c| term.grid()[Line(line)][Column(c)].c).collect();
        if let Some(at) = text.find("inner") {
            inner = Some(term.grid()[Line(line)][Column(at)].fg);
            assert!(text[at..].starts_with("inner/"), "the -F marker of the alias: {text:?}");
            assert!(!text.contains("f.txt"), "the alias's -1, one name to a line: {text:?}");
        }
    }
    let blue = matches!(inner, Some(Color::Named(NamedColor::Blue | NamedColor::BrightBlue)));
    assert!(blue, "a folder is blue in the listing, not plain: {inner:?}");
    drop(term);
    drop(session);
    let _ = std::fs::remove_dir_all(&dir);
}

/// Tab-Tab lists the choices in color, as `ls` does: a folder blue, not the plain text color.
#[test]
#[ignore]
fn pty_tab_tab_lists_choices_in_color() {
    use alacritty_terminal::index::{Column, Line};
    use alacritty_terminal::vte::ansi::{Color, NamedColor};
    let dir = std::env::temp_dir().join(format!("rustimal-tabtab-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(dir.join("alpha_dir")).unwrap();
    std::fs::write(dir.join("alpha_file.txt"), "x").unwrap();
    let session = Session::start(&dir);
    session.wait_until("the first prompt", 30, |s| s.at_prompt());
    session.send(b"ls alpha_\t");
    std::thread::sleep(Duration::from_millis(500));
    session.send(b"\t");
    session.wait_until("the choices", 30, |s| s.screen().contains("alpha_file.txt"));
    std::thread::sleep(Duration::from_millis(400));
    let term = session.term.lock();
    let mut found = None;
    for line in 0..term.screen_lines() as i32 {
        let text: String = (0..term.columns()).map(|c| term.grid()[Line(line)][Column(c)].c).collect();
        // The list, not the command line being typed.
        if text.contains("alpha_file.txt")
            && !text.contains('\u{276f}')
            && let Some(at) = text.find("alpha_dir")
        {
            // Past the common start the choices share, where the name's own color shows.
            found = Some((text[at..].starts_with("alpha_dir/"), term.grid()[Line(line)][Column(at + 6)].fg));
        }
    }
    let (marked, color) = found.unwrap_or_else(|| panic!("no list on screen: {}", session.screen()));
    assert!(marked, "the / after a folder");
    assert!(matches!(color, Color::Named(NamedColor::Blue | NamedColor::BrightBlue)), "a folder is blue: {color:?}");
    drop(term);
    drop(session);
    let _ = std::fs::remove_dir_all(&dir);
}