marver 0.0.16

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
//! The terminal interface.
//!
//! # The extensibility seam
//!
//! Everything on screen is a [`View`]: `render`, `handle_key`, `tick`. The app
//! owns a stack of them and only ever talks to the top one. Configurable panes
//! are deferred, but they arrive as more `View` implementations and a layout
//! that renders several at once — not as a rewrite of this file.
//!
//! # Keys
//!
//! Three rules every view is expected to keep, because a keymap that is learnt
//! once and then contradicted is worse than one that was never guessed at:
//!
//! - **`esc` leaves the screen.** The one exception is [`task::TaskView`], where
//!   `esc` belongs to the agent — it is how Claude is interrupted.
//! - **`ctrl-q` leaves the screen, everywhere, including there.** It is the
//!   single answer to "how do I get out of this", and it arrives in every
//!   terminal: raw mode clears `IXON`, so nothing upstream takes it for flow
//!   control.
//! - **`x` discards and `c` commits.** They used to overlap — `c` cancelled a
//!   task on one screen and committed on another — and muscle memory does not
//!   stop at the edge of a screen.
//!
//! [`View::keys`] is what puts a screen's own bindings in the footer. The whole
//! set is written out in the README.
//!
//! # Talking to the daemon
//!
//! The TUI opens the same SQLite database the daemon does, rather than asking it
//! over a socket. WAL mode allows concurrent readers alongside one writer, and
//! `busy_timeout` covers the contended moments, so two processes on one local
//! file is a supported arrangement rather than a workaround.
//!
//! This is a deliberate departure from `ARCHITECTURE.md` §3, which describes the
//! TUI as a socket client. A protocol becomes necessary the moment the TUI and
//! daemon stop sharing a filesystem — viewing tasks from another machine is the
//! obvious case. Until then it would be a lot of machinery to reach a file that
//! is already right there.

pub mod new_task;
pub mod review;
pub mod task;
pub mod tasks;

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

use ratatui::Frame;
use ratatui::crossterm::event::{self, Event, KeyEvent, KeyEventKind};
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),
}

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

/// How long the loop may sleep when nothing on screen is live.
///
/// Also the refresh rate for daemon-side changes, since nothing pushes them
/// here — a task moving to `awaiting-review` becomes visible within this.
pub const TICK: Duration = Duration::from_millis(250);

/// How long the loop may sleep when a view is showing a live terminal.
///
/// `event::poll` watches stdin and nothing else, while a pane's output arrives
/// on a channel from the control client's reader thread. At [`TICK`] the loop
/// was therefore asleep when the echo of a keystroke came back, so every
/// character appeared up to a quarter of a second after it was typed.
///
/// This is only how often the loop *looks*. What it draws is decided by
/// [`View::dirty`], so a quiet pane costs one `poll` per interval and nothing
/// else.
pub const LIVE_TICK: Duration = Duration::from_millis(8);

/// The shortest gap between two draws.
///
/// A busy agent can produce output faster than anyone can read it, and redrawing
/// per chunk would spend the whole budget on frames nobody sees. Bounding the
/// rate keeps the worst case at one frame of latency, which is not perceptible,
/// while leaving the common case — a keystroke echoing back — immediate.
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.
///
/// Long enough to register, short enough to stay out of the way. Without an
/// expiry the last thing said sat there for ever — pressing `r` left
/// "refreshed" over a list that had been refreshed many times since, which is
/// worse than saying nothing.
///
/// Note this is a floor, not a ceiling: ageing happens on the event loop's
/// tick, so a message on a screen polled at [`TICK`] lasts until the first tick
/// past this.
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>;

    /// 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.
    ///
    /// Text fields and the embedded terminal set this: `q` must type a `q`
    /// rather than quitting.
    fn captures_input(&self) -> bool {
        false
    }

    /// How long the event loop may sleep before calling [`View::tick`] again.
    ///
    /// A view with something live behind it — a pane whose output arrives on a
    /// channel the loop cannot wait on — asks for [`LIVE_TICK`]. Everything else
    /// takes the default, because a task list changes when the daemon changes it
    /// and a quarter of a second is soon enough to hear about that.
    fn poll_interval(&self) -> Duration {
        TICK
    }

    /// Whether anything has changed since the last render.
    ///
    /// Defaults to yes, which is the old unconditional behaviour and right for
    /// any view cheap enough to redraw at [`TICK`]. A view that asks to be
    /// polled quickly should override it, or the faster poll becomes a faster
    /// redraw of a screen that has not moved.
    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.
///
/// Detail is free text from git, tmux, or Claude Code, and a blocked reason can
/// be a paragraph with newlines in it. Two things follow, and this handles both:
/// a row must not become several rows, and every row should be about the same
/// size so the column reads as a column.
///
/// Cut by words rather than by columns because the result is read, not measured:
/// half a word tells you less than the whole one it came from.
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(" ")
}

/// 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,
        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.
    ///
    /// The view's half is cleared by its own `render`, which is the only place
    /// that can honestly say the screen now matches the view.
    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.
    ///
    /// Split manually because a view needs `&mut Store` while it is itself
    /// borrowed from `self`; they are disjoint fields, but the compiler needs
    /// to be shown that.
    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 key to the top view.
    ///
    /// Infallible by design. A view's errors are the everyday failures of git,
    /// tmux, and the filesystem — a worktree the daemon reaped, a flaky
    /// subprocess. Propagating them here would end the session and discard the
    /// stack, so they are reported in the status line instead. Only terminal
    /// I/O, which the event loop owns, can stop the interface.
    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;
        }
        self.status.clear();
        // Whatever the key does, the frame after it differs from the one before.
        self.dirty = true;

        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());
                return;
            }
        };

        match action {
            Action::None => {}
            Action::Push(view) => self.views.push(view),
            Action::Pop => {
                // Never pop the last view; there would be nothing to draw.
                if self.views.len() > 1 {
                    self.views.pop();
                } 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.
///
/// The status used to replace the hints outright, so saying anything at all
/// took the keymap off the screen. Given its own column on the right it can
/// appear and go without the rest of the footer moving.
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();
    execute!(out, EnterAlternateScreen)?;
    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(), 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();

    while !app.should_quit() {
        // The interval belongs to the view on top: only it knows whether
        // anything behind it is moving.
        if event::poll(app.poll_interval())? {
            match event::read()? {
                Event::Key(key) => app.handle_key(key),
                Event::Resize(_, _) => app.mark_dirty(),
                _ => {}
            }
        }
        app.tick();

        // Drawing is what costs; looking is nearly free. Separating them is what
        // lets a live pane be polled at 8ms without redrawing 125 times a second
        // for a screen that has not changed.
        // The gate is tested first and `&&` short-circuits, so a change that
        // arrives inside the frame window stays owed rather than being taken and
        // dropped — otherwise the last chunk before a pane fell quiet would
        // never be drawn at all.
        if drawn.elapsed() >= MIN_FRAME && app.take_dirty() {
            terminal.draw(|frame| app.render(frame))?;
            drawn = Instant::now();
        }
    }
    Ok(())
}

#[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()
    }

    /// Tick a view outside the app, as the event loop would.
    pub fn tick_view(view: &mut dyn View, store: &mut Store) {
        let config = Config::new("/tmp/marver-test", "/tmp");
        let mut status = Status::default();
        let mut ctx = Context {
            store,
            config: &config,
            status: &mut status,
        };
        view.tick(&mut 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 {
        let config = Config::new("/tmp/marver-test", "/tmp");
        let mut status = Status::default();
        let mut ctx = Context {
            store,
            config: &config,
            status: &mut status,
        };
        view.handle_key(key, &mut 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)
    }

    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 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. Before
        // this, `v` then `a` on a queued task exited the process from the home
        // screen, discarding the stack.
        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. `esc`
        // cannot, because the agent's terminal needs it, so this is what makes
        // "how do I get out of here" have a single answer.
        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. The agent's screen is the one
        // exception, and it is an exception because Claude needs `esc`.
        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. Whatever `c` does now, it is not destructive,
        // and the footers must agree with that.
        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, 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()),
        ];
        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);
    }
}