mindfork 0.18.3

A terminal AI chat written in Rust: local models via llama.cpp, or OpenAI, Anthropic, Gemini, Grok and OpenRouter in the cloud, with persistent memory, notes, RAG and tools.
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
//! `mindfork keys` — what the app receives for each key, and what the chat's
//! input box does with it (docs/research/macos.md §13.4, fork F7).
//!
//! A terminal decides which chords reach a program at all, and in what form:
//! Terminal.app keeps `Ctrl+←/→` for Spaces and sends Option+← as `ESC b`,
//! Konsole's `Shift+Enter` is a sequence crossterm drops. "The key did nothing"
//! says none of that; the event that arrived does. So the terminal is put into
//! the very modes the app reads keys in ([`runtime::enable_key_modes`]), each
//! event is printed as crossterm reports it, and beside it the outcome — a
//! sketch of an input box that starts every key from the same text, run through
//! the real [`InputBox`] and the chat's own line-break rule.
//!
//! Nothing is created: no data root, no log. `--output` copies the lines into
//! a file, for a session read from elsewhere (macos.md §13.3).

use std::fs::File;
use std::io::{IsTerminal, Write, stdout};
use std::path::Path;
use std::process::ExitCode;

use anyhow::{Context, Result};
#[cfg(unix)]
use ratatui::crossterm::event::PopKeyboardEnhancementFlags;
use ratatui::crossterm::event::{
    DisableBracketedPaste, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEvent,
    KeyModifiers, MouseEvent,
};
use ratatui::crossterm::execute;
use ratatui::crossterm::terminal::{disable_raw_mode, enable_raw_mode};

use crate::app::runtime::{self, Chunk};
use crate::shared::i18n::Locale;
use crate::shared::keys;
use crate::widgets::input_box::{InputBox, KeyOutcome};

/// The text every key starts from, and the cursor's column in it — between two
/// words, so a move by a word and by a character land on different marks.
const SAMPLE: &str = "one two three";
const SAMPLE_CURSOR: usize = 8;

/// Where an echoed line goes: the terminal, raw, and the `--output` file.
struct Echo<W: Write> {
    term: W,
    file: Option<File>,
}

impl<W: Write> Echo<W> {
    /// One line. Raw mode does not turn `\n` into a new line, so the terminal
    /// gets `\r\n`; the file gets plain `\n`.
    fn line(&mut self, text: &str) -> Result<()> {
        write!(self.term, "{text}\r\n")?;
        self.term.flush()?;
        if let Some(file) = &mut self.file {
            writeln!(file, "{text}")?;
        }
        Ok(())
    }
}

/// Restores the terminal however the loop ends — an error included. Turning
/// mouse capture off when it is not on is harmless.
struct Restore;

impl Drop for Restore {
    fn drop(&mut self) {
        let _ = execute!(stdout(), DisableMouseCapture, DisableBracketedPaste);
        #[cfg(unix)]
        let _ = execute!(stdout(), PopKeyboardEnhancementFlags);
        let _ = disable_raw_mode();
    }
}

/// What the echo itself does with an event, beside printing it.
#[derive(Debug, PartialEq, Eq)]
enum Control {
    Go,
    ToggleMouse,
    Quit,
}

/// The app's own quit (`Ctrl+Q`, `F10`) ends the echo too, and its mouse
/// switch (`Ctrl+W`) switches it here; everything else is only shown.
fn control_of(key: &KeyEvent) -> Control {
    if key.code == KeyCode::F(10) {
        return Control::Quit;
    }
    if key.modifiers == KeyModifiers::CONTROL {
        match keys::hotkey_char(key) {
            Some('q') => return Control::Quit,
            Some('w') => return Control::ToggleMouse,
            _ => {}
        }
    }
    Control::Go
}

/// Runs the echo until `Ctrl+Q` or `F10`. A terminal on stdout was checked by
/// the caller (`main`'s launch gate).
pub fn run(output: Option<&Path>, loc: &Locale) -> Result<ExitCode> {
    debug_assert!(stdout().is_terminal());
    let file = output.map(|path| create_record(path, loc)).transpose()?;
    let mut echo = Echo {
        term: stdout(),
        file,
    };
    enable_raw_mode()?;
    let restore = Restore;
    for line in header(loc, runtime::enable_key_modes(), &env_var) {
        echo.line(&line)?;
    }
    echo_loop(runtime::read_batch, set_mouse_capture, &mut echo, loc)?;
    drop(restore);
    if let Some(path) = output {
        println!(
            "{}",
            loc.tf("cli.keys.saved", &[("path", &path.display().to_string())])
        );
    }
    Ok(ExitCode::SUCCESS)
}

/// The `--output` file — a new one: a record of one terminal is not written
/// over by the next one's.
fn create_record(path: &Path, loc: &Locale) -> Result<File> {
    File::create_new(path).with_context(|| {
        loc.tf(
            "cli.keys.cannot_write",
            &[("path", &path.display().to_string())],
        )
    })
}

fn set_mouse_capture(on: bool) -> Result<()> {
    if on {
        execute!(stdout(), EnableMouseCapture)?;
    } else {
        execute!(stdout(), DisableMouseCapture)?;
    }
    Ok(())
}

/// The echo's loop, apart from the terminal: `next` hands out batches as the
/// app reads them, `set_mouse` switches capture, and each piece of a batch is
/// one line. Read as the app reads — a batch at a time, presses only, a burst
/// of text keys taken for one paste (Windows has no bracketed paste) — so the
/// echo shows what the screens are handed, not each key of a paste.
fn echo_loop<W: Write>(
    mut next: impl FnMut() -> Result<Vec<Event>>,
    mut set_mouse: impl FnMut(bool) -> Result<()>,
    echo: &mut Echo<W>,
    loc: &Locale,
) -> Result<()> {
    let mut mouse = false;
    loop {
        for chunk in runtime::chunk_batch(next()?) {
            let control = match &chunk {
                Chunk::Event(Event::Key(key)) => control_of(key),
                _ => Control::Go,
            };
            if control == Control::ToggleMouse {
                mouse = !mouse;
                set_mouse(mouse)?;
            }
            echo.line(&describe(&chunk, &control, mouse, loc))?;
            if control == Control::Quit {
                return Ok(());
            }
        }
    }
}

/// The lines printed before the first key: the terminal, what it answered, and
/// how to read and leave the echo. `env` reads a variable of the environment.
fn header(loc: &Locale, kitty: Option<bool>, env: &dyn Fn(&str) -> Option<String>) -> Vec<String> {
    let kitty = match kitty {
        Some(true) => loc.t("cli.keys.kitty_on"),
        Some(false) => loc.t("cli.keys.kitty_off"),
        None => loc.t("cli.keys.kitty_none"),
    };
    vec![
        loc.tf("cli.keys.title", &[("version", env!("CARGO_PKG_VERSION"))]),
        loc.tf("cli.keys.terminal", &[("terminal", &terminal_facts(env))]),
        kitty.to_string(),
        loc.tf("cli.keys.newline", &[("chord", keys::newline_chord())]),
        loc.tf("cli.keys.sample", &[("sample", &sketch(&sample_box()))]),
        loc.t("cli.keys.controls").to_string(),
        String::new(),
    ]
}

/// A variable of this process's environment, `None` when unset or empty.
fn env_var(name: &str) -> Option<String> {
    std::env::var(name).ok().filter(|value| !value.is_empty())
}

/// The OS and the variables a terminal names itself by — the facts a report
/// needs and a user would not know to give. `WT_SESSION` is named, not shown:
/// its value is a session's id.
fn terminal_facts(env: &dyn Fn(&str) -> Option<String>) -> String {
    let mut facts = vec![std::env::consts::OS.to_string()];
    for name in ["TERM_PROGRAM", "TERM_PROGRAM_VERSION", "TERM", "COLORTERM"] {
        if let Some(value) = env(name) {
            facts.push(format!("{name}={value}"));
        }
    }
    if env("WT_SESSION").is_some() {
        facts.push("WT_SESSION".to_string());
    }
    facts.join(", ")
}

/// One echoed line for a piece of a batch. A key's release never gets here:
/// the batch keeps presses only, as the app's does.
fn describe(chunk: &Chunk, control: &Control, mouse: bool, loc: &Locale) -> String {
    let (label, outcome) = match chunk {
        // A burst of text keys the app takes for one paste (Windows).
        Chunk::Paste(text) => ("Paste (keys)".to_string(), paste_outcome(text, loc)),
        Chunk::Event(Event::Paste(text)) => ("Paste".to_string(), paste_outcome(text, loc)),
        Chunk::Event(Event::Key(key)) => {
            let outcome = match control {
                Control::Quit => loc.t("cli.keys.quit").to_string(),
                Control::ToggleMouse if mouse => loc.t("cli.keys.mouse_on").to_string(),
                Control::ToggleMouse => loc.t("cli.keys.mouse_off").to_string(),
                Control::Go => key_outcome(key, loc),
            };
            (key_label(key), outcome)
        }
        Chunk::Event(Event::Mouse(mouse)) => ("Mouse".to_string(), mouse_outcome(mouse)),
        Chunk::Event(Event::Resize(width, height)) => (
            "Resize".to_string(),
            loc.tf(
                "cli.keys.window",
                &[
                    ("width", &width.to_string()),
                    ("height", &height.to_string()),
                ],
            ),
        ),
        Chunk::Event(other) => (format!("{other:?}"), String::new()),
    };
    format!("{label:<24} → {outcome}").trim_end().to_string()
}

/// A paste's size and its first characters. A paste rebuilt from keys carries
/// `Enter` as `\r`, which the input box turns into a line break as it does `\n`.
fn paste_outcome(text: &str, loc: &Locale) -> String {
    let text = text.replace("\r\n", "\n").replace('\r', "\n");
    loc.tf(
        "cli.keys.paste",
        &[
            ("chars", &text.chars().count().to_string()),
            ("lines", &(text.matches('\n').count() + 1).to_string()),
            ("preview", &preview(&text)),
        ],
    )
}

/// The key as crossterm reported it: the modifiers in a fixed order, then the
/// code — a character quoted and escaped, so a space or a control character is
/// seen for what it is.
fn key_label(key: &KeyEvent) -> String {
    let mut parts: Vec<String> = modifier_names(key.modifiers)
        .into_iter()
        .map(str::to_string)
        .collect();
    parts.push(match key.code {
        KeyCode::Char(c) => format!("'{}'", c.escape_debug()),
        KeyCode::F(n) => format!("F{n}"),
        other => format!("{other:?}"),
    });
    let mut label = parts.join("+");
    for (name, _) in key.state.iter_names() {
        label.push(' ');
        label.push_str(name);
    }
    label
}

/// The modifiers in a fixed order, by the names the app's help uses.
fn modifier_names(modifiers: KeyModifiers) -> Vec<&'static str> {
    [
        (KeyModifiers::CONTROL, "Ctrl"),
        (KeyModifiers::ALT, "Alt"),
        (KeyModifiers::SHIFT, "Shift"),
        (KeyModifiers::SUPER, "Super"),
        (KeyModifiers::HYPER, "Hyper"),
        (KeyModifiers::META, "Meta"),
    ]
    .into_iter()
    .filter(|(flag, _)| modifiers.contains(*flag))
    .map(|(_, name)| name)
    .collect()
}

/// What the chat's input box does with a key, in the order the chat screen
/// asks (`screens::chat::input`): the line break first, then `Enter`, a
/// `Ctrl` shortcut by its physical letter, and the box itself.
fn key_outcome(key: &KeyEvent, loc: &Locale) -> String {
    let mut field = sample_box();
    if keys::is_line_break(key) {
        field.insert_newline();
        return sketch(&field);
    }
    if key.code == KeyCode::Enter {
        return loc.t("cli.keys.send").to_string();
    }
    if key.modifiers.contains(KeyModifiers::CONTROL)
        && !keys::is_altgr_text(key)
        && let Some(physical) = keys::hotkey_char(key)
    {
        let chord = format!("Ctrl+{}", physical.to_ascii_uppercase());
        return loc.tf("cli.keys.shortcut", &[("chord", &chord)]);
    }
    match field.on_key(*key) {
        KeyOutcome::Ignored => loc.t("cli.keys.ignored").to_string(),
        KeyOutcome::Edited | KeyOutcome::Moved => sketch(&field),
    }
}

/// A mouse event as crossterm reported it, at a 1-based cell.
fn mouse_outcome(mouse: &MouseEvent) -> String {
    let mut text = format!("{:?} at {},{}", mouse.kind, mouse.column + 1, mouse.row + 1);
    for name in modifier_names(mouse.modifiers) {
        text.push(' ');
        text.push_str(name);
    }
    text
}

/// The input box every key starts from: [`SAMPLE`], the cursor at
/// [`SAMPLE_CURSOR`].
fn sample_box() -> InputBox {
    let mut field = InputBox::new();
    field.set_text(SAMPLE);
    let left = KeyEvent::new(KeyCode::Left, KeyModifiers::NONE);
    for _ in SAMPLE_CURSOR..SAMPLE.chars().count() {
        field.on_key(left);
    }
    field
}

/// The box's text with its cursor `|`, its selection `«…»` and its line
/// breaks `⏎` — what a key did, without a frame to draw it in.
fn sketch(field: &InputBox) -> String {
    let cursor = field.cursor();
    let selection = field.selection_span();
    let mut out = String::new();
    for (row, line) in field.line_strings().iter().enumerate() {
        if row > 0 {
            out.push('⏎');
        }
        let chars: Vec<char> = line.chars().collect();
        for col in 0..=chars.len() {
            let at = (row, col);
            if selection.is_some_and(|(_, end)| end == at) {
                out.push('»');
            }
            if cursor == at {
                out.push('|');
            }
            if selection.is_some_and(|(start, _)| start == at) {
                out.push('«');
            }
            if let Some(&c) = chars.get(col) {
                out.extend(c.escape_debug());
            }
        }
    }
    out
}

/// The first characters of a paste, escaped, a line break as `⏎`.
fn preview(text: &str) -> String {
    const SHOWN: usize = 40;
    let mut out: String = text
        .chars()
        .take(SHOWN)
        .map(|c| {
            if c == '\n' {
                "⏎".to_string()
            } else {
                c.escape_debug().to_string()
            }
        })
        .collect();
    if text.chars().count() > SHOWN {
        out.push('…');
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::shared::i18n::{Lang, locale};
    use ratatui::crossterm::event::{KeyEventState, MouseButton, MouseEventKind};

    fn en() -> &'static Locale {
        locale(Lang::En)
    }

    fn key(code: KeyCode, modifiers: KeyModifiers) -> KeyEvent {
        KeyEvent::new(code, modifiers)
    }

    fn outcome(code: KeyCode, modifiers: KeyModifiers) -> String {
        key_outcome(&key(code, modifiers), en())
    }

    #[test]
    fn every_key_starts_between_two_words() {
        assert_eq!(sketch(&sample_box()), "one two |three");
    }

    /// The Mac's word motions — Terminal.app's `ESC b`, iTerm2's `Alt+←` — and
    /// the PC's `Ctrl+←` all land on the same mark; a bare `←` moves one
    /// character, so a word move can't be mistaken for it.
    #[test]
    fn a_word_move_and_a_character_move_land_apart() {
        for (code, modifiers) in [
            (KeyCode::Char('b'), KeyModifiers::ALT),
            (KeyCode::Left, KeyModifiers::ALT),
            (KeyCode::Left, KeyModifiers::CONTROL),
        ] {
            assert_eq!(
                outcome(code, modifiers),
                "one |two three",
                "{code:?} {modifiers:?}"
            );
        }
        assert_eq!(outcome(KeyCode::Left, KeyModifiers::NONE), "one two| three");
        assert_eq!(
            outcome(KeyCode::Char('f'), KeyModifiers::ALT),
            "one two three|"
        );
    }

    #[test]
    fn the_three_line_breaks_break_the_line_and_enter_sends() {
        for (code, modifiers) in [
            (KeyCode::Enter, KeyModifiers::SHIFT),
            (KeyCode::Enter, KeyModifiers::ALT),
            (KeyCode::Char('j'), KeyModifiers::CONTROL),
        ] {
            assert_eq!(
                outcome(code, modifiers),
                "one two ⏎|three",
                "{code:?} {modifiers:?}"
            );
        }
        assert_eq!(
            outcome(KeyCode::Enter, KeyModifiers::NONE),
            "sends the message"
        );
    }

    #[test]
    fn typing_deleting_and_selecting_show_in_the_sketch() {
        assert_eq!(
            outcome(KeyCode::Char('x'), KeyModifiers::NONE),
            "one two x|three"
        );
        assert_eq!(outcome(KeyCode::Backspace, KeyModifiers::ALT), "one |three");
        assert_eq!(
            outcome(KeyCode::Backspace, KeyModifiers::NONE),
            "one two|three"
        );
        assert_eq!(
            outcome(KeyCode::Right, KeyModifiers::SHIFT),
            "one two «t»|hree"
        );
        assert_eq!(
            outcome(KeyCode::Left, KeyModifiers::SHIFT),
            "one two|« »three"
        );
        assert_eq!(outcome(KeyCode::Home, KeyModifiers::NONE), "|one two three");
    }

    /// An `Alt`+letter other than a word motion is not typed — the app's rule
    /// since Option chords used to type their letter — and a `Ctrl` chord is
    /// named by the letter the app matched, whatever the layout typed.
    #[test]
    fn shortcuts_and_untyped_chords_say_so() {
        assert_eq!(
            outcome(KeyCode::Char('x'), KeyModifiers::ALT),
            "the input box does nothing with it"
        );
        assert_eq!(
            outcome(KeyCode::Char('l'), KeyModifiers::CONTROL),
            "the shortcut Ctrl+L"
        );
        assert_eq!(
            outcome(KeyCode::F(1), KeyModifiers::NONE),
            "the input box does nothing with it"
        );
    }

    #[test]
    fn the_label_is_the_event_as_crossterm_gave_it() {
        assert_eq!(
            key_label(&key(KeyCode::Char('b'), KeyModifiers::ALT)),
            "Alt+'b'"
        );
        assert_eq!(
            key_label(&key(
                KeyCode::Enter,
                KeyModifiers::SHIFT | KeyModifiers::CONTROL
            )),
            "Ctrl+Shift+Enter"
        );
        assert_eq!(
            key_label(&key(KeyCode::Char(' '), KeyModifiers::NONE)),
            "' '"
        );
        assert_eq!(
            key_label(&key(KeyCode::Char('\u{1}'), KeyModifiers::NONE)),
            "'\\u{1}'"
        );
        assert_eq!(key_label(&key(KeyCode::F(1), KeyModifiers::NONE)), "F1");
        let mut keypad = key(KeyCode::Left, KeyModifiers::NONE);
        keypad.state = KeyEventState::KEYPAD;
        assert_eq!(key_label(&keypad), "Left KEYPAD");
    }

    fn line(event: Event, control: &Control, mouse: bool) -> String {
        describe(&Chunk::Event(event), control, mouse, en())
    }

    #[test]
    fn quit_and_the_mouse_switch_are_the_apps_own_keys() {
        assert_eq!(
            control_of(&key(KeyCode::Char('q'), KeyModifiers::CONTROL)),
            Control::Quit
        );
        assert_eq!(
            control_of(&key(KeyCode::F(10), KeyModifiers::NONE)),
            Control::Quit
        );
        assert_eq!(
            control_of(&key(KeyCode::Char('w'), KeyModifiers::CONTROL)),
            Control::ToggleMouse
        );
        assert_eq!(
            control_of(&key(KeyCode::Char('q'), KeyModifiers::NONE)),
            Control::Go
        );
        assert_eq!(
            control_of(&key(KeyCode::Char('e'), KeyModifiers::CONTROL)),
            Control::Go
        );
        let quit = Event::Key(key(KeyCode::Char('q'), KeyModifiers::CONTROL));
        assert_eq!(
            line(quit, &Control::Quit, false),
            format!("{:<24} → quits", "Ctrl+'q'")
        );
        let switch = Event::Key(key(KeyCode::Char('w'), KeyModifiers::CONTROL));
        assert!(line(switch, &Control::ToggleMouse, true).ends_with("mouse capture on"));
    }

    /// The batch is split as the app splits it: a burst of text keys — a
    /// paste on Windows — is one paste, its `Enter`s line breaks, while one key
    /// alone stays a key.
    #[test]
    fn the_batch_is_split_as_the_app_splits_it() {
        let press = |c| Event::Key(key(KeyCode::Char(c), KeyModifiers::NONE));
        let enter = Event::Key(key(KeyCode::Enter, KeyModifiers::NONE));
        let chunks = runtime::chunk_batch(vec![press('h'), press('i'), enter, press('!')]);
        let lines: Vec<String> = chunks
            .iter()
            .map(|chunk| describe(chunk, &Control::Go, false, en()))
            .collect();
        assert_eq!(lines.len(), 1, "{lines:?}");
        assert!(lines[0].starts_with("Paste (keys)"), "{lines:?}");
        assert!(
            lines[0].contains("characters: 4, lines: 2: hi⏎!"),
            "{lines:?}"
        );
        let one = runtime::chunk_batch(vec![press('x')]);
        assert_eq!(
            describe(&one[0], &Control::Go, false, en()),
            format!("{:<24} → one two x|three", "'x'")
        );
    }

    #[test]
    fn a_paste_a_click_and_a_resize_are_shown() {
        let paste = line(Event::Paste("hi\nthere".into()), &Control::Go, false);
        assert!(paste.starts_with("Paste "), "{paste}");
        assert!(
            paste.contains("characters: 8, lines: 2: hi⏎there"),
            "{paste}"
        );
        let long = preview(&"x".repeat(50));
        assert_eq!(long.chars().count(), 41);
        assert!(long.ends_with('…'));
        let click = Event::Mouse(MouseEvent {
            kind: MouseEventKind::Down(MouseButton::Left),
            column: 4,
            row: 9,
            modifiers: KeyModifiers::SHIFT,
        });
        assert!(line(click, &Control::Go, true).ends_with("Down(Left) at 5,10 Shift"));
        assert!(line(Event::Resize(80, 24), &Control::Go, false).ends_with("80×24"));
        assert_eq!(
            line(Event::FocusGained, &Control::Go, false),
            "FocusGained              →"
        );
    }

    /// No environment at all: the header still names the OS.
    fn no_env(_: &str) -> Option<String> {
        None
    }

    #[test]
    fn the_header_names_the_terminal_and_the_way_out() {
        let lines = header(en(), Some(false), &no_env);
        let text = lines.join("\n");
        assert!(text.contains(std::env::consts::OS), "{text}");
        assert!(text.contains("one two |three"), "{text}");
        assert!(text.contains("Ctrl+Q"), "{text}");
        assert!(text.contains("not answered"), "{text}");
        assert_eq!(lines.last().map(String::as_str), Some(""));
        let answered = header(en(), Some(true), &no_env).join("\n");
        assert!(answered.contains("answered, and turned on"), "{answered}");
        let windows = header(en(), None, &no_env).join("\n");
        assert!(windows.contains("not asked"), "{windows}");
    }

    /// The variables a terminal names itself by, in a fixed order; a Windows
    /// Terminal session is named, its id is not shown.
    #[test]
    fn the_terminal_is_named_by_its_variables() {
        let env = |name: &str| match name {
            "TERM_PROGRAM" => Some("Apple_Terminal".to_string()),
            "TERM_PROGRAM_VERSION" => Some("466".to_string()),
            "TERM" => Some("xterm-256color".to_string()),
            "WT_SESSION" => Some("a-session-id".to_string()),
            _ => None,
        };
        let facts = terminal_facts(&env);
        assert_eq!(
            facts,
            format!(
                "{}, TERM_PROGRAM=Apple_Terminal, TERM_PROGRAM_VERSION=466, \
                 TERM=xterm-256color, WT_SESSION",
                std::env::consts::OS
            )
        );
        assert_eq!(terminal_facts(&no_env), std::env::consts::OS);
    }

    /// The loop, off the terminal: batches in, a line per piece out — on the
    /// terminal with `\r\n`, in the file with `\n` — the mouse switched both
    /// ways, and nothing read after the quit.
    #[test]
    fn the_loop_echoes_each_piece_and_stops_at_the_quit() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("keys.txt");
        let mut echo = Echo {
            term: Vec::new(),
            file: Some(create_record(&path, en()).unwrap()),
        };
        let press = |c| Event::Key(key(KeyCode::Char(c), KeyModifiers::NONE));
        let ctrl = |c| Event::Key(key(KeyCode::Char(c), KeyModifiers::CONTROL));
        let mut batches = std::collections::VecDeque::from(vec![
            vec![press('x')],
            vec![ctrl('w')],
            vec![press('h'), press('i')],
            vec![ctrl('w'), ctrl('q'), press('z')],
        ]);
        let mut switched = Vec::new();
        echo_loop(
            || Ok(batches.pop_front().expect("read after the quit")),
            |on| {
                switched.push(on);
                Ok(())
            },
            &mut echo,
            en(),
        )
        .unwrap();
        assert_eq!(switched, vec![true, false]);
        let term = String::from_utf8(echo.term).unwrap();
        let lines: Vec<&str> = term.split_terminator("\r\n").collect();
        assert_eq!(lines.len(), 5, "{term}");
        assert!(lines[0].ends_with("one two x|three"), "{term}");
        assert!(lines[1].ends_with("mouse capture on"), "{term}");
        assert!(lines[2].starts_with("Paste (keys)"), "{term}");
        assert!(lines[3].ends_with("mouse capture off"), "{term}");
        assert!(lines[4].ends_with("quits"), "{term}");
        drop(echo.file);
        let saved = std::fs::read_to_string(&path).unwrap();
        assert_eq!(saved, format!("{}\n", lines.join("\n")));
    }

    /// The record of one terminal is not written over by the next one's.
    #[test]
    fn an_existing_record_is_refused() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("keys.txt");
        std::fs::write(&path, "Terminal.app\n").unwrap();
        let error = create_record(&path, en()).unwrap_err();
        assert!(format!("{error:#}").contains("Cannot create"), "{error:#}");
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "Terminal.app\n");
    }
}