tam-cli 0.7.1

Terminal agent multiplexer — manage units of work, not just processes
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
//! `[tui] scroll_mode = "nvim"`: `v` opens a copy of the text of the agent
//! (or shell) the pane shows in nvim, in the pane, until nvim exits (`:q`)
//! or the leave key hangs it up.
//!
//! nvim runs on a PTY the dashboard owns (`tam_daemon::pty::Pty`, as the
//! daemon's agents and shells do), in the dashboard's environment: it never
//! outlives the dashboard, and the daemon knows nothing of it. Its screen is
//! drawn in the pane (`view`, a `Peek` of its own: the mouse selects on it),
//! keys are written to it by a thread of its own, and a task reads its
//! output for what tam's terminal emulator does not do: the clipboard sets
//! (OSC 52) are passed on to the dashboard's terminal, and the queries nvim
//! waits on are answered (see [`Watch`]).

use std::fs::OpenOptions;
use std::io::Write as _;
use std::os::fd::OwnedFd;
use std::os::unix::fs::OpenOptionsExt;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::{mpsc, Arc};

use anyhow::{Context, Result};
use tam_daemon::pty::{self, Pty};
use tokio::sync::{broadcast, mpsc::UnboundedSender, watch};

use super::peek::Peek;

/// `TERM` of the editor: tam's emulator (vt100) draws it, not the
/// dashboard's terminal, which `xterm-kitty` would name.
const TERM: &str = "xterm-256color";

/// What the dashboard answers to nvim's primary device attributes query:
/// a VT220 with colours. nvim asks when it exits and waits a second for
/// the answer.
const DEVICE_ATTRIBUTES: &[u8] = b"\x1b[?62;22c";

/// Lines the wheel scrolls by, with the keys of an editor that asked for
/// no mouse reports.
const WHEEL_LINES: usize = 3;

/// What the editor tells the dashboard (its event loop).
#[derive(Debug, PartialEq, Eq)]
pub enum Event {
    /// Its screen changed: to draw again.
    Changed,
    /// It set the clipboard (OSC 52): the sequence to pass on to the
    /// dashboard's terminal, which does it.
    Clipboard(String),
}

/// Where the copy opens.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Start {
    /// At its last line, at the bottom of the window: the pane was live.
    End,
    /// This line (from 1) on the window's first row: the pane was scrolled
    /// back to it.
    Line(u64),
}

/// The program the copy opens in, and where copies are written.
pub struct Program {
    /// The command, the editor's arguments after it: `nvim` (a test's
    /// stand-in).
    pub argv: Vec<String>,
    /// tam's runtime directory, where the daemon's socket is.
    pub copies: PathBuf,
}

impl Program {
    pub fn nvim() -> Self {
        let socket = tam_proto::default_socket_path();
        Self {
            argv: vec!["nvim".into()],
            copies: socket
                .parent()
                .map_or_else(std::env::temp_dir, Path::to_path_buf),
        }
    }

    /// How the dashboard names it.
    pub fn name(&self) -> &str {
        self.argv.first().map_or("nvim", String::as_str)
    }
}

/// The editor open in the pane, on the text of an agent (or a shell: the
/// mode names it, as the view does).
pub struct Editor {
    /// Its screen, drawn in the pane in place of the agent's, and the
    /// mouse's selection on it. Always live (`from` stays `None`).
    pub view: Peek,
    /// The size of its terminal.
    size: (u16, u16),
    /// `None`: a test's, drawn only.
    running: Option<Running>,
}

struct Running {
    pty: Pty,
    /// To the thread writing to the editor's input.
    keys: mpsc::Sender<Vec<u8>>,
    /// Goes with it (removed when dropped).
    _copy: Copy,
}

impl Editor {
    /// Write `text` to a copy and open it with `program`, at `start`, on a
    /// terminal of `size`, in `dir`. Its screen changes and clipboard sets
    /// come as `events` (when a tokio runtime runs: the dashboard's).
    pub fn open(
        program: &Program,
        agent: &str,
        text: &str,
        start: Start,
        size: (u16, u16),
        dir: &Path,
        events: UnboundedSender<Event>,
    ) -> Result<Self> {
        let copy = Copy::write(&program.copies, agent, text)?;
        let (name, args) = program.argv.split_first().context("no editor")?;
        let mut cmd = Command::new(name);
        cmd.args(args)
            .args(nvim_args(start, &copy.path))
            .env("TERM", TERM);
        // The dashboard's environment (`Launch::default()`), no wrapper.
        let pty = Pty::spawn(cmd, dir, &pty::Launch::default(), program.name())?;
        let size = (size.0.max(1), size.1.max(1));
        pty.resize(size.0, size.1);
        let keys = key_writer(pty.master())?;
        if let Ok(runtime) = tokio::runtime::Handle::try_current() {
            let (_, output) = pty.attach_output();
            runtime.spawn(watch_output(
                pty.screen_changes(),
                output,
                keys.clone(),
                events,
            ));
        }
        let mut editor = Self {
            view: Peek {
                agent: Some(agent.to_string()),
                ..Peek::default()
            },
            size,
            running: Some(Running {
                pty,
                keys,
                _copy: copy,
            }),
        };
        editor.refresh();
        Ok(editor)
    }

    /// An editor showing `screen`, running nothing: for tests.
    #[cfg(test)]
    pub fn drawn(agent: &str, screen: &tam_proto::ScreenInfo) -> Self {
        let mut view = Peek {
            agent: Some(agent.to_string()),
            ..Peek::default()
        };
        view.set_screen(screen);
        Self {
            view,
            size: (screen.cols, screen.rows),
            running: None,
        }
    }

    /// Type `bytes` into it.
    pub fn keys(&self, bytes: Vec<u8>) {
        if let Some(running) = &self.running {
            let _ = running.keys.send(bytes);
        }
    }

    /// Take its latest screen.
    pub fn refresh(&mut self) {
        if let Some(running) = &self.running {
            self.view.set_screen(&running.pty.screen(None));
        }
    }

    /// Its exit status once it exited.
    pub fn exited(&mut self) -> Option<i32> {
        self.running.as_mut()?.pty.check_exited()
    }

    /// Give it the size of the pane it was drawn in, when that changed.
    pub fn fit(&mut self) {
        let (cols, rows) = self.view.room;
        if cols == 0 || rows == 0 || (cols, rows) == self.size {
            return;
        }
        self.size = (cols, rows);
        if let Some(running) = &self.running {
            running.pty.resize(cols, rows);
        }
    }

    /// What the wheel turned over its screen at `(x, y)` sends it: a wheel
    /// report where it asked for the mouse (nvim does by default: it
    /// scrolls the window under it), else `ctrl-y`/`ctrl-e`, a line each.
    pub fn wheel(&self, up: bool, x: u16, y: u16) -> Option<Vec<u8>> {
        let screen = self.view.screen.as_ref()?.screen();
        Some(wheel(
            screen,
            up,
            x.saturating_sub(self.view.area.x),
            y.saturating_sub(self.view.area.y),
        ))
    }
}

impl Drop for Running {
    /// Hang it up, as its terminal closing would (unless it is gone
    /// already: no signal to a pid reaped and maybe reused).
    fn drop(&mut self) {
        if self.pty.check_exited().is_none() {
            self.pty.hang_up();
        }
    }
}

/// nvim's arguments: read-only, no swap file, no shada (the copy is never
/// among its recent files), no columns before the text (the agent's lines
/// are cut at the pane's width already), at `start`; the user's config
/// otherwise (a yank goes through their `clipboard`).
fn nvim_args(start: Start, file: &Path) -> Vec<std::ffi::OsString> {
    let mut args: Vec<std::ffi::OsString> = [
        "-M",
        "-n",
        "-i",
        "NONE",
        "-c",
        "setlocal nonumber norelativenumber signcolumn=no foldcolumn=0",
    ]
    .iter()
    .map(Into::into)
    .collect();
    match start {
        Start::End => args.extend(["+".into(), "-c".into(), "normal! zb".into()]),
        // The line on the window's first row, and the cursor as near it as
        // 'scrolloff' lets it be (`zt` would leave 'scrolloff' lines above
        // it).
        Start::Line(line) => args.extend([
            "-c".into(),
            format!(
                "call winrestview({{'topline': min([{line}, line('$')]), \
                 'lnum': min([{line} + min([&scrolloff, (winheight(0) - 1) / 2]), line('$')])}})"
            )
            .into(),
        ]),
    }
    args.extend(["--".into(), file.into()]);
    args
}

/// The bytes of the wheel turned at `(col, row)` of `screen`.
fn wheel(screen: &vt100::Screen, up: bool, col: u16, row: u16) -> Vec<u8> {
    if screen.mouse_protocol_mode() == vt100::MouseProtocolMode::None {
        // ctrl-y shows a line more above, ctrl-e below.
        let key = if up { 0x19 } else { 0x05 };
        return vec![key; WHEEL_LINES];
    }
    let button = if up { 64u16 } else { 65 };
    let (col, row) = (col + 1, row + 1);
    match screen.mouse_protocol_encoding() {
        vt100::MouseProtocolEncoding::Sgr => format!("\x1b[<{button};{col};{row}M").into_bytes(),
        // One byte each, from 32 (positions past 223 cannot be said).
        _ => {
            let byte = |n: u16| (32 + n).min(255) as u8;
            vec![0x1b, b'[', b'M', byte(button), byte(col), byte(row)]
        }
    }
}

/// A thread writing to the editor's input what is sent to it, in order:
/// not the event loop, which a program reading none of its input would
/// block.
fn key_writer(master: Arc<OwnedFd>) -> Result<mpsc::Sender<Vec<u8>>> {
    let (tx, rx) = mpsc::channel::<Vec<u8>>();
    std::thread::Builder::new()
        .name("editor-keys".into())
        .spawn(move || {
            for bytes in rx {
                if !pty::write_pty(&master, &bytes) {
                    break;
                }
            }
        })
        .context("failed to start the editor's input")?;
    Ok(tx)
}

/// Until the editor is gone: tell the event loop when its screen changes,
/// pass on its clipboard sets, answer its queries (see [`Watch`]).
async fn watch_output(
    mut changes: watch::Receiver<()>,
    mut output: broadcast::Receiver<Vec<u8>>,
    keys: mpsc::Sender<Vec<u8>>,
    events: UnboundedSender<Event>,
) {
    let mut parser = watch_parser();
    loop {
        tokio::select! {
            changed = changes.changed() => {
                if changed.is_err() || events.send(Event::Changed).is_err() {
                    return;
                }
            }
            bytes = output.recv() => match bytes {
                Ok(bytes) => {
                    // A parser bug must not end the task (nvim would wait
                    // on its answers): start over.
                    let fed = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                        parser.process(&bytes)
                    }));
                    if fed.is_err() {
                        parser = watch_parser();
                    }
                    let watch = parser.callbacks_mut();
                    if !watch.answers.is_empty() {
                        let _ = keys.send(std::mem::take(&mut watch.answers));
                    }
                    for set in watch.sets.drain(..) {
                        if events.send(Event::Clipboard(set)).is_err() {
                            return;
                        }
                    }
                }
                // Output went by unread: nothing to draw from it.
                Err(broadcast::error::RecvError::Lagged(_)) => {}
                Err(broadcast::error::RecvError::Closed) => return,
            },
        }
    }
}

/// A parser for what [`Watch`] reads: only its callbacks matter, the
/// screen a terminal's usual size.
fn watch_parser() -> vt100::Parser<Watch> {
    let (rows, cols) = (
        std::num::NonZeroU16::new(24).expect("not zero"),
        std::num::NonZeroU16::new(80).expect("not zero"),
    );
    vt100::Parser::new_with_callbacks(rows, cols, 0, Watch::default())
}

/// What the dashboard reads in the editor's output. Reading it (holding
/// its output) stops the PTY's own answers (`Pty`: a viewer's terminal
/// answers then), so the ones nvim waits on are given here: its status
/// (`CSI 5 n`: else it draws 100 ms late) and its device attributes
/// (`CSI c`: else it takes a second to exit). Not the cursor position,
/// which nvim does not ask.
#[derive(Default)]
struct Watch {
    /// For its input, in order.
    answers: Vec<u8>,
    /// OSC 52 sequences, for the dashboard's terminal.
    sets: Vec<String>,
}

impl vt100::Callbacks for Watch {
    fn copy_to_clipboard(&mut self, _: &mut vt100::Screen, ty: &[u8], data: &[u8]) {
        self.sets.extend(clipboard_set(ty, data));
    }

    fn unhandled_csi(
        &mut self,
        _: &mut vt100::Screen,
        i1: Option<u8>,
        _i2: Option<u8>,
        params: &[&[u16]],
        c: char,
    ) {
        match (i1, c, params) {
            (None, 'n', [[5]]) => self.answers.extend_from_slice(b"\x1b[0n"),
            (None, 'c', [] | [[0]]) => self.answers.extend_from_slice(DEVICE_ATTRIBUTES),
            _ => {}
        }
    }
}

/// The OSC 52 sequence setting the clipboard `ty` (`c`, `p`, …) to `data`
/// (base64), for the dashboard's terminal: only one made of what such a
/// sequence holds (nothing else gets written to the terminal). Queries
/// (`?`) are never passed on: vt100 reports them apart.
fn clipboard_set(ty: &[u8], data: &[u8]) -> Option<String> {
    let ty_ok = ty.iter().all(|b| b"cpqs01234567".contains(b));
    let base64 = |b: &u8| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'/' | b'=');
    if !ty_ok || data.is_empty() || !data.iter().all(base64) {
        return None;
    }
    let ty = std::str::from_utf8(ty).ok()?;
    let data = std::str::from_utf8(data).ok()?;
    Some(format!("\x1b]52;{ty};{data}\x1b\\"))
}

/// The text the editor opens: a file only its user reads (0600), in tam's
/// runtime directory, removed when dropped. A dashboard killed before
/// leaves its copies: the next one to open one removes them.
struct Copy {
    path: PathBuf,
}

impl Copy {
    fn write(dir: &Path, agent: &str, text: &str) -> Result<Self> {
        std::fs::create_dir_all(dir)
            .with_context(|| format!("failed to create {}", dir.display()))?;
        sweep(dir);
        let pid = std::process::id();
        // The agent's id names it in the editor; the pid says whose it is.
        let agent: String = agent
            .chars()
            .map(|c| {
                if c.is_ascii_alphanumeric() || c == '-' {
                    c
                } else {
                    '_'
                }
            })
            .collect();
        let path = dir.join(format!("{COPY_PREFIX}{pid}-{agent}"));
        // A copy left by a dead dashboard of this pid.
        let _ = std::fs::remove_file(&path);
        let mut file = OpenOptions::new()
            .write(true)
            .create_new(true)
            .mode(0o600)
            .open(&path)
            .with_context(|| format!("failed to write {}", path.display()))?;
        let copy = Self { path };
        file.write_all(text.as_bytes())
            .and_then(|()| file.write_all(b"\n"))
            .with_context(|| format!("failed to write {}", copy.path.display()))?;
        Ok(copy)
    }
}

impl Drop for Copy {
    fn drop(&mut self) {
        let _ = std::fs::remove_file(&self.path);
    }
}

const COPY_PREFIX: &str = "copy-";

/// Remove the copies of dashboards that are gone (killed: they could not).
fn sweep(dir: &Path) {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return;
    };
    for entry in entries.flatten() {
        let name = entry.file_name();
        let Some(pid) = name
            .to_str()
            .and_then(|n| n.strip_prefix(COPY_PREFIX))
            .and_then(|rest| rest.split('-').next())
            .and_then(|pid| pid.parse::<i32>().ok())
        else {
            continue;
        };
        let gone = nix::sys::signal::kill(nix::unistd::Pid::from_raw(pid), None)
            == Err(nix::errno::Errno::ESRCH);
        if gone {
            let _ = std::fs::remove_file(entry.path());
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::os::unix::fs::PermissionsExt;
    use std::time::{Duration, Instant};

    /// A stand-in for nvim: `sh -c SCRIPT nvim ARGS...`.
    fn stand_in(dir: &Path, script: &str) -> Program {
        Program {
            argv: vec!["sh".into(), "-c".into(), script.into(), "nvim".into()],
            copies: dir.to_path_buf(),
        }
    }

    fn open(
        program: &Program,
        start: Start,
    ) -> (Editor, tokio::sync::mpsc::UnboundedReceiver<Event>) {
        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
        let editor = Editor::open(
            program,
            "m-0000abcd",
            "line 1\nline 2",
            start,
            (100, 30),
            &program.copies,
            tx,
        )
        .unwrap();
        (editor, rx)
    }

    fn text(editor: &Editor) -> String {
        let screen = editor.view.screen.as_ref().unwrap().screen();
        screen.contents()
    }

    /// Wait until the editor's screen has `what`.
    fn wait_for(editor: &mut Editor, what: &str) -> String {
        let deadline = Instant::now() + Duration::from_secs(10);
        loop {
            editor.refresh();
            let text = text(editor);
            if text.contains(what) {
                return text;
            }
            assert!(Instant::now() < deadline, "no {what:?} in {text:?}");
            std::thread::sleep(Duration::from_millis(20));
        }
    }

    #[test]
    fn nvim_reads_a_private_copy_at_the_line_the_pane_showed() {
        let dir = tempfile::tempdir().unwrap();
        // Prints its arguments, then what it is typed.
        let program = stand_in(dir.path(), "printf '<%s>\\n' \"$@\"; exec cat");
        let (mut editor, _events) = open(&program, Start::Line(42));
        // The copy: the agent's text, its user's only.
        let copies: Vec<PathBuf> = std::fs::read_dir(dir.path())
            .unwrap()
            .map(|e| e.unwrap().path())
            .collect();
        assert_eq!(copies.len(), 1, "{copies:?}");
        let copy = &copies[0];
        assert_eq!(std::fs::read_to_string(copy).unwrap(), "line 1\nline 2\n");
        let mode = std::fs::metadata(copy).unwrap().permissions().mode();
        assert_eq!(mode & 0o777, 0o600);
        // Its arguments, the copy last.
        let text = wait_for(&mut editor, &format!("<-->\n<{}>", copy.display()));
        for arg in [
            "<-M>",
            "<-n>",
            "<-i>",
            "<NONE>",
            "<setlocal nonumber norelativenumber signcolumn=no foldcolumn=0>",
            "'topline': min([42, line('$')])",
        ] {
            assert!(text.contains(arg), "{arg}: {text}");
        }

        // Keys reach it, in its terminal of the pane's size, which follows
        // the pane.
        editor.keys(b"typed\r".to_vec());
        wait_for(&mut editor, "typed\ntyped");
        let cols = |editor: &Editor| editor.view.screen.as_ref().unwrap().screen().size().1.get();
        assert_eq!(cols(&editor), 100);
        editor.view.room = (90, 20);
        editor.fit();
        editor.refresh();
        assert_eq!(cols(&editor), 90);
        assert_eq!(editor.exited(), None);

        // Gone with it: the copy, and the program (hung up).
        drop(editor);
        assert!(!copy.exists());
    }

    #[test]
    fn a_live_pane_opens_at_the_end() {
        let args = nvim_args(Start::End, Path::new("/run/tam/copy"));
        let args: Vec<&str> = args.iter().map(|a| a.to_str().unwrap()).collect();
        assert_eq!(args[6..], ["+", "-c", "normal! zb", "--", "/run/tam/copy"]);
    }

    #[test]
    fn its_exit_is_seen_and_a_missing_program_is_an_error() {
        let dir = tempfile::tempdir().unwrap();
        let (mut editor, _events) = open(&stand_in(dir.path(), "exit 3"), Start::End);
        let deadline = Instant::now() + Duration::from_secs(10);
        let status = loop {
            if let Some(status) = editor.exited() {
                break status;
            }
            assert!(Instant::now() < deadline, "not exited");
            std::thread::sleep(Duration::from_millis(10));
        };
        assert_eq!(status, 3);
        drop(editor);

        let missing = Program {
            argv: vec!["/nonexistent/tam-test-nvim".into()],
            copies: dir.path().to_path_buf(),
        };
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        let err = Editor::open(&missing, "m-1", "x", Start::End, (80, 24), dir.path(), tx)
            .err()
            .expect("no such program");
        assert!(format!("{err:#}").contains("tam-test-nvim"), "{err:#}");
        // No copy left behind.
        assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0);
    }

    #[test]
    fn copies_of_dashboards_gone_are_swept() {
        let dir = tempfile::tempdir().unwrap();
        // A pid no process has (above the kernel's maximum).
        let gone = dir.path().join(format!("{COPY_PREFIX}2147483646-m-1"));
        let mine = dir
            .path()
            .join(format!("{COPY_PREFIX}{}-m-2", std::process::id()));
        let other = dir.path().join("sock");
        for path in [&gone, &mine, &other] {
            std::fs::write(path, "x").unwrap();
        }
        let copy = Copy::write(dir.path(), "m-3", "text").unwrap();
        assert!(!gone.exists());
        assert!(mine.exists() && other.exists() && copy.path.exists());
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn clipboard_sets_are_passed_on_and_queries_answered() {
        let dir = tempfile::tempdir().unwrap();
        // Waits for its output to be read, sets the clipboard, asks for it
        // (never passed on), then asks what nvim waits on and shows the
        // answers.
        let script = "sleep 0.5; \
            printf '\\033]52;c;aGVsbG8=\\007\\033]52;c;?\\007\\033]52;c;no base64!\\007'; \
            stty -icanon -echo min 1; \
            printf '\\033[5n'; a=$(head -c 4 | cat -v); \
            printf '\\033[c'; b=$(head -c 9 | cat -v); \
            echo \"status:$a\"; echo \"attributes:$b\"; exec cat";
        let (mut editor, mut events) = open(&stand_in(dir.path(), script), Start::End);
        let mut sets = Vec::new();
        let deadline = tokio::time::Instant::now() + Duration::from_secs(10);
        loop {
            editor.refresh();
            if text(&editor).contains("attributes:") {
                break;
            }
            match tokio::time::timeout_at(deadline, events.recv()).await {
                Ok(Some(Event::Clipboard(set))) => sets.push(set),
                Ok(Some(Event::Changed)) => {}
                _ => panic!("no answers: {:?}", text(&editor)),
            }
        }
        while let Ok(event) = events.try_recv() {
            if let Event::Clipboard(set) = event {
                sets.push(set);
            }
        }
        assert_eq!(sets, ["\x1b]52;c;aGVsbG8=\x1b\\"]);
        let text = text(&editor);
        assert!(text.contains("status:^[[0n"), "{text}");
        assert!(text.contains("attributes:^[[?62;22c"), "{text}");
    }

    #[test]
    fn wide_characters_do_not_trouble_the_watch() {
        let mut parser = watch_parser();
        let line = "漢字 🦀 é ".repeat(20);
        parser.process(format!("{line}\x1b[5n\x1b]52;c;aGk=\x07{line}").as_bytes());
        let watch = parser.callbacks_mut();
        assert_eq!(watch.answers, b"\x1b[0n");
        assert_eq!(watch.sets, ["\x1b]52;c;aGk=\x1b\\"]);
    }

    #[test]
    fn the_wheel_is_the_mouse_s_where_it_asked_for_it_else_keys() {
        let screen = |modes: &str| {
            let mut parser = vt100::Parser::new(
                std::num::NonZeroU16::new(24).unwrap(),
                std::num::NonZeroU16::new(80).unwrap(),
                0,
            );
            parser.process(modes.as_bytes());
            parser
        };
        let sgr = screen("\x1b[?1002h\x1b[?1006h");
        assert_eq!(wheel(sgr.screen(), true, 4, 9), b"\x1b[<64;5;10M");
        assert_eq!(wheel(sgr.screen(), false, 0, 0), b"\x1b[<65;1;1M");
        let x10 = screen("\x1b[?1000h");
        assert_eq!(wheel(x10.screen(), true, 4, 9), b"\x1b[M\x60\x25\x2a");
        let none = screen("");
        assert_eq!(wheel(none.screen(), true, 4, 9), [0x19; 3]);
        assert_eq!(wheel(none.screen(), false, 4, 9), [0x05; 3]);
    }

    #[test]
    fn only_well_formed_clipboard_sets_are_passed_on() {
        assert_eq!(
            clipboard_set(b"c", b"aGk="),
            Some("\x1b]52;c;aGk=\x1b\\".into())
        );
        assert_eq!(
            clipboard_set(b"", b"aGk="),
            Some("\x1b]52;;aGk=\x1b\\".into())
        );
        for (ty, data) in [
            (&b"c"[..], &b""[..]),
            (b"c", b"aGk\x1b[2J"),
            (b"c\x1b", b"aGk="),
            (b"x", b"aGk="),
        ] {
            assert_eq!(clipboard_set(ty, data), None, "{ty:?} {data:?}");
        }
    }
}