marver 0.0.6

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
//! 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.
//!
//! # 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;

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::{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 to wait for input before redrawing anyway.
///
/// 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);

/// 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,
}

/// 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; cleared on the next key.
    pub status: &'a mut String,
}

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

/// 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
    }
}

/// 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: String,
    quit: bool,
}

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

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

    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.clone();
        let (view, mut ctx) = self.split();
        view.render(frame, body, &mut ctx);

        frame.render_widget(footer_line(&hints, &status, depth), footer);
    }

    /// 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();

        let (view, mut ctx) = self.split();
        let action = match view.handle_key(key, &mut ctx) {
            Ok(action) => action,
            Err(err) => {
                self.status = 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) {
        let (view, mut ctx) = self.split();
        if let Err(err) = view.tick(&mut ctx) {
            *ctx.status = err.to_string();
        }
    }
}

fn footer_line<'a>(hints: &[(&'a str, &'a str)], status: &'a str, depth: usize) -> Paragraph<'a> {
    if !status.is_empty() {
        return Paragraph::new(Line::from(Span::styled(
            format!(" {status}"),
            Style::default().fg(Color::Yellow),
        )));
    }
    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<()> {
    while !app.should_quit() {
        terminal.draw(|frame| app.render(frame))?;

        if event::poll(TICK)? {
            match event::read()? {
                Event::Key(key) => app.handle_key(key),
                // A resize redraws on the next pass; nothing else to do.
                Event::Resize(_, _) => {}
                _ => {}
            }
        }
        app.tick();
    }
    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 = String::new();
        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()
    }

    /// 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 = String::new();
        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_line_replaces_the_key_hints_and_clears_on_the_next_key() {
        let mut app = app();
        app.status = "something happened".into();
        let screen = render_app(&mut app, 60, 10);
        assert!(screen.last().unwrap().contains("something happened"));

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

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