runandlog 0.6.0

CLI / TUI that runs the shell commands in a Markdown file and writes the results back
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
//! Terminal UI. Pick a cell, run it, and read the result in place.

use std::collections::HashMap;
use std::io;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError, mpsc};
use std::thread;
use std::time::Duration;

use ratatui::DefaultTerminal;
use ratatui::crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use ratatui::layout::{Constraint, Layout};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span, Text};
use ratatui::widgets::{Block, Borders, Paragraph};
use runandlog_core::{Canceller, ExecOutcome};

use crate::live::LiveOutput;
use crate::session::Session;

// The run/draw loop needs a terminal and cannot be covered by automated tests, so
// the tests live in runandlog-core (parse, exec, render), in session (write-back)
// and in live (the rolling buffer behind the live view). What is left here is
// tested through the small decisions pulled out as free functions.

/// Interval between input polls and redraws.
const TICK: Duration = Duration::from_millis(100);
const SPINNER: [char; 4] = ['|', '/', '-', '\\'];
const PAGE_LINES: usize = 10;
/// How many trailing lines of a running command's output are shown under its cell.
///
/// Enough to see that something is happening and what it is; more would push the
/// cells below off the screen every time a command runs.
const LIVE_TAIL_LINES: usize = 3;
/// How much of a running command's output is kept for the live view.
///
/// Only the last few lines are drawn, so this only has to be comfortably more than
/// they can take up -- a command printing for hours must not grow with its output.
const LIVE_LIMIT: usize = 16 * 1024;

/// Opens the TUI.
pub fn run(mut session: Session) -> io::Result<()> {
    let (password_tx, password_rx) = mpsc::channel();
    let password_queue = Arc::new(Mutex::new(PasswordQueue {
        accepting: false,
        requests: password_tx,
    }));
    // Kept alive until the TUI closes: dropping it takes the socket away. A failure
    // to start leaves commands where they were before there was a helper -- asking
    // for a password fails at once -- which is no reason to refuse to open.
    #[cfg(unix)]
    let _askpass = start_askpass(&mut session, Arc::clone(&password_queue));
    let terminal = ratatui::init();
    let result = App::new(session, password_rx, password_queue).run(terminal);
    ratatui::restore();
    result
}

/// A command asking the user for a password, waiting for the answer on `reply`.
struct PasswordRequest {
    prompt: String,
    reply: mpsc::Sender<Option<String>>,
}

/// The password prompt on screen, and what has been typed into it so far.
struct PasswordPrompt {
    request: PasswordRequest,
    typed: String,
}

impl PasswordPrompt {
    /// Sends the answer, or `None` for "declined".
    fn answer(self, answer: Option<String>) {
        // The helper may be gone already -- its command was cancelled, say -- and
        // then there is nobody left to tell.
        let _ = self.request.reply.send(answer);
    }
}

/// Where the helper's requests go, and whether a run is taking them.
///
/// One lock for both, so that a request cannot land in the queue between the end
/// of a run declining what is queued and the next run opening the queue again.
/// The listener checks the run before it calls the prompter and lets go of its
/// lock to do so; a request that passed that check just as the run ended would
/// otherwise arrive after the drain and be shown under the next cell. (The GUI's
/// `Passwords` has the same shape, for the same reason.)
struct PasswordQueue {
    accepting: bool,
    requests: mpsc::Sender<PasswordRequest>,
}

impl PasswordQueue {
    fn lock(queue: &Mutex<PasswordQueue>) -> MutexGuard<'_, PasswordQueue> {
        // A poisoned lock holds a usable queue all the same.
        queue.lock().unwrap_or_else(PoisonError::into_inner)
    }

    /// Hands a request to the TUI. `None` when no run is taking requests, when
    /// the request's own run is over (`gone`), or when the TUI has closed.
    ///
    /// `gone` is asked under the lock. Being open is not enough: the queue may
    /// have been closed for the request's run and opened again for the next one
    /// while the request was on its way, and then it is the next run's queue that
    /// is open. `gone` tells the runs apart -- it is true once the request's run
    /// has ended -- and nothing can end or start a run's queue while it is asked.
    fn submit(
        queue: &Mutex<PasswordQueue>,
        request: PasswordRequest,
        gone: &dyn Fn() -> bool,
    ) -> Option<()> {
        let queue = Self::lock(queue);
        if !queue.accepting || gone() {
            return None;
        }
        queue.requests.send(request).ok()
    }
}

/// Starts the askpass helper, forwarding its prompts to the TUI through `queue`.
#[cfg(unix)]
fn start_askpass(
    session: &mut Session,
    queue: Arc<Mutex<PasswordQueue>>,
) -> Option<crate::askpass::Askpass> {
    let askpass = crate::askpass::Askpass::start(Box::new(move |prompt, gone| {
        let (reply, answer) = mpsc::channel();
        PasswordQueue::submit(
            &queue,
            PasswordRequest {
                prompt: prompt.to_string(),
                reply,
            },
            gone,
        )?;
        // A dropped sender -- the TUI closed, or the run ended with the prompt up --
        // is a decline.
        crate::askpass::wait_for_answer(&answer, gone)
    }))
    .ok()?;
    session.set_run_hook(askpass.hook());
    Some(askpass)
}

/// Declines the prompt on screen and every request still queued behind it.
///
/// For the end of a run, **with the [`PasswordQueue`] locked and closed**: they all
/// belong to the run that has just ended, but a request that arrived after the
/// last tick is still in the queue, and the next tick would put it up under the
/// next cell as though that cell had asked (in a "run all", the next cell starts
/// at once). The run token keeps the answer from reaching the old helper; this
/// keeps the question from being shown.
fn decline_prompts(shown: &mut Option<PasswordPrompt>, queued: &mpsc::Receiver<PasswordRequest>) {
    if let Some(prompt) = shown.take() {
        prompt.answer(None);
    }
    while let Ok(request) = queued.try_recv() {
        // The helper may be gone already; then there is nobody left to tell.
        let _ = request.reply.send(None);
    }
}

/// What a key does to the password prompt.
#[derive(Debug, PartialEq, Eq)]
enum PromptKey {
    Type(char),
    Erase,
    Send,
    Decline,
    Ignore,
}

/// Reads a key as input to the password prompt.
///
/// Ctrl-C is not handled here: it keeps meaning "stop the command", which declines
/// the prompt along the way.
fn prompt_key(key: KeyEvent) -> PromptKey {
    match key.code {
        KeyCode::Enter => PromptKey::Send,
        KeyCode::Esc => PromptKey::Decline,
        KeyCode::Backspace => PromptKey::Erase,
        KeyCode::Char(c)
            if !key
                .modifiers
                .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT) =>
        {
            PromptKey::Type(c)
        }
        _ => PromptKey::Ignore,
    }
}

/// Whether a "run all" batch may go on to the next cell.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Batch {
    Continue,
    Stop,
}

/// Whether a key press means "quit".
fn is_quit_key(key: KeyEvent) -> bool {
    match key.code {
        KeyCode::Char('q') | KeyCode::Esc => true,
        KeyCode::Char('c') => key.modifiers.contains(KeyModifiers::CONTROL),
        _ => false,
    }
}

/// Whether a key press means "stop the running command".
///
/// Only Ctrl-C. `q` and `Esc` keep their documented meaning of quitting once the
/// command has finished, which is what you want for a command that is merely slow;
/// Ctrl-C is the way out of one that will never finish.
fn is_cancel_key(key: KeyEvent) -> bool {
    key.code == KeyCode::Char('c') && key.modifiers.contains(KeyModifiers::CONTROL)
}

/// What the marker of a cell says, telling apart a first run from a repeat.
///
/// Both are the same width so that the highlighted markers line up down the
/// column, whichever cells happen to carry a result.
fn run_label(has_result: bool) -> &'static str {
    if has_result { "Re-run" } else { "Run   " }
}

/// Where a cell stands in *this* session of the TUI.
///
/// A result already in the file is not a run of this session: reopening a document
/// that was run yesterday should not colour every cell as done. What the colours
/// answer is "how far has this batch got", which only holds for runs since the
/// file was opened or last reloaded.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CellState {
    /// Not run since the file was opened.
    Waiting,
    /// Running right now.
    Running,
    /// Run and finished successfully.
    Done,
    /// Run and finished with a non-zero exit, a timeout, or a cancellation.
    Failed,
}

/// Where a cell stands, from the index being run and what has finished.
fn cell_state(index: usize, running: Option<usize>, finished: Option<bool>) -> CellState {
    if running == Some(index) {
        return CellState::Running;
    }
    match finished {
        Some(true) => CellState::Done,
        Some(false) => CellState::Failed,
        None => CellState::Waiting,
    }
}

/// Colour of a cell's marker.
///
/// The marker is what the eye follows down a "run all", so the state is carried
/// there in full: waiting, running now, done, or done badly.
fn marker_color(state: CellState) -> Color {
    match state {
        CellState::Waiting => Color::Green,
        CellState::Running => Color::Yellow,
        CellState::Done => Color::Blue,
        CellState::Failed => Color::Red,
    }
}

/// Style of a cell's command text.
///
/// A finished cell is dimmed so that the cells still to come stand out from the
/// ones already dealt with -- the question during a long batch is where it is up
/// to, and that is easier to see from the text than from a marker alone.
fn command_style(state: CellState) -> Style {
    match state {
        CellState::Done | CellState::Failed => Style::default().fg(Color::DarkGray),
        _ => Style::default(),
    }
}

/// The lines to draw, plus the line range occupied by each cell.
struct Rendered {
    lines: Vec<Line<'static>>,
    /// (first line, one past the last line) for each cell.
    spans: Vec<(usize, usize)>,
}

struct App {
    session: Session,
    selected: usize,
    scroll: usize,
    /// Height of the body area. Used to adjust the scroll position.
    viewport: usize,
    status: String,
    /// The cell being run (0-based) and the spinner phase.
    running: Option<(usize, usize)>,
    /// What the command being run has printed so far.
    live: LiveOutput,
    /// Prompts for a password from the askpass helper.
    password_requests: mpsc::Receiver<PasswordRequest>,
    /// The helper's way in to `password_requests`, opened for each run and closed
    /// after it.
    password_queue: Arc<Mutex<PasswordQueue>>,
    /// The password prompt on screen, if a command is asking for one.
    password: Option<PasswordPrompt>,
    /// Cells run since the file was opened, and whether each one succeeded.
    ///
    /// Keyed by index, and dropped whenever the file is re-read: after a reload the
    /// cell at an index need not be the one that ran.
    finished: HashMap<usize, bool>,
    quit: bool,
}

impl App {
    fn new(
        session: Session,
        password_requests: mpsc::Receiver<PasswordRequest>,
        password_queue: Arc<Mutex<PasswordQueue>>,
    ) -> App {
        let status = if session.is_empty() {
            "No runnable cells. Press q to quit.".to_string()
        } else {
            "Enter/r: run  a: run all  j/k: move  R: reload  q: quit".to_string()
        };
        App {
            session,
            selected: 0,
            scroll: 0,
            viewport: 1,
            status,
            running: None,
            live: LiveOutput::new(LIVE_LIMIT),
            password_requests,
            password_queue,
            password: None,
            finished: HashMap::new(),
            quit: false,
        }
    }

    fn run(mut self, mut terminal: DefaultTerminal) -> io::Result<()> {
        while !self.quit {
            self.redraw(&mut terminal)?;
            self.handle_events(&mut terminal)?;
        }
        Ok(())
    }

    fn redraw(&mut self, terminal: &mut DefaultTerminal) -> io::Result<()> {
        let rendered = self.render_lines();
        terminal.draw(|frame| {
            let areas = Layout::vertical([
                Constraint::Length(1),
                Constraint::Min(1),
                Constraint::Length(1),
            ])
            .split(frame.area());

            let header = Line::from(vec![
                Span::styled("File: ", Style::default().fg(Color::DarkGray)),
                Span::styled(
                    self.session.path().display().to_string(),
                    Style::default().add_modifier(Modifier::BOLD),
                ),
            ]);
            frame.render_widget(Paragraph::new(header), areas[0]);

            // The body height is what is left after the top and bottom borders.
            self.viewport = (areas[1].height.saturating_sub(2) as usize).max(1);
            self.adjust_scroll(&rendered);

            let body = Paragraph::new(Text::from(rendered.lines.clone()))
                .block(Block::default().borders(Borders::TOP | Borders::BOTTOM))
                .scroll((self.scroll as u16, 0));
            frame.render_widget(body, areas[1]);

            let status = match (&self.password, self.running) {
                (Some(prompt), _) => Line::from(vec![
                    Span::styled(
                        format!("{} ", prompt.request.prompt),
                        Style::default()
                            .fg(Color::Yellow)
                            .add_modifier(Modifier::BOLD),
                    ),
                    // One mark per character, so the typing can be seen to land
                    // without showing what was typed.
                    Span::raw("*".repeat(prompt.typed.chars().count())),
                    Span::styled(
                        "  (Enter: send  Esc: decline  Ctrl-C: stop)",
                        Style::default().fg(Color::DarkGray),
                    ),
                ]),
                (None, Some((index, phase))) => Line::from(Span::styled(
                    format!(
                        "{} running cell {}",
                        SPINNER[phase % SPINNER.len()],
                        index + 1
                    ),
                    Style::default().fg(Color::DarkGray),
                )),
                (None, None) => Line::from(Span::styled(
                    self.status.clone(),
                    Style::default().fg(Color::DarkGray),
                )),
            };
            frame.render_widget(Paragraph::new(status), areas[2]);
        })?;
        Ok(())
    }

    /// Builds the lines to display.
    fn render_lines(&self) -> Rendered {
        let mut lines = Vec::new();
        let mut spans = Vec::new();
        let doc = self.session.doc();

        let running = self.running.map(|(index, _)| index);
        for cell in &doc.cells {
            let start = lines.len();
            let selected = cell.index == self.selected;
            let state = cell_state(cell.index, running, self.finished.get(&cell.index).copied());
            let color = marker_color(state);
            let marker_style = if selected {
                Style::default()
                    .fg(Color::Black)
                    .bg(color)
                    .add_modifier(Modifier::BOLD)
            } else {
                Style::default().fg(color)
            };
            lines.push(Line::from(vec![
                Span::styled(
                    format!(
                        " [{}] > {} ",
                        cell.display_number(),
                        run_label(doc.result_text(cell).is_some())
                    ),
                    marker_style,
                ),
                Span::styled(
                    match &cell.out_file {
                        Some(path) => format!("  -> {path}"),
                        None => String::new(),
                    },
                    Style::default().fg(Color::DarkGray),
                ),
            ]));
            for command in cell.command.lines() {
                lines.push(Line::from(vec![
                    Span::styled("   > ", Style::default().fg(Color::DarkGray)),
                    Span::styled(command.to_string(), command_style(state)),
                ]));
            }
            if state == CellState::Running {
                // The live tail takes the place of the previous result rather than
                // sitting under it: the two are the same cell's output from
                // different runs, and stacked they read as one long result.
                lines.extend(self.live_lines());
            } else if let Some(result) = doc.result_text(cell) {
                lines.push(Line::from(""));
                for line in result.lines() {
                    lines.push(Line::from(Span::styled(
                        format!("   {line}"),
                        Style::default().fg(Color::Gray),
                    )));
                }
            }
            lines.push(Line::from(""));
            spans.push((start, lines.len()));
        }

        if lines.is_empty() {
            lines.push(Line::from(Span::styled(
                "  No shell / sh / bash / zsh code block found.",
                Style::default().fg(Color::DarkGray),
            )));
        }
        Rendered { lines, spans }
    }

    /// The live output of the running cell: its last few lines, as they arrive.
    ///
    /// Always the same height, however little has been printed. Growing the block
    /// line by line would shift every cell below it each time the command prints,
    /// and the reason to watch a running command is to read it.
    fn live_lines(&self) -> Vec<Line<'static>> {
        let mut lines = vec![Line::from("")];
        let tail = self.live.tail_lines(LIVE_TAIL_LINES);
        for index in 0..LIVE_TAIL_LINES {
            let line = match tail.get(index) {
                Some(line) => format!("   {line}"),
                None if index == 0 && tail.is_empty() => "   (no output yet)".to_string(),
                None => String::new(),
            };
            lines.push(Line::from(Span::styled(
                line,
                Style::default().fg(Color::DarkGray),
            )));
        }
        lines
    }

    /// Nudges the scroll position so the selected cell stays on screen.
    fn adjust_scroll(&mut self, rendered: &Rendered) {
        if let Some(&(start, end)) = rendered.spans.get(self.selected) {
            if start < self.scroll {
                self.scroll = start;
            } else if end > self.scroll + self.viewport {
                // For a cell taller than the viewport, prefer its top over its bottom.
                self.scroll = end.saturating_sub(self.viewport).min(start);
            }
        }
        self.scroll = self.scroll.min(rendered.lines.len().saturating_sub(1));
    }

    fn handle_events(&mut self, terminal: &mut DefaultTerminal) -> io::Result<()> {
        // Nothing is running, so whatever asks now is a leftover from a command that
        // has already been written back -- a background process it started, say.
        // There is no cell to show the prompt against, so it is declined.
        while let Ok(request) = self.password_requests.try_recv() {
            let _ = request.reply.send(None);
        }
        if !event::poll(TICK)? {
            return Ok(());
        }
        if let Event::Key(key) = event::read()?
            && key.kind == KeyEventKind::Press
        {
            self.handle_key(key, terminal)?;
        }
        Ok(())
    }

    fn handle_key(&mut self, key: KeyEvent, terminal: &mut DefaultTerminal) -> io::Result<()> {
        if is_quit_key(key) {
            self.quit = true;
            return Ok(());
        }
        match key.code {
            KeyCode::Char('j') | KeyCode::Down => self.select(1),
            KeyCode::Char('k') | KeyCode::Up => self.select(-1),
            KeyCode::Char('g') | KeyCode::Home => {
                self.selected = 0;
                self.scroll = 0;
            }
            KeyCode::Char('G') | KeyCode::End => {
                self.selected = self.session.len().saturating_sub(1);
            }
            KeyCode::PageDown => self.scroll = self.scroll.saturating_add(PAGE_LINES),
            KeyCode::PageUp => self.scroll = self.scroll.saturating_sub(PAGE_LINES),
            KeyCode::Char('R') => self.reload(),
            KeyCode::Enter | KeyCode::Char('r') => {
                if !self.session.is_empty() {
                    self.execute(self.selected, terminal)?;
                }
            }
            KeyCode::Char('a') => {
                for index in 0..self.session.len() {
                    if self.quit {
                        break;
                    }
                    self.selected = index;
                    if self.execute(index, terminal)? == Batch::Stop {
                        break;
                    }
                }
            }
            _ => {}
        }
        Ok(())
    }

    fn select(&mut self, delta: isize) {
        if self.session.is_empty() {
            return;
        }
        let last = self.session.len() - 1;
        self.selected = self.selected.saturating_add_signed(delta).min(last);
    }

    fn reload(&mut self) {
        match self.session.reload() {
            Ok(()) => {
                self.selected = self.selected.min(self.session.len().saturating_sub(1));
                // The cells are whatever the file now holds, so which ones this
                // session has run no longer means anything: an index that was run
                // may be a different cell now.
                self.finished.clear();
                self.status = "Reloaded.".to_string();
            }
            Err(error) => self.status = format!("Reload failed: {error}"),
        }
    }

    /// Runs one cell. The run goes to a worker thread so the screen keeps
    /// updating while it is in flight.
    ///
    /// The return value tells a "run all" batch whether it may continue.
    fn execute(&mut self, index: usize, terminal: &mut DefaultTerminal) -> io::Result<Batch> {
        let command = self.session.command_of(index);
        // Open before the run starts: the helper's first request can come as soon as
        // the command does.
        PasswordQueue::lock(&self.password_queue).accepting = true;
        let run = self.session.start_run();
        // One per run: a cancelled cell must not leave the next one unable to start.
        let canceller = Canceller::new();
        let worker_canceller = canceller.clone();
        let (tx, rx) = mpsc::channel();
        // The output is carried over its own channel rather than shared behind a
        // lock: the drawing happens on this thread, and a channel keeps the worker
        // from ever waiting on it.
        let (output_tx, output_rx) = mpsc::channel();
        thread::spawn(move || {
            let outcome =
                runandlog_core::run_streaming(&command, &run.options, &worker_canceller, |chunk| {
                    // A closed channel means the front end has stopped listening,
                    // which is not the command's problem.
                    let _ = output_tx.send(chunk.to_string());
                });
            // Ended here, on the worker: the run must not outlive the command by
            // the write-back that follows on the drawing thread.
            drop(run);
            let _ = tx.send(outcome);
        });

        self.live.clear();
        // Marked as running before the first draw, so the cell shows itself as the
        // one being run rather than looking untouched until the first tick.
        self.running = Some((index, 0));
        let outcome = self.wait_for(index, rx, output_rx, terminal, &canceller);
        {
            // Closed and drained under the one lock, so that nothing of this run
            // can be queued after the drain.
            let mut queue = PasswordQueue::lock(&self.password_queue);
            queue.accepting = false;
            decline_prompts(&mut self.password, &self.password_requests);
        }
        self.running = None;
        self.live.clear();
        match outcome {
            Ok(Ok(outcome)) => match self.session.apply_outcome(index, &outcome) {
                Ok(()) => {
                    self.finished.insert(index, outcome.is_success());
                    self.status = format!("Cell {} done ({})", index + 1, outcome.status_text());
                }
                Err(error) => {
                    // The write was refused, which usually means the file changed
                    // underneath us. Carrying on would run the *old* commands held in
                    // memory -- including ones the file no longer contains -- so stop
                    // the batch and pick the file back up from disk.
                    self.status = format!("Writing the result failed: {error}");
                    self.reload_after_conflict();
                    return Ok(Batch::Stop);
                }
            },
            Ok(Err(error)) => {
                // The shell never started. Nothing was written back, but the cell was
                // asked for and did not work, which is what its colour says.
                self.finished.insert(index, false);
                self.status = format!("The run failed: {error}");
            }
            Err(error) => return Err(error),
        }
        Ok(Batch::Continue)
    }

    /// Re-reads the file after a refused write, keeping the status text that
    /// explains why the write was refused.
    fn reload_after_conflict(&mut self) {
        if self.session.reload().is_ok() {
            self.selected = self.selected.min(self.session.len().saturating_sub(1));
            // As in `reload`: the indices no longer name the cells that ran.
            self.finished.clear();
        }
    }

    /// Handles keys pressed while a command is running.
    ///
    /// Only quitting and cancelling are honoured here; everything else is
    /// discarded, since keys pressed during the run would otherwise all fire at
    /// once when it finishes.
    ///
    /// The quit keys are the same ones the normal event loop takes, so that the
    /// documented "q quits after the command finishes" holds while one is running.
    /// Ctrl-C does not wait: raw mode means the terminal never turns it into a
    /// signal, and the command sits in a process group of its own anyway, so this
    /// is the only thing that can reach a command that hangs.
    fn drain_events_while_running(&mut self, canceller: &Canceller) -> io::Result<()> {
        while event::poll(Duration::ZERO)? {
            if let Event::Key(key) = event::read()?
                && key.kind == KeyEventKind::Press
            {
                if is_cancel_key(key) {
                    canceller.cancel();
                    self.quit = true;
                } else if self.password.is_some() {
                    // While a prompt is up, keys are what is being typed into it --
                    // `q` included, which is a letter of the password here.
                    self.type_into_prompt(key);
                } else if is_quit_key(key) {
                    // Quit after the command finishes; its result still gets written back.
                    self.quit = true;
                }
            }
        }
        Ok(())
    }

    /// Puts up the next password prompt, if a command is asking and none is up.
    fn take_password_request(&mut self) {
        if self.password.is_none()
            && let Ok(request) = self.password_requests.try_recv()
        {
            self.password = Some(PasswordPrompt {
                request,
                typed: String::new(),
            });
        }
    }

    /// Applies a key to the password prompt on screen.
    fn type_into_prompt(&mut self, key: KeyEvent) {
        let Some(prompt) = self.password.as_mut() else {
            return;
        };
        match prompt_key(key) {
            PromptKey::Type(c) => prompt.typed.push(c),
            PromptKey::Erase => {
                prompt.typed.pop();
            }
            PromptKey::Send => {
                if let Some(prompt) = self.password.take() {
                    let typed = prompt.typed.clone();
                    prompt.answer(Some(typed));
                }
            }
            PromptKey::Decline => {
                if let Some(prompt) = self.password.take() {
                    prompt.answer(None);
                }
            }
            PromptKey::Ignore => {}
        }
    }

    /// Takes whatever the running command has printed since the last look.
    fn collect_output(&mut self, output_rx: &mpsc::Receiver<String>) {
        // Never blocks: the point is to draw what has arrived, not to wait for more.
        while let Ok(chunk) = output_rx.try_recv() {
            self.live.push(&chunk);
        }
    }

    /// Waits for the run to finish, spinning the spinner and redrawing meanwhile.
    fn wait_for(
        &mut self,
        index: usize,
        rx: mpsc::Receiver<io::Result<ExecOutcome>>,
        output_rx: mpsc::Receiver<String>,
        terminal: &mut DefaultTerminal,
        canceller: &Canceller,
    ) -> io::Result<io::Result<ExecOutcome>> {
        let mut phase = 0;
        loop {
            match rx.recv_timeout(TICK) {
                Ok(result) => {
                    // Drain here too. A cell that finishes inside one TICK would
                    // otherwise return without ever looking at the terminal, so during
                    // "run all" over fast cells a queued q / Esc / Ctrl-C would not be
                    // seen until the whole batch had run.
                    self.drain_events_while_running(canceller)?;
                    return Ok(result);
                }
                Err(mpsc::RecvTimeoutError::Timeout) => {
                    phase += 1;
                    self.running = Some((index, phase));
                    self.collect_output(&output_rx);
                    self.take_password_request();
                    self.redraw(terminal)?;
                    self.drain_events_while_running(canceller)?;
                }
                Err(mpsc::RecvTimeoutError::Disconnected) => {
                    return Ok(Err(io::Error::other("the worker thread died unexpectedly")));
                }
            }
        }
    }
}

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

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

    #[test]
    fn requests_are_taken_only_while_a_run_is() {
        let (requests_tx, requests_rx) = mpsc::channel();
        let queue = Mutex::new(PasswordQueue {
            accepting: false,
            requests: requests_tx,
        });
        let ask = || {
            let (reply, _answer) = mpsc::channel();
            PasswordRequest {
                prompt: "Password:".to_string(),
                reply,
            }
        };
        let alive = || false;
        // Between runs: refused, and nothing queued.
        assert_eq!(PasswordQueue::submit(&queue, ask(), &alive), None);
        assert!(requests_rx.try_recv().is_err());
        // During a run: queued.
        PasswordQueue::lock(&queue).accepting = true;
        assert_eq!(PasswordQueue::submit(&queue, ask(), &alive), Some(()));
        assert!(requests_rx.try_recv().is_ok());
        // Still during a run, but the request's own run is over: it was on its
        // way while the queue was closed for its run and opened for the next.
        assert_eq!(PasswordQueue::submit(&queue, ask(), &|| true), None);
        assert!(requests_rx.try_recv().is_err());
        // After the run: refused again.
        PasswordQueue::lock(&queue).accepting = false;
        assert_eq!(PasswordQueue::submit(&queue, ask(), &alive), None);
        assert!(requests_rx.try_recv().is_err());
    }

    #[test]
    fn the_end_of_a_run_declines_the_prompt_shown_and_the_ones_still_queued() {
        let (requests_tx, requests_rx) = mpsc::channel();
        let ask = |prompt: &str| {
            let (reply, answer) = mpsc::channel();
            (
                PasswordRequest {
                    prompt: prompt.to_string(),
                    reply,
                },
                answer,
            )
        };
        let (shown, shown_answer) = ask("shown");
        let mut shown = Some(PasswordPrompt {
            request: shown,
            typed: "half-typ".to_string(),
        });
        // Arrived after the last tick: never shown, still in the queue.
        let (queued, queued_answer) = ask("queued");
        requests_tx.send(queued).unwrap();
        let (later, later_answer) = ask("later");
        requests_tx.send(later).unwrap();

        decline_prompts(&mut shown, &requests_rx);

        assert!(shown.is_none());
        assert_eq!(shown_answer.try_recv(), Ok(None));
        assert_eq!(queued_answer.try_recv(), Ok(None));
        assert_eq!(later_answer.try_recv(), Ok(None));
        assert!(requests_rx.try_recv().is_err());
    }

    #[test]
    fn recognises_the_documented_quit_keys() {
        assert!(is_quit_key(key(KeyCode::Char('q'), KeyModifiers::NONE)));
        assert!(is_quit_key(key(KeyCode::Esc, KeyModifiers::NONE)));
        assert!(is_quit_key(key(KeyCode::Char('c'), KeyModifiers::CONTROL)));
    }

    #[test]
    fn a_cell_that_already_ran_says_so() {
        assert_eq!(run_label(true).trim(), "Re-run");
        assert_eq!(run_label(false).trim(), "Run");
        // Equal widths keep the markers aligned down the column.
        assert_eq!(run_label(true).len(), run_label(false).len());
    }

    #[test]
    fn a_cell_that_has_not_run_in_this_session_looks_untouched() {
        // A result from an earlier session is not a run of this one: reopening a
        // document that was run yesterday must not colour every cell as done.
        assert_eq!(cell_state(0, None, None), CellState::Waiting);
    }

    #[test]
    fn the_cell_being_run_is_told_apart_from_the_ones_already_run() {
        assert_eq!(cell_state(1, Some(1), None), CellState::Running);
        assert_eq!(cell_state(1, Some(1), Some(true)), CellState::Running);
        assert_eq!(cell_state(0, Some(1), Some(true)), CellState::Done);
        assert_eq!(cell_state(0, Some(1), Some(false)), CellState::Failed);
    }

    #[test]
    fn every_state_has_a_colour_of_its_own() {
        // The colour is the whole signal, so two states sharing one would make them
        // indistinguishable on screen.
        let colors = [
            marker_color(CellState::Waiting),
            marker_color(CellState::Running),
            marker_color(CellState::Done),
            marker_color(CellState::Failed),
        ];
        for (index, color) in colors.iter().enumerate() {
            assert!(
                !colors[index + 1..].contains(color),
                "two states share {color:?}"
            );
        }
    }

    #[test]
    fn a_finished_cell_is_dimmed_and_the_rest_are_not() {
        assert_eq!(command_style(CellState::Waiting), Style::default());
        assert_eq!(command_style(CellState::Running), Style::default());
        assert_ne!(command_style(CellState::Done), Style::default());
        assert_ne!(command_style(CellState::Failed), Style::default());
    }

    #[test]
    fn keys_go_into_the_password_prompt() {
        assert_eq!(
            prompt_key(key(KeyCode::Char('q'), KeyModifiers::NONE)),
            PromptKey::Type('q')
        );
        assert_eq!(
            prompt_key(key(KeyCode::Char('Q'), KeyModifiers::SHIFT)),
            PromptKey::Type('Q')
        );
        assert_eq!(
            prompt_key(key(KeyCode::Enter, KeyModifiers::NONE)),
            PromptKey::Send
        );
        assert_eq!(
            prompt_key(key(KeyCode::Esc, KeyModifiers::NONE)),
            PromptKey::Decline
        );
        assert_eq!(
            prompt_key(key(KeyCode::Backspace, KeyModifiers::NONE)),
            PromptKey::Erase
        );
        // A control chord is not a character of the password.
        assert_eq!(
            prompt_key(key(KeyCode::Char('u'), KeyModifiers::CONTROL)),
            PromptKey::Ignore
        );
    }

    #[test]
    fn a_plain_c_is_not_a_quit_key() {
        assert!(!is_quit_key(key(KeyCode::Char('c'), KeyModifiers::NONE)));
        assert!(!is_quit_key(key(KeyCode::Char('r'), KeyModifiers::NONE)));
        assert!(!is_quit_key(key(KeyCode::Char('a'), KeyModifiers::NONE)));
    }
}