plannotator-tui 0.15.0

Annotate Markdown in the terminal - standalone, and as a Herdr plugin.
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
//! `plannotator-tui review`: a git diff in the terminal, with notes the person sends to a
//! coding agent, the way a document review sends them.
//!
//! The data side (capture, notes, anchoring, the record, the feedback text) is the
//! `plannotator-tui-review` crate; the diff itself is drawn by diffs-rs (`diff`). This
//! module tree is the screen between them, parallel to the document review in `app/`, and
//! it reuses that review's pieces from `ui/`, `delivery`, `archive` and `keys`.
//!
//! - `mod.rs`: the screen's state and the operations that change notes.
//! - [`diff`]: the diffs-rs engine, in this app's terms.
//! - [`files`]: the changed files on the left, and filtering them.
//! - [`notes`]: the rail's order and wording.
//! - [`drafts`]: making, editing and removing notes.
//! - [`herdr`]: `plannotator-tui herdr review`. [`scope`]: what it shares with `rex review`
//!   and `hc review`, and the pane they open.
//! - [`input`]: keys and the mouse; [`mouse`]: clicks and drags in the diff. [`draw`],
//!   [`header`], [`footer`], [`rail`] and [`overlays`]: the frame; [`compose_at`]: where the
//!   comment box opens; [`inline`]: notes drawn in the diff. [`divider`]: dragging the lines between the panes and between a split
//!   diff's sides.
//! - [`settings`]: how the diff is drawn (`[review]`), its menu, and remembering the choices.
//! - [`send`]: send, resend, finish and undo. [`pi`]: the Pi link.
//! - [`pick`]: the change picker (`p`, `review --pick`): what to review, and switching to it.
//! - [`watch`]: noticing that the diff changed on disk, for the footer.
//! - [`whole`]: the whole-file view (`o`, `O`), a second diffs-rs engine.
//! - [`post`]: posting the notes to the pull request on GitHub, after a summary
//!   ([`post_view`] draws it).
//! - [`cli`]: `plannotator-tui review [--staged | --unstaged | --base REF | --commit SHA | PR |
//!   --pick] [DIR]`.
//!
//! A pull request review (`PR` is a GitHub link, `N` or `#N`) fetches the PR with the
//! person's `gh` login into their clone or a cache repository ([`capture`]), and sends to the
//! agent as any review does. It can also post the notes to the PR as one GitHub review
//! ([`post`]), only after the person confirms a summary of what it posts.

pub(crate) mod cli;
mod compose_at;
mod diff;
mod divider;
mod drafts;
mod draw;
mod exit;
mod files;
mod footer;
mod header;
pub(crate) mod herdr;
mod inline;
mod input;
mod jump;
mod mouse;
mod notes;
mod overlays;
mod pi;
pub(crate) mod pick;
mod post;
mod post_view;
mod rail;
pub(crate) mod scope;
mod send;
pub(crate) mod settings;
#[cfg(test)]
mod tests;
mod viewed;
mod watch;
mod whole;

use std::path::{Path, PathBuf};
use std::sync::mpsc::SyncSender;
use std::time::Instant;

use anyhow::{Context as _, Result};
use plannotator_tui_review::{Capture, FilePatch, Progress, Repo, ReviewStore, Status};
use ratatui::layout::Rect;
use ratatui::style::Style;

use crate::delivery::Delivery;
use crate::keys::Keymap;
use crate::notes_rail::{NotesRail, RailStart};
use crate::theme::palette;
use crate::ui::agent_picker::{AgentPicker, Reach};
use crate::ui::compose::Compose;
use crate::ui::send_button::SendState;
use diff::{Diff, Lines};

/// What the comment box is writing.
#[derive(Debug, Clone, PartialEq, Eq)]
enum Draft {
    /// A comment on lines.
    Comment(Lines),
    /// Replacement code for new-side lines.
    Suggestion(Lines),
    /// A comment on a whole file.
    File(String),
    /// A comment on the whole change, on no file.
    Change,
    /// A comment on new-side lines outside every hunk, made in the whole file, with the code
    /// it quotes.
    Outside(Lines, String),
    /// A new body for an existing note, by id.
    Edit(String),
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum Mode {
    Browse,
    Compose(Draft),
    /// Quit was asked for while notes are unsent; the footer asks first.
    ConfirmQuit,
    /// The Review menu, with its highlighted row.
    Menu(usize),
    PickTarget,
    Help,
    /// Go to definition's list: which identifier, or which answer.
    Pick(jump::Pick),
    /// Typing the file list's name filter.
    FilterFiles,
    /// The kind picker, with its highlighted row.
    Kinds(usize),
    /// The diff settings menu, with its highlighted row.
    Settings(usize),
    /// The summary before a post to GitHub.
    Post(post::Confirm),
}

/// Which pane keys go to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Focus {
    Diff,
    Notes,
    Files,
}

/// Where things were drawn last frame, for the mouse.
#[derive(Debug, Default, Clone)]
struct Geometry {
    /// The whole frame: a mouse report outside it is ignored (`ui::drag::on_screen`).
    screen: Rect,
    diff: Rect,
    rail: Rect,
    /// The file list; empty while it is hidden.
    files: Rect,
    /// The file list's rows drawn last frame: their screen row and key.
    file_rows: Vec<(u16, String)>,
    send_button: Option<Rect>,
    review_button: Option<Rect>,
    settings_button: Option<Rect>,
    /// The layout switch's two halves: `true` for Split.
    layout_switch: Vec<(Rect, bool)>,
    wrap_switch: Option<Rect>,
    /// The `no ws` chip, while whitespace changes are hidden.
    whitespace_chip: Option<Rect>,
    /// Rail bubbles drawn last frame, with their note's index.
    bubbles: Vec<(Rect, usize)>,
    menu_rows: Vec<(Rect, usize)>,
    /// The settings menu's rows, and the whole box.
    settings_rows: Vec<(Rect, usize)>,
    settings_box: Option<Rect>,
    /// The buttons of the toolbar beside a mouse selection, and the whole bar.
    toolbar: Vec<(Rect, crate::keys::Action)>,
    toolbar_bar: Option<Rect>,
    /// The notes' boxes drawn in the diff last frame, with their ids.
    boxes: Vec<(Rect, u64)>,
    /// The columns the comment box wrapped to last frame; 0 before its first.
    compose_wrap: usize,
    /// Where the comment box drew its text, and the first of the text's rows shown there.
    compose_text: Option<(Rect, usize)>,
}

/// The review screen.
#[allow(
    clippy::struct_excessive_bools,
    reason = "independent toggles and requests, none of them a state machine"
)]
pub(crate) struct Screen {
    repo: Repo,
    capture: Capture,
    diff: Diff,
    store: ReviewStore,
    /// Viewed marks, shared with the browser app (`viewed`).
    progress: Progress,
    data_dir: PathBuf,
    project: String,
    delivery: Box<dyn Delivery>,
    /// The target the review started with, while Send goes to an agent picked instead.
    start_delivery: Option<Box<dyn Delivery>>,
    picker: AgentPicker,
    /// Where the picker looks for agents, and whether Send asks which one first.
    reach: Reach,
    /// What to send once the picker that Send opened has a choice.
    pick_then: Option<send::PickThen>,
    pi_link: Option<crate::pi::link::Link>,
    keys: Keymap,
    /// Whether the terminal reports Shift+Enter distinctly; the comment box's hint says so.
    shift_enter: bool,
    /// Copy to the terminal clipboard when a send cannot reach the agent (off headless).
    clipboard: bool,
    /// `[ui] copy_on_select`: whether a mouse selection is copied on release.
    on_release: mouse::OnRelease,
    mode: Mode,
    focus: Focus,
    /// The selected note, by its position in the rail's order.
    rail_cursor: usize,
    /// First rail row drawn.
    rail_scroll: usize,
    /// Whether the rail shows: `[ui] notes_rail`, the last session's choice, `toggle-notes`.
    /// A note saved or removed never opens or closes it.
    notes_rail: NotesRail,
    /// The changed files on the left, and their filter.
    files: files::FileList,
    /// The notes drawn in the diff, when the Notes setting says so.
    inline: inline::Inline,
    compose: Compose,
    /// The side of its lines the open comment box took.
    compose_at: Option<compose_at::Placed>,
    send_state: SendState,
    last_send: crate::ui::send_button::LastSend,
    /// What `undo-finish` takes back, the last first: a finish, or a removed note.
    undo: Vec<send::Undo>,
    /// The undo histories of the reviews switched away from in this session, by their
    /// record's path, for when they are back.
    undos: std::collections::HashMap<PathBuf, Vec<send::Undo>>,
    status: Option<String>,
    geometry: Geometry,
    /// A drag with the left button in the diff, until the release.
    drag: Option<mouse::Drag>,
    /// The line the last drag's selection grew from, for a shift-click.
    grown: Option<mouse::Grown>,
    /// The toolbar beside the lines a drag selected, until the next key or click.
    toolbar: Option<mouse::Toolbar>,
    /// The lines between the panes, and the notes panel's width.
    dividers: divider::Dividers,
    /// How the diff is drawn: `[review]`, as changed since.
    settings: settings::Settings,
    /// Whether the diff changed on disk since the last capture.
    watch: watch::Watch,
    /// The last key or paste, so no disk check starts while the person types.
    last_key: Option<Instant>,
    /// The whole-file view, while it is open over the diff.
    whole: Option<whole::Whole>,
    /// The event loop's wake channel, for the whole-file view's engine and the agent finder.
    wake: SyncSender<()>,
    /// Go to definition: the search under way, and the places to go back to.
    nav: jump::Nav,
    /// The key help's scroll, and how far it can scroll at the size drawn last.
    help_scroll: usize,
    help_room: std::cell::Cell<usize>,
    /// `pick-changes` was pressed: the event loop opens the change picker over the review.
    pick_request: bool,
    /// The other reviews this session showed, for the notes left unsent on them.
    switched: pick::shown::Switched,
    /// A `gh` call for the post summary under way: the PR check, or the post.
    post_job: Option<post::Job>,
    quit: bool,
}

impl std::fmt::Debug for Screen {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Screen")
            .field("root", &self.capture.root)
            .field("scope", &self.capture.scope)
            .finish_non_exhaustive()
    }
}

impl Screen {
    /// Open the review of `capture` with the default settings, remembering none.
    #[cfg(test)]
    pub(crate) fn open(
        repo: Repo,
        capture: Capture,
        data_dir: &Path,
        delivery: Box<dyn Delivery>,
        wake: SyncSender<()>,
    ) -> Result<Self> {
        Self::open_with(repo, capture, data_dir, delivery, wake, settings::Settings::default())
    }

    /// Open the review of `capture`: load its notes, place them on this diff, and start the
    /// viewer as `settings` say. `wake` is the event loop's: the viewer sends on it when it
    /// has work ready.
    pub(crate) fn open_with(
        repo: Repo,
        capture: Capture,
        data_dir: &Path,
        delivery: Box<dyn Delivery>,
        wake: SyncSender<()>,
        settings: settings::Settings,
    ) -> Result<Self> {
        let (project, owner) = capture.record_owner();
        let store = ReviewStore::load(data_dir, &project, &owner, &capture.scope)?;
        let light = crate::theme::theme() == crate::theme::Theme::Light;
        let watch = watch::Watch::start(&capture.scope, wake.clone());
        let order = files::tree::order(&capture.files.iter().map(|f| f.path.as_str()).collect::<Vec<_>>());
        let paths: Vec<String> =
            order.into_iter().filter_map(|i| capture.files.get(i).map(|f| f.path.clone())).collect();
        let diff = Diff::open(&capture, &paths, settings.now, light, wake.clone())?;
        let progress = Progress::open(&capture, data_dir, viewed::saving(data_dir));
        let mut screen = Self {
            repo,
            capture,
            diff,
            store,
            progress,
            data_dir: data_dir.to_path_buf(),
            project,
            delivery,
            start_delivery: None,
            picker: AgentPicker::default(),
            reach: Reach::default(),
            pick_then: None,
            pi_link: None,
            keys: Keymap::default(),
            shift_enter: false,
            clipboard: false,
            on_release: mouse::OnRelease::Copy,
            mode: Mode::Browse,
            focus: Focus::Diff,
            rail_cursor: 0,
            rail_scroll: 0,
            notes_rail: NotesRail::default(),
            files: files::FileList::default(),
            inline: inline::Inline::new(settings.now.notes),
            compose: Compose::default(),
            compose_at: None,
            send_state: SendState::Ready,
            last_send: crate::ui::send_button::LastSend::None,
            undo: Vec::new(),
            undos: std::collections::HashMap::new(),
            status: None,
            geometry: Geometry::default(),
            drag: None,
            grown: None,
            toolbar: None,
            dividers: divider::Dividers::default(),
            settings,
            watch,
            last_key: None,
            whole: None,
            wake,
            nav: jump::Nav::default(),
            help_scroll: 0,
            help_room: std::cell::Cell::new(0),
            pick_request: false,
            switched: pick::shown::Switched::default(),
            post_job: None,
            quit: false,
        };
        screen.notes_rail.settle(!screen.store.annotations().is_empty());
        screen.files_for_capture();
        let placed = screen.place_notes()?;
        // What placing the notes found, and a remembered settings file that could not be read.
        screen.status = match (placed, screen.settings.take_notice()) {
            (Some(placed), Some(notice)) => Some(format!("{placed} \u{b7} {notice}")),
            (placed, notice) => placed.or(notice),
        };
        screen.derive_send_state();
        Ok(screen)
    }

    /// Say `notice` in the footer ahead of what it says already, as the review opens.
    pub(crate) fn add_notice(&mut self, notice: String) {
        self.status = Some(match self.status.take() {
            Some(status) => format!("{notice} \u{b7} {status}"),
            None => notice,
        });
    }

    pub(crate) fn set_keys(&mut self, keys: Keymap, shift_enter: bool) {
        self.keys = keys;
        self.shift_enter = shift_enter;
    }

    /// Start the notes rail as the last session left it, else as `[ui] notes_rail` says.
    /// `when-notes` is decided by the notes the review opens with: saving a note never
    /// opens the rail (`NotesRail::settle`).
    pub(crate) fn start_notes_rail(&mut self, start: RailStart) {
        self.notes_rail = NotesRail::load(start, &self.data_dir);
        self.notes_rail.settle(!self.store.annotations().is_empty());
    }

    /// Whether the rail is shown, width allowing. Hidden, notes keep their gutter marks.
    /// With notes inline only, it shows once opened by hand, for the session.
    fn rail_shown(&self) -> bool {
        if self.settings.now.notes == crate::config::review::Notes::Inline {
            return self.inline.rail;
        }
        self.notes_rail.shown(!self.store.annotations().is_empty())
    }

    /// `toggle-notes`: close the rail, or open it again, and remember which. The next frame
    /// gives the diff the rail's columns, or takes them back, and the viewer reflows as on a
    /// resize. With notes inline only, it opens or closes for the session.
    fn toggle_notes(&mut self) {
        if self.settings.now.notes == crate::config::review::Notes::Inline {
            self.inline.rail = !self.inline.rail;
            self.after_rail_change(Ok(()));
            return;
        }
        let remembered = self.notes_rail.toggle(!self.store.annotations().is_empty(), &self.data_dir);
        self.after_rail_change(remembered);
    }

    /// Moving the focus to the notes opens a closed rail.
    fn reveal_notes(&mut self) {
        if self.settings.now.notes == crate::config::review::Notes::Inline {
            self.inline.rail = true;
            return;
        }
        let remembered = self.notes_rail.reveal(!self.store.annotations().is_empty(), &self.data_dir);
        self.after_rail_change(remembered);
    }

    fn after_rail_change(&mut self, remembered: Result<()>) {
        if let Err(error) = remembered {
            self.status = Some(format!("{error:#}"));
        }
        if !self.rail_shown() && self.focus == Focus::Notes {
            self.focus = Focus::Diff;
        }
    }

    pub(crate) fn enable_clipboard(&mut self) {
        self.clipboard = true;
    }

    /// `[ui] copy_on_select`: off, a mouse selection waits for `y` to be copied.
    pub(crate) fn set_copy_on_select(&mut self, on: bool) {
        self.on_release = if on { mouse::OnRelease::Copy } else { mouse::OnRelease::Wait };
    }

    pub(crate) fn wants_quit(&self) -> bool {
        self.quit
    }

    /// Whether `pick-changes` was pressed since the last call.
    pub(crate) fn take_pick_request(&mut self) -> bool {
        std::mem::take(&mut self.pick_request)
    }

    /// Take what the viewers, the Pi link, the disk watch and the agent finder have ready, and
    /// scroll for a drag held past the diff's edge.
    /// True when the screen changed.
    pub(crate) fn tick(&mut self) -> Result<bool> {
        let mut changed = false;
        // A setting the viewer could not take yet (before its first file or frame) now.
        self.apply_settings()?;
        if self.diff.poll(&self.capture)? {
            self.sync_markers();
            changed = true;
        }
        changed |= self.show_pending_file()?;
        changed |= self.take_attributes()?;
        changed |= self.poll_pi();
        changed |= self.poll_search()?;
        changed |= self.poll_post();
        let typing = matches!(self.mode, Mode::Compose(_))
            || self.last_key.is_some_and(|at| at.elapsed() < watch::QUIET_AFTER_KEY);
        changed |= self.watch.poll(&self.repo, &self.capture.scope, !typing);
        if let Some(whole) = &mut self.whole
            && whole.poll(&self.capture)?
        {
            self.sync_whole_markers();
            changed = true;
        }
        changed |= self.reach.poll();
        changed |= self.step_at_edge(Instant::now())?;
        let whole_draw = self.whole.as_ref().is_some_and(whole::Whole::needs_draw);
        Ok(changed || self.diff.needs_draw() || whole_draw)
    }

    /// After a frame. True when the keys already waiting should be dropped: the post
    /// summary just came on screen, and they were typed before it.
    pub(crate) fn after_draw(&mut self) -> bool {
        self.diff.after_draw();
        if let Some(whole) = &mut self.whole {
            whole.after_draw();
        }
        self.post_shown()
    }

    /// Stop the viewer's workers. Call it once the loop ends, so their errors are reported.
    pub(crate) fn close(&mut self) -> Result<()> {
        let whole = self.whole.as_mut().map_or(Ok(()), whole::Whole::close);
        self.diff.close().and(whole)
    }

    /// Resolve every note against the current capture and save where they are now. Returns
    /// what moved or went outdated, for the footer.
    fn place_notes(&mut self) -> Result<Option<String>> {
        let resolutions = self.capture.resolve_all(self.store.annotations())?;
        self.store.apply(&resolutions)?;
        let count = |status| self.store.annotations().iter().filter(|n| n.status() == Some(status)).count();
        let (moved, outdated) = (count(Status::Moved), count(Status::Outdated));
        let mut parts = Vec::new();
        if moved > 0 {
            parts.push(format!("{moved} moved"));
        }
        if outdated > 0 {
            parts.push(format!("{outdated} outdated"));
        }
        Ok((!parts.is_empty()).then(|| format!("notes: {}", parts.join(" · "))))
    }

    /// Recapture the diff (`r`): notes follow their lines, the ones whose code is gone move
    /// to Outdated. A capture that fails leaves the review as it was.
    fn reload(&mut self) -> Result<()> {
        let captured = {
            let _no_check_meanwhile = self.watch.hold_git();
            self.repo.capture(&self.capture.scope)
        };
        let capture = match captured {
            Ok(capture) => capture,
            Err(err) => {
                self.status = Some(format!("reload failed: {err}"));
                return Ok(());
            }
        };
        self.watch.recaptured();
        self.progress = self.progress.reopen(&capture, &self.data_dir);
        self.capture = capture;
        self.files_for_capture();
        self.diff.replace(&self.capture, self.files.shown())?;
        self.files.retarget();
        let placed = self.place_notes()?;
        // The whole file is read again too, at the line it was on.
        if let Some(whole) = &self.whole {
            let (path, version, line) =
                (whole.path.clone(), whole.version, whole.target()?.map(|(first, _)| first));
            self.show_whole(&path, version, line);
        }
        self.clamp_rail_cursor();
        self.sync_markers();
        self.derive_send_state();
        let empty = if self.capture.is_empty() { " · no changes left" } else { "" };
        self.status =
            Some(format!("reloaded{empty}{}", placed.map(|p| format!(" · {p}")).unwrap_or_default()));
        Ok(())
    }

    /// The gutter markers: unsent notes in the comment colour, sent ones dimmed. Outdated
    /// notes and notes off the diff have none.
    fn sync_markers(&mut self) {
        let unsent = Style::new().fg(palette().comment);
        let sent = Style::new().fg(ratatui::style::Color::DarkGray);
        let marks: Vec<(Lines, Style)> = self
            .store
            .annotations()
            .iter()
            .filter(|note| notes::in_diff(note))
            .map(|note| {
                let lines = Lines {
                    path: note.file_path.clone(),
                    side: note.side,
                    first: note.line_start,
                    last: note.line_end,
                };
                (lines, if self.store.is_pending(note) { unsent } else { sent })
            })
            .chain(
                self.whole
                    .is_none()
                    .then(|| self.drag.as_ref().and_then(mouse::Drag::lines))
                    .flatten()
                    .map(|lines| (lines, mouse::drag_mark())),
            )
            .collect();
        if let Err(err) = self.diff.set_markers(&marks) {
            self.status = Some(format!("could not mark notes in the diff: {err:#}"));
        }
        self.sync_boxes();
        self.sync_whole_markers();
    }

    fn file(&self, path: &str) -> Option<&FilePatch> {
        self.capture.file(path)
    }

    fn after_note_change(&mut self) {
        self.clamp_rail_cursor();
        self.sync_markers();
        self.derive_send_state();
    }

    fn derive_send_state(&mut self) {
        self.send_state = if self.store.all_delivered() { SendState::Sent } else { SendState::Ready };
    }

    /// The repository root as Pi and the feedback name it: for a pull request fetched into
    /// the cache, the folder the review was opened in.
    fn root(&self) -> &Path {
        self.repo.workdir()
    }

    /// The repository folder's name, for the footer; a pull request's `owner/repo`.
    fn repo_name(&self) -> String {
        if let Some(pull) = &self.capture.pull {
            return pull.view.repo.slug();
        }
        self.root()
            .file_name()
            .map_or_else(|| self.root().display().to_string(), |n| n.to_string_lossy().into())
    }
}

/// Open a review of `dir` for `request` and fail before any screen opens when there is
/// nothing to show: `No uncommitted changes in app`. A pull request is fetched with `gh`
/// into `dir`'s clone of its repository, else into a bare cache repository under the data
/// dir (`clients/plannotator-tui/pulls/<host>/<owner>/<repo>.git`).
#[cfg(test)]
pub(crate) fn capture(dir: &Path, request: &plannotator_tui_review::Request) -> Result<(Repo, Capture)> {
    let (repo, capture) = capture_any(dir, request)?;
    match nothing_to_review(&repo, &capture) {
        Some(nothing) => anyhow::bail!(nothing),
        None => Ok((repo, capture)),
    }
}

/// [`capture`], empty or not.
pub(crate) fn capture_any(dir: &Path, request: &plannotator_tui_review::Request) -> Result<(Repo, Capture)> {
    use plannotator_tui_review::{Gh, Request};
    if let Request::PullRequest { pr } = request {
        let cache = crate::workspace_paths::data_dir().join("clients").join("plannotator-tui").join("pulls");
        return Repo::pull_request(dir, pr, &cache, &Gh::default())
            .with_context(|| format!("reviewing pull request {pr}"));
    }
    let repo = Repo::discover(dir)?;
    let capture = repo.open(request).with_context(|| format!("reviewing {}", repo.root().display()))?;
    Ok((repo, capture))
}

/// A bare review with nothing to show opens the picker instead, once there is a commit to
/// pick: in a repository with none, the picker could only say there is nothing.
pub(crate) fn picks_instead(repo: &Repo) -> bool {
    repo.commits(0, 1).is_ok_and(|commits| !commits.is_empty())
}

/// What to say when `capture` has nothing to show: `No uncommitted changes in app`.
pub(crate) fn nothing_to_review(repo: &Repo, capture: &Capture) -> Option<String> {
    use plannotator_tui_review::Scope;
    if !capture.is_empty() {
        return None;
    }
    let root = repo.root();
    let name = root.file_name().map_or_else(|| root.display().to_string(), |n| n.to_string_lossy().into());
    let what = match &capture.scope {
        Scope::Uncommitted => "uncommitted changes".to_owned(),
        Scope::Staged => "staged changes".to_owned(),
        Scope::Unstaged => "unstaged changes".to_owned(),
        Scope::Branch { base } => format!("changes since {base}"),
        Scope::Commit { sha } => format!("changes in commit {}", sha.get(..7).unwrap_or(sha)),
        Scope::Range { from, to } => {
            format!("changes in commits {}..{}", from.get(..7).unwrap_or(from), to.get(..7).unwrap_or(to))
        }
        Scope::PullRequest { url, .. } => return Some(format!("No changes in {url}")),
    };
    Some(format!("No {what} in {name}"))
}