marver 0.0.27

A TUI workspace for AI agent sessions: tmux orchestration, git worktree management, and repo control in one place.
Documentation
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
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
//! The terminal interface.
//!
//! Every screen is a [`View`]: `render`, `handle_key`, `tick`. The app owns a
//! stack of them and talks only to the top one. The TUI opens the daemon's
//! SQLite database directly; only the hook path uses the socket.
//!
//! Key contract, kept by every view:
//!
//! - `esc` leaves the screen — except [`task::TaskView`], where it goes to the
//!   agent.
//! - `ctrl-q` leaves everywhere, including there.
//! - `ctrl-c` leaves, or drops the text being typed if a field is open. No
//!   other chord is a binding.
//! - `x` discards, `c` commits.

pub mod filter;
pub mod new_task;
pub mod repos;
pub mod review;
pub mod task;
pub mod tasks;
pub mod todos;

use std::io::{Stdout, stdout};
use std::time::{Duration, Instant};

use ratatui::Frame;
use ratatui::crossterm::event::{
    self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEvent, KeyEventKind,
    KeyModifiers, MouseEvent, MouseEventKind,
};
use ratatui::crossterm::execute;
use ratatui::crossterm::terminal::{
    EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
};
use ratatui::layout::{Alignment, Constraint, Layout, Rect};
use ratatui::prelude::CrosstermBackend;
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::Paragraph;

use crate::daemon::Config;
use crate::domain::TaskState;
use crate::store::Store;

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error(transparent)]
    Io(#[from] std::io::Error),
    #[error(transparent)]
    Store(#[from] crate::store::Error),
    #[error(transparent)]
    Review(#[from] crate::review::Error),
    #[error(transparent)]
    Tmux(#[from] crate::tmux::Error),
    #[error(transparent)]
    Archive(#[from] crate::archive::Error),
}

pub type Result<T> = std::result::Result<T, Error>;

/// How long the loop may sleep when nothing on screen is live.
pub const TICK: Duration = Duration::from_millis(250);

/// How long the loop may sleep when a view is showing a live terminal.
pub const LIVE_TICK: Duration = Duration::from_millis(8);

/// How long the loop may sleep while a live screen is actually moving.
pub const BUSY_TICK: Duration = Duration::from_millis(1);

/// How long after the last movement the loop keeps looking at [`BUSY_TICK`].
pub const BUSY_WINDOW: Duration = Duration::from_millis(250);

/// The shortest gap between two draws.
pub const MIN_FRAME: Duration = Duration::from_millis(16);

/// What a view wants to happen after a key.
pub enum Action {
    /// Stay where we are.
    None,
    /// Open a view on top of this one.
    Push(Box<dyn View>),
    /// Close this view, revealing the one beneath.
    Pop,
    Quit,
}

/// How long a status message stays on screen when nothing else happens.
pub const STATUS_TTL: Duration = Duration::from_millis(500);

/// The footer message, and when it appeared.
#[derive(Debug, Default)]
pub struct Status {
    text: String,
    shown_at: Option<Instant>,
}

impl Status {
    pub fn say(&mut self, message: impl Into<String>) {
        self.text = message.into();
        self.shown_at = Some(Instant::now());
    }

    pub fn clear(&mut self) {
        self.text.clear();
        self.shown_at = None;
    }

    pub fn text(&self) -> &str {
        &self.text
    }

    pub fn is_empty(&self) -> bool {
        self.text.is_empty()
    }

    /// Drop the message once it has been up long enough to have been read.
    pub fn expire(&mut self, ttl: Duration) {
        if self.shown_at.is_some_and(|shown| shown.elapsed() >= ttl) {
            self.clear();
        }
    }
}

/// What a view is given to work with.
pub struct Context<'a> {
    pub store: &'a mut Store,
    pub config: &'a Config,
    /// One line shown at the bottom; replaced by the next key, and expired by
    /// [`STATUS_TTL`] when there is no next key.
    pub status: &'a mut Status,
}

impl Context<'_> {
    pub fn say(&mut self, message: impl Into<String>) {
        self.status.say(message);
    }
}

/// One screen.
pub trait View {
    /// Shown in the header.
    fn title(&self) -> String;

    fn render(&mut self, frame: &mut Frame, area: Rect, ctx: &mut Context);

    fn handle_key(&mut self, key: KeyEvent, ctx: &mut Context) -> Result<Action>;

    /// A wheel notch. Moving the selection is right for a list, so that is the
    /// default and only the screens showing something taller than themselves —
    /// the agent's terminal, a diff — override it.
    fn handle_mouse(&mut self, mouse: MouseEvent, ctx: &mut Context) -> Result<Action> {
        let code = match mouse.kind {
            MouseEventKind::ScrollUp => KeyCode::Up,
            MouseEventKind::ScrollDown => KeyCode::Down,
            // Clicks and drags are reported because asking for the wheel asks
            // for all of it; marver has nothing to do with them.
            _ => return Ok(Action::None),
        };
        self.handle_key(KeyEvent::new(code, KeyModifiers::NONE), ctx)
    }

    /// Called every [`TICK`], whether or not a key arrived.
    fn tick(&mut self, _ctx: &mut Context) -> Result<()> {
        Ok(())
    }

    /// Key hints for the footer, as `(keys, what it does)`.
    fn keys(&self) -> Vec<(&'static str, &'static str)> {
        Vec::new()
    }

    /// Whether this view wants raw keys, suppressing global bindings.
    fn captures_input(&self) -> bool {
        false
    }

    /// How long the event loop may sleep before calling [`View::tick`] again.
    fn poll_interval(&self) -> Duration {
        TICK
    }

    /// Whether anything has changed since the last render.
    fn dirty(&self) -> bool {
        true
    }
}

/// How much detail any one task gets to show before it is cut.
pub const DETAIL_WORDS: usize = 8;

/// The first `words` words of `text`, marked when there were more.
pub fn first_words(text: &str, words: usize) -> String {
    // `split_whitespace` is also what flattens embedded newlines and runs of
    // spaces, so the caller cannot be handed something that breaks the layout.
    let mut taken: Vec<&str> = text.split_whitespace().take(words).collect();
    let more = text.split_whitespace().nth(words).is_some();
    if taken.is_empty() {
        return String::new();
    }
    if more {
        taken.push("");
    }
    taken.join(" ")
}

/// `1 worktree`, `2 worktrees`, `2 branches`. For counts that appear in a
/// sentence.
pub fn plural(count: usize, noun: &str) -> String {
    if count == 1 {
        return format!("1 {noun}");
    }
    let ending = if noun.ends_with('h') { "es" } else { "s" };
    format!("{count} {noun}{ending}")
}

/// A colour per state, used everywhere a state is shown.
pub fn state_style(state: TaskState) -> Style {
    let colour = match state {
        TaskState::Queued => Color::DarkGray,
        TaskState::Running => Color::Cyan,
        TaskState::Blocked => Color::Yellow,
        TaskState::AwaitingReview => Color::Green,
        // Set aside on purpose, so it reads as quiet rather than as trouble.
        TaskState::Paused => Color::Magenta,
        TaskState::Committed => Color::Blue,
        TaskState::Failed => Color::Red,
        TaskState::Cancelled => Color::DarkGray,
    };
    Style::default().fg(colour)
}

pub struct App {
    store: Store,
    config: Config,
    views: Vec<Box<dyn View>>,
    status: Status,
    quit: bool,
    /// Set by anything the views cannot see: a key, a resize, the stack
    /// moving, a status message appearing or ageing out.
    dirty: bool,
}

impl App {
    pub fn new(store: Store, config: Config) -> Self {
        Self {
            store,
            config,
            views: vec![Box::new(tasks::TasksView::new())],
            status: Status::default(),
            quit: false,
            dirty: true,
        }
    }

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

    /// How long the loop may sleep before looking again.
    pub fn poll_interval(&self) -> Duration {
        self.views.last().map_or(TICK, |view| view.poll_interval())
    }

    /// Something happened that the next frame has to show.
    pub fn mark_dirty(&mut self) {
        self.dirty = true;
    }

    /// Whether a frame is owed, clearing the app's own half of the answer.
    pub fn take_dirty(&mut self) -> bool {
        let owed = self.dirty || self.views.last().is_some_and(|view| view.dirty());
        self.dirty = false;
        owed
    }

    pub fn depth(&self) -> usize {
        self.views.len()
    }

    /// Borrow the store and the top view at once.
    fn split(&mut self) -> (&mut Box<dyn View>, Context<'_>) {
        let view = self.views.last_mut().expect("the stack is never empty");
        (
            view,
            Context {
                store: &mut self.store,
                config: &self.config,
                status: &mut self.status,
            },
        )
    }

    pub fn render(&mut self, frame: &mut Frame) {
        let area = frame.area();
        let [header, body, footer] = Layout::vertical([
            Constraint::Length(1),
            Constraint::Min(1),
            Constraint::Length(1),
        ])
        .areas(area);

        let title = self.views.last().map(|v| v.title()).unwrap_or_default();
        let depth = self.views.len();
        frame.render_widget(
            Paragraph::new(Line::from(vec![
                Span::styled(
                    " marver ",
                    Style::default()
                        .fg(Color::Black)
                        .bg(Color::Magenta)
                        .add_modifier(Modifier::BOLD),
                ),
                Span::raw(" "),
                Span::styled(title, Style::default().add_modifier(Modifier::BOLD)),
            ])),
            header,
        );

        let hints: Vec<(&str, &str)> = self.views.last().map(|v| v.keys()).unwrap_or_default();
        let status = self.status.text().to_string();
        let (view, mut ctx) = self.split();
        view.render(frame, body, &mut ctx);

        let [keys, corner] = footer_split(footer, &status);
        frame.render_widget(footer_line(&hints, depth), keys);
        if !status.is_empty() {
            frame.render_widget(status_line(&status), corner);
        }
    }

    /// Route a wheel notch to the top view.
    pub fn handle_mouse(&mut self, mouse: MouseEvent) {
        // Same rule as a key: what the last one said has been read by now.
        let had_status = !self.status.is_empty();
        self.status.clear();
        self.dirty |= had_status;

        let (view, mut ctx) = self.split();
        match view.handle_mouse(mouse, &mut ctx) {
            Ok(action) => self.apply(action),
            Err(err) => {
                self.status.say(err.to_string());
                self.dirty = true;
            }
        }
    }

    /// Route a key to the top view.
    pub fn handle_key(&mut self, key: KeyEvent) {
        // Terminals that report releases would otherwise act on every key
        // twice.
        if key.kind == KeyEventKind::Release {
            return;
        }
        // A key is not itself a reason to draw — what it *did* is, and the
        // view it went to is what knows that.
        let had_status = !self.status.is_empty();
        self.status.clear();
        self.dirty |= had_status;

        let (view, mut ctx) = self.split();
        let action = match view.handle_key(key, &mut ctx) {
            Ok(action) => action,
            Err(err) => {
                self.status.say(err.to_string());
                self.dirty = true;
                return;
            }
        };
        // Anything the view said in passing is new text on screen.
        self.dirty |= !self.status.is_empty();

        self.apply(action);
    }

    /// Do what a view asked for.
    fn apply(&mut self, action: Action) {
        match action {
            Action::None => {}
            // The stack moving is a different screen, whatever the view
            // thinks.
            Action::Push(view) => {
                self.views.push(view);
                self.dirty = true;
            }
            Action::Pop => {
                // Never pop the last view; there would be nothing to draw.
                if self.views.len() > 1 {
                    self.views.pop();
                    self.dirty = true;
                } else {
                    self.quit = true;
                }
            }
            Action::Quit => self.quit = true,
        }
    }

    /// Infallible for the same reason as [`App::handle_key`], and more so: a
    /// tick fires four times a second, so a transient tmux failure would end
    /// the session without the user having touched anything.
    pub fn tick(&mut self) {
        // Before the view runs, so a message it sets this tick gets its full
        // time on screen rather than being aged by the same pass that wrote
        // it.
        let had_status = !self.status.is_empty();
        self.status.expire(STATUS_TTL);
        if had_status && self.status.is_empty() {
            self.dirty = true;
        }

        let (view, mut ctx) = self.split();
        if let Err(err) = view.tick(&mut ctx) {
            ctx.status.say(err.to_string());
        }
    }
}

/// Split the footer into the key hints and the corner the status sits in.
fn footer_split(area: Rect, status: &str) -> [Rect; 2] {
    if status.is_empty() {
        return [area, Rect::new(area.x, area.y, 0, area.height)];
    }
    // One space either side, and never more than the footer has to give.
    let width = (status.chars().count() as u16 + 2).min(area.width);
    Layout::horizontal([Constraint::Min(0), Constraint::Length(width)]).areas(area)
}

fn status_line(status: &str) -> Paragraph<'_> {
    Paragraph::new(Line::from(Span::styled(
        format!("{status} "),
        Style::default().fg(Color::Yellow),
    )))
    .alignment(Alignment::Right)
}

fn footer_line<'a>(hints: &[(&'a str, &'a str)], depth: usize) -> Paragraph<'a> {
    let mut spans = Vec::new();
    for (keys, what) in hints {
        spans.push(Span::styled(
            format!(" {keys}"),
            Style::default()
                .fg(Color::Magenta)
                .add_modifier(Modifier::BOLD),
        ));
        spans.push(Span::styled(
            format!(" {what} "),
            Style::default().fg(Color::DarkGray),
        ));
    }
    if depth > 1 {
        spans.push(Span::styled(
            format!(" · depth {depth}"),
            Style::default().fg(Color::DarkGray),
        ));
    }
    Paragraph::new(Line::from(spans))
}

type Term = ratatui::Terminal<CrosstermBackend<Stdout>>;

/// Take over the terminal.
fn enter() -> Result<Term> {
    enable_raw_mode()?;
    let mut out = stdout();
    // Asking for the wheel means asking for the whole mouse, so drag-to-select
    // now needs shift (option on macOS) held.
    execute!(out, EnterAlternateScreen, EnableMouseCapture)?;
    Ok(ratatui::Terminal::new(CrosstermBackend::new(out))?)
}

/// Hand the terminal back. Called even on error, or the user's shell is left
/// in raw mode with no echo.
fn leave(terminal: &mut Term) -> Result<()> {
    disable_raw_mode()?;
    execute!(
        terminal.backend_mut(),
        DisableMouseCapture,
        LeaveAlternateScreen
    )?;
    terminal.show_cursor()?;
    Ok(())
}

/// Run the interface until the user quits.
pub fn run(store: Store, config: Config) -> Result<()> {
    let mut terminal = enter()?;
    let result = event_loop(&mut terminal, App::new(store, config));
    // Restore first, so a panic message or error is readable.
    let restored = leave(&mut terminal);
    result.and(restored)
}

fn event_loop(terminal: &mut Term, mut app: App) -> Result<()> {
    // Once up front, so there is something on screen before the first event.
    terminal.draw(|frame| app.render(frame))?;
    let mut drawn = Instant::now();

    // When something last moved, which decides how hard the loop is looking.
    let mut stirred = Instant::now();

    // A frame that is owed but has not been drawn yet, because the last one was
    // too recent, carried across iterations so the wait below can be cut short
    // for it.
    let mut owed = false;

    while !app.should_quit() {
        // The interval belongs to the view on top: only it knows whether
        // anything behind it is moving.
        let wait = poll_wait(
            owed,
            drawn.elapsed(),
            app.poll_interval(),
            busy_floor(&app, stirred),
        );
        if event::poll(wait)? {
            match event::read()? {
                Event::Key(key) => {
                    app.handle_key(key);
                    stirred = Instant::now();
                }
                Event::Mouse(mouse) => {
                    app.handle_mouse(mouse);
                    stirred = Instant::now();
                }
                Event::Resize(_, _) => app.mark_dirty(),
                _ => {}
            }
        }
        app.tick();

        // Asked every pass, so the app's flag is consumed rather than left to
        // accumulate behind the rate limit.
        owed |= app.take_dirty();

        // Drawing is what costs; looking is nearly free.
        if owed && drawn.elapsed() >= MIN_FRAME {
            terminal.draw(|frame| app.render(frame))?;
            drawn = Instant::now();
            owed = false;
            // A frame with something new in it is the other kind of movement:
            // an agent producing steadily keeps the loop at BUSY_TICK without
            // anyone touching the keyboard.
            stirred = drawn;
        }
    }
    Ok(())
}

/// How long the loop may wait before looking again. With a frame owed, only
/// until the rate limit allows it, so a key that lands within [`MIN_FRAME`] of
/// the last draw does not wait out the whole poll interval.
fn poll_wait(owed: bool, since_draw: Duration, interval: Duration, floor: Duration) -> Duration {
    if owed {
        MIN_FRAME.saturating_sub(since_draw)
    } else {
        interval.min(floor)
    }
}

/// The fastest the loop will look, given how recently anything moved.
fn busy_floor(app: &App, stirred: Instant) -> Duration {
    if app.poll_interval() <= LIVE_TICK && stirred.elapsed() < BUSY_WINDOW {
        BUSY_TICK
    } else {
        TICK
    }
}

#[cfg(test)]
pub(crate) mod testing {
    use super::*;
    use ratatui::Terminal;
    use ratatui::backend::TestBackend;

    /// Render a view and return the screen as lines of text.
    pub fn render_view(
        view: &mut dyn View,
        store: &mut Store,
        width: u16,
        height: u16,
    ) -> Vec<String> {
        let config = Config::new("/tmp/marver-test", "/tmp");
        let mut status = Status::default();
        let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
        terminal
            .draw(|frame| {
                let mut ctx = Context {
                    store,
                    config: &config,
                    status: &mut status,
                };
                view.render(frame, frame.area(), &mut ctx);
            })
            .unwrap();
        buffer_lines(terminal.backend().buffer(), width, height)
    }

    /// Render the whole app, chrome included.
    pub fn render_app(app: &mut App, width: u16, height: u16) -> Vec<String> {
        let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
        terminal.draw(|frame| app.render(frame)).unwrap();
        buffer_lines(terminal.backend().buffer(), width, height)
    }

    fn buffer_lines(buffer: &ratatui::buffer::Buffer, width: u16, height: u16) -> Vec<String> {
        (0..height)
            .map(|y| {
                (0..width)
                    .map(|x| buffer[(x, y)].symbol().to_string())
                    .collect::<String>()
                    .trim_end()
                    .to_string()
            })
            .collect()
    }

    /// Build a `Context` the way the app does, and hand it to `f`.
    pub fn with_context<T>(store: &mut Store, f: impl FnOnce(&mut Context) -> T) -> T {
        let config = Config::new("/tmp/marver-test", "/tmp");
        let mut status = Status::default();
        let mut ctx = Context {
            store,
            config: &config,
            status: &mut status,
        };
        f(&mut ctx)
    }

    /// Tick a view outside the app, as the event loop would.
    pub fn tick_view(view: &mut dyn View, store: &mut Store) {
        with_context(store, |ctx| view.tick(ctx).expect("tick"));
    }

    /// Feed a key to a view outside the app, returning what it asked for.
    pub fn press(view: &mut dyn View, store: &mut Store, key: KeyEvent) -> Action {
        with_context(store, |ctx| view.handle_key(key, ctx).unwrap())
    }

    /// Turn the wheel one notch at a view.
    pub fn wheel(view: &mut dyn View, store: &mut Store, up: bool) -> Action {
        let kind = if up {
            MouseEventKind::ScrollUp
        } else {
            MouseEventKind::ScrollDown
        };
        let mouse = MouseEvent {
            kind,
            column: 0,
            row: 0,
            modifiers: KeyModifiers::NONE,
        };
        with_context(store, |ctx| view.handle_mouse(mouse, ctx).unwrap())
    }
}

#[cfg(test)]
mod tests {
    use super::testing::*;
    use super::*;
    use ratatui::crossterm::event::{KeyCode, KeyEventState, KeyModifiers};

    fn store() -> Store {
        Store::open_in_memory().unwrap()
    }

    fn app() -> App {
        App::new(store(), Config::new("/tmp/marver-test", "/tmp"))
    }

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

    #[test]
    fn counts_are_pluralised_including_the_nouns_that_take_es() {
        assert_eq!(plural(1, "worktree"), "1 worktree");
        assert_eq!(plural(0, "worktree"), "0 worktrees");
        assert_eq!(plural(1, "branch"), "1 branch");
        assert_eq!(plural(2, "branch"), "2 branches", "not `2 branchs`");
    }

    #[test]
    fn a_wheel_notch_clears_the_last_status_line_as_a_key_would() {
        // Otherwise a message said about the previous action outlives it and
        // reads as a report on what the wheel just did.
        let mut app = app();
        app.status.say("removed 1 worktree");

        app.handle_mouse(MouseEvent {
            kind: MouseEventKind::ScrollDown,
            column: 0,
            row: 0,
            modifiers: KeyModifiers::NONE,
        });

        assert!(app.status.is_empty());
    }

    #[test]
    fn a_frame_held_back_by_the_rate_limit_is_waited_for_and_not_slept_through() {
        // A key pressed 5ms after a draw cannot be drawn for another 11ms. The
        // loop must wait those 11ms, not the poll interval — this is a quarter
        // of a second of lag on every screen that is not the agent's.
        let wait = poll_wait(true, Duration::from_millis(5), TICK, TICK);

        assert_eq!(wait, Duration::from_millis(11));
    }

    #[test]
    fn a_frame_that_is_already_due_is_not_waited_for_at_all() {
        let wait = poll_wait(true, Duration::from_millis(40), TICK, TICK);
        assert_eq!(wait, Duration::ZERO);
    }

    #[test]
    fn with_nothing_owed_the_loop_sleeps_as_long_as_the_view_allows() {
        // Or a screen that reports itself dirty every pass — most of them —
        // would redraw at the frame rate instead of four times a second.
        assert_eq!(
            poll_wait(false, Duration::from_millis(40), TICK, TICK),
            TICK
        );
        assert_eq!(
            poll_wait(false, Duration::from_millis(40), LIVE_TICK, BUSY_TICK),
            BUSY_TICK,
            "a live pane still gets the busy floor"
        );
    }

    struct Dummy;

    impl View for Dummy {
        fn title(&self) -> String {
            "dummy".into()
        }
        fn render(&mut self, frame: &mut Frame, area: Rect, _: &mut Context) {
            frame.render_widget(Paragraph::new("DUMMY BODY"), area);
        }
        fn handle_key(&mut self, _: KeyEvent, _: &mut Context) -> Result<Action> {
            Ok(Action::Pop)
        }
    }

    /// A screen with something live behind it: polled fast, and the only judge
    /// of whether it needs redrawing. [`task::TaskView`] is the real one.
    struct Live {
        says: Option<&'static str>,
    }

    impl View for Live {
        fn title(&self) -> String {
            "live".into()
        }
        fn render(&mut self, _: &mut Frame, _: Rect, _: &mut Context) {}
        fn handle_key(&mut self, _: KeyEvent, ctx: &mut Context) -> Result<Action> {
            if let Some(message) = self.says {
                ctx.say(message);
            }
            Ok(Action::None)
        }
        fn poll_interval(&self) -> Duration {
            LIVE_TICK
        }
        fn dirty(&self) -> bool {
            false
        }
    }

    #[test]
    fn a_key_a_live_screen_swallows_does_not_cost_a_frame() {
        // The keystroke goes to the agent and marver draws nothing for it; the
        // echo, a millisecond later, is what there is to draw.
        let mut app = app();
        app.views.push(Box::new(Live { says: None }));
        app.take_dirty();

        app.handle_key(key(KeyCode::Char('a')));

        assert!(
            !app.take_dirty(),
            "a forwarded key owes no frame of its own"
        );
    }

    #[test]
    fn but_anything_it_changes_does() {
        let mut app = app();
        app.views.push(Box::new(Live { says: Some("sent") }));
        app.take_dirty();
        app.handle_key(key(KeyCode::Char('a')));
        assert!(app.take_dirty(), "a message it left is new text on screen");

        // And the message going away again is equally a change.
        app.status.say("still here");
        app.views.pop();
        app.views.push(Box::new(Live { says: None }));
        app.take_dirty();
        app.handle_key(key(KeyCode::Char('a')));
        assert!(app.take_dirty(), "clearing the status line is a change too");
    }

    #[test]
    fn the_stack_moving_always_costs_a_frame() {
        // Whatever the view underneath believes about its own dirtiness, it is
        // not the screen that was just on show.
        let mut app = app();
        app.views.push(Box::new(Live { says: None }));
        app.take_dirty();

        app.handle_key(key(KeyCode::Char('x'))); // Live returns None
        assert!(!app.take_dirty());

        app.views.push(Box::new(Dummy)); // Dummy pops on any key
        app.take_dirty();
        app.handle_key(key(KeyCode::Char('x')));
        assert!(app.take_dirty(), "popping revealed a different screen");
    }

    #[test]
    fn the_loop_looks_harder_only_while_a_live_screen_is_moving() {
        let mut app = app();
        let long_ago = Instant::now() - BUSY_WINDOW - Duration::from_millis(1);

        // The task list: nothing behind it, so nothing to look harder for.
        assert_eq!(app.poll_interval(), TICK);
        assert_eq!(busy_floor(&app, Instant::now()), TICK);

        app.views.push(Box::new(Live { says: None }));
        assert_eq!(app.poll_interval(), LIVE_TICK);
        assert_eq!(
            busy_floor(&app, Instant::now()),
            BUSY_TICK,
            "something moved just now"
        );
        assert_eq!(
            app.poll_interval().min(busy_floor(&app, long_ago)),
            LIVE_TICK,
            "and a screen left alone goes back to the quiet rate"
        );
    }

    /// A view whose every operation fails, the way git and tmux really do.
    struct Broken;

    impl View for Broken {
        fn title(&self) -> String {
            "broken".into()
        }
        fn render(&mut self, _: &mut Frame, _: Rect, _: &mut Context) {}
        fn handle_key(&mut self, _: KeyEvent, _: &mut Context) -> Result<Action> {
            Err(Error::Review(crate::review::Error::NothingStaged))
        }
        fn tick(&mut self, _: &mut Context) -> Result<()> {
            Err(Error::Review(crate::review::Error::NothingStaged))
        }
    }

    #[test]
    fn a_view_error_is_reported_rather_than_ending_the_session() {
        // A reaped worktree or a flaky tmux call is an everyday event.
        let mut app = app();
        app.views.push(Box::new(Broken));

        app.handle_key(key(KeyCode::Char('a')));
        assert!(!app.should_quit(), "a git error must not end the session");
        assert_eq!(app.depth(), 2, "the stack must survive");
        assert!(!app.status.is_empty(), "and the user must be told");

        let screen = render_app(&mut app, 60, 10);
        assert!(
            screen.last().unwrap().contains("nothing is staged"),
            "the failure belongs in the status line: {screen:?}"
        );
    }

    #[test]
    fn a_failing_tick_is_reported_rather_than_ending_the_session() {
        // Ticks fire four times a second, so this one would end the session
        // without the user having touched anything.
        let mut app = app();
        app.views.push(Box::new(Broken));
        app.tick();
        assert!(!app.should_quit());
        assert!(!app.status.is_empty());
    }

    #[test]
    fn the_app_starts_on_the_task_list() {
        let mut app = app();
        assert_eq!(app.depth(), 1);
        let screen = render_app(&mut app, 60, 10);
        assert!(screen[0].contains("marver"), "{screen:?}");
        assert!(screen[0].contains("Tasks"), "{screen:?}");
    }

    #[test]
    fn pushing_and_popping_moves_between_views() {
        let mut app = app();
        app.views.push(Box::new(Dummy));
        assert_eq!(app.depth(), 2);

        let screen = render_app(&mut app, 60, 10);
        assert!(
            screen.iter().any(|l| l.contains("DUMMY BODY")),
            "{screen:?}"
        );
        assert!(
            screen.last().unwrap().contains("depth 2"),
            "the footer should show how deep we are: {screen:?}"
        );

        // Dummy pops on any key.
        app.handle_key(key(KeyCode::Char('x')));
        assert_eq!(app.depth(), 1);
        assert!(!app.should_quit());
    }

    #[test]
    fn popping_the_last_view_quits_rather_than_leaving_nothing() {
        let mut app = app();
        app.views.clear();
        app.views.push(Box::new(Dummy));
        app.handle_key(key(KeyCode::Char('x')));
        assert!(
            app.should_quit(),
            "an empty stack would have nothing to draw"
        );
    }

    #[test]
    fn key_releases_are_ignored() {
        let mut app = app();
        app.views.push(Box::new(Dummy));
        let release = KeyEvent::new_with_kind_and_state(
            KeyCode::Char('x'),
            KeyModifiers::NONE,
            KeyEventKind::Release,
            KeyEventState::NONE,
        );
        app.handle_key(release);
        assert_eq!(
            app.depth(),
            2,
            "a release must not act twice with the press"
        );
    }

    #[test]
    fn the_status_sits_in_the_corner_without_taking_the_keymap_away() {
        let mut app = app();
        app.status.say("refreshed");
        let footer = render_app(&mut app, 60, 10).last().unwrap().clone();

        assert!(footer.contains("refreshed"), "{footer:?}");
        assert!(
            footer.contains("new"),
            "the keys must survive being spoken over: {footer:?}"
        );
        // Right-hand corner, so nothing on the left shifts when it appears.
        let keys = footer.find("new").expect("hints");
        let said = footer.find("refreshed").expect("status");
        assert!(
            said > keys,
            "the status belongs after the hints: {footer:?}"
        );

        app.handle_key(key(KeyCode::Esc));
        assert!(app.status.is_empty(), "a stale message must not linger");
    }

    #[test]
    fn a_long_status_cannot_push_the_footer_off_screen() {
        let mut app = app();
        app.status.say("x".repeat(500));
        let screen = render_app(&mut app, 40, 8);
        assert_eq!(
            screen.last().unwrap().chars().count(),
            screen.last().unwrap().trim_end().chars().count(),
            "no wrapping past the footer's one line"
        );
        assert_eq!(screen.len(), 8, "the layout still has exactly one footer");
    }

    #[test]
    fn a_status_message_expires_on_its_own() {
        // Nothing clears the footer when the user simply watches: `r` left
        // "refreshed" sitting under a list that had refreshed many times
        // since.
        let mut app = app();
        app.status.say("refreshed");

        app.tick();
        assert!(
            !app.status.is_empty(),
            "it must survive long enough to be read"
        );

        // Ageing is by elapsed time, so a zero lifetime is the honest way to
        // reach the far side of it without sleeping.
        app.status.expire(Duration::ZERO);
        assert!(app.status.is_empty(), "a message with no next key must go");

        let footer = render_app(&mut app, 60, 10).last().unwrap().clone();
        assert!(
            !footer.contains("refreshed"),
            "the corner empties again: {footer:?}"
        );
        assert!(footer.contains("new"), "and the hints stay put: {footer:?}");
    }

    #[test]
    fn the_status_lifetime_is_short_enough_to_stay_out_of_the_way() {
        // Half a second, and expiry lands on the event loop's tick — so this
        // is a floor, not a ceiling.
        assert!(STATUS_TTL <= Duration::from_millis(500));
        assert!(
            STATUS_TTL >= TICK,
            "shorter than a tick would never be seen"
        );
    }

    #[test]
    fn an_expiry_only_starts_when_something_is_said() {
        let mut status = Status::default();
        status.expire(Duration::ZERO);
        assert!(status.is_empty(), "expiring nothing is harmless");

        status.say("hello");
        status.expire(Duration::from_secs(60));
        assert_eq!(status.text(), "hello", "it is nowhere near due");
    }

    #[test]
    fn detail_is_cut_by_words_and_says_when_it_was() {
        assert_eq!(first_words("short enough", 8), "short enough");
        assert_eq!(first_words("", 8), "", "nothing in, nothing out");
        assert_eq!(first_words("   ", 8), "", "and whitespace is nothing");

        let long = "one two three four five six seven eight nine ten";
        let cut = first_words(long, 8);
        assert_eq!(cut, "one two three four five six seven eight …");
        assert!(!cut.contains("nine"), "{cut:?}");
    }

    #[test]
    fn a_detail_with_newlines_stays_one_line() {
        // A blocked reason is whatever Claude Code said, and a row that
        // becomes three rows takes the whole table's alignment with it.
        let cut = first_words("first line\nsecond line\n\nfourth", 20);
        assert_eq!(cut, "first line second line fourth");
        assert!(!cut.contains('\n'));
    }

    #[test]
    fn cutting_never_leaves_a_dangling_marker() {
        // Exactly at the limit is not "there is more".
        assert_eq!(first_words("one two three", 3), "one two three");
        assert_eq!(first_words("one two three four", 3), "one two three …");
    }

    #[test]
    fn ctrl_q_leaves_every_screen() {
        // The one binding that has to mean the same thing everywhere.
        use crate::tui::{new_task::NewTaskView, review::ReviewView, tasks::TasksView};

        let mut store = store();
        let chord = KeyEvent::new(KeyCode::Char('q'), KeyModifiers::CONTROL);

        let mut list = TasksView::new();
        assert!(
            matches!(press(&mut list, &mut store, chord), Action::Quit),
            "the root has nothing under it, so leaving is quitting"
        );

        // The text fields are the interesting ones: they take almost every key
        // as input, and would otherwise type a `q`.
        let mut new_task = NewTaskView::new();
        assert!(matches!(
            press(&mut new_task, &mut store, chord),
            Action::Pop
        ));

        let mut review = ReviewView::new(1);
        assert!(matches!(press(&mut review, &mut store, chord), Action::Pop));
    }

    #[test]
    fn esc_leaves_every_screen_that_is_not_the_agents() {
        // The rule the README states first.
        use crate::tui::{new_task::NewTaskView, review::ReviewView, tasks::TasksView};

        let mut store = store();
        let esc = key(KeyCode::Esc);

        let mut list = TasksView::new();
        assert!(matches!(press(&mut list, &mut store, esc), Action::Quit));

        let mut new_task = NewTaskView::new();
        assert!(matches!(press(&mut new_task, &mut store, esc), Action::Pop));

        let mut review = ReviewView::new(1);
        assert!(matches!(press(&mut review, &mut store, esc), Action::Pop));
    }

    #[test]
    fn c_never_destroys_and_x_never_commits() {
        // The overlap that started this: `c` cancelled on one screen and
        // committed on another.
        use crate::tui::{review::ReviewView, tasks::TasksView};

        let list = TasksView::new();
        let hints = list.keys();
        assert!(
            hints.iter().any(|(k, what)| *k == "x" && *what == "cancel"),
            "the list should offer x to cancel: {hints:?}"
        );
        assert!(
            !hints.iter().any(|(k, _)| *k == "c"),
            "and should not bind c at all: {hints:?}"
        );

        let review = ReviewView::new(1);
        let hints = review.keys();
        assert!(hints.iter().any(|(k, what)| *k == "c" && *what == "commit"));
        assert!(hints.iter().any(|(k, what)| *k == "x" && *what == "reject"));
    }

    #[test]
    fn every_screen_advertises_how_to_leave_it() {
        // A footer that does not say how to get out is how a screen becomes a
        // trap, which the agent's terminal briefly was.
        use crate::tui::{
            new_task::NewTaskView, repos::ReposView, review::ReviewView, tasks::TasksView,
        };

        let screens: Vec<(&str, Vec<(&str, &str)>)> = vec![
            ("tasks", TasksView::new().keys()),
            ("new task", NewTaskView::new().keys()),
            ("review", ReviewView::new(1).keys()),
            ("agent", crate::tui::task::TaskView::new(1).keys()),
            ("repos", ReposView::new().keys()),
        ];
        for (name, hints) in screens {
            assert!(
                hints
                    .iter()
                    .any(|(k, _)| k.contains("esc") || k.contains('q')),
                "{name} does not say how to leave: {hints:?}"
            );
        }
    }

    #[test]
    fn every_state_has_a_distinct_enough_colour() {
        use std::collections::HashSet;
        let colours: HashSet<_> = TaskState::ALL
            .iter()
            .map(|s| format!("{:?}", state_style(*s).fg))
            .collect();
        // Queued and Cancelled deliberately share grey; everything else
        // differs.
        assert_eq!(colours.len(), TaskState::ALL.len() - 1);
    }
}