marver 0.0.9

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
//! The task list: marver's home screen.

use ratatui::Frame;
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::layout::{Constraint, Rect};
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Cell, Paragraph, Row, Table, TableState};

use super::{
    Action, Context, Result, View, new_task::NewTaskView, review::ReviewView, state_style,
    task::TaskView,
};
use crate::domain::{Task, TaskState};
use crate::store::Transition;

pub struct TasksView {
    tasks: Vec<Task>,
    table: TableState,
    /// Hide finished tasks. On by default: the list is a worklist, and old
    /// committed tasks would push live ones off the screen within a day.
    hide_done: bool,
    loaded: bool,
}

impl Default for TasksView {
    fn default() -> Self {
        Self::new()
    }
}

impl TasksView {
    pub fn new() -> Self {
        Self {
            tasks: Vec::new(),
            table: TableState::default().with_selected(Some(0)),
            hide_done: true,
            loaded: false,
        }
    }

    fn reload(&mut self, ctx: &mut Context) -> Result<()> {
        let mut tasks = ctx.store.list_tasks()?;
        if self.hide_done {
            tasks.retain(|t| !matches!(t.state, TaskState::Committed | TaskState::Cancelled));
        }
        // Newest first: the thing you just started is the thing you care about.
        tasks.reverse();

        // Keep the cursor on the same task across a refresh, so a state change
        // elsewhere in the list does not move the selection under the user.
        let selected_id = self.selected().map(|t| t.id);
        self.tasks = tasks;
        let index = selected_id
            .and_then(|id| self.tasks.iter().position(|t| t.id == id))
            .unwrap_or_else(|| self.table.selected().unwrap_or(0));
        self.table
            .select(Some(index.min(self.tasks.len().saturating_sub(1))));
        self.loaded = true;
        Ok(())
    }

    pub fn selected(&self) -> Option<&Task> {
        self.table.selected().and_then(|i| self.tasks.get(i))
    }

    fn move_by(&mut self, delta: isize) {
        if self.tasks.is_empty() {
            return;
        }
        let current = self.table.selected().unwrap_or(0) as isize;
        let last = self.tasks.len() as isize - 1;
        self.table
            .select(Some(current.saturating_add(delta).clamp(0, last) as usize));
    }
}

impl View for TasksView {
    fn title(&self) -> String {
        let shown = self.tasks.len();
        if self.hide_done {
            format!("Tasks ({shown} open)")
        } else {
            format!("Tasks ({shown})")
        }
    }

    fn render(&mut self, frame: &mut Frame, area: Rect, ctx: &mut Context) {
        if !self.loaded {
            let _ = self.reload(ctx);
        }

        if self.tasks.is_empty() {
            frame.render_widget(
                Paragraph::new(vec![
                    Line::from(""),
                    Line::from("  Nothing queued."),
                    Line::from(""),
                    Line::from(Span::styled(
                        "  Press n to describe a task.",
                        Style::default().add_modifier(Modifier::DIM),
                    )),
                ]),
                area,
            );
            return;
        }

        let rows: Vec<Row> = self
            .tasks
            .iter()
            .map(|task| {
                Row::new(vec![
                    Cell::from(format!("{}", task.id)),
                    Cell::from(Span::styled(
                        task.state.as_str().to_string(),
                        state_style(task.state),
                    )),
                    Cell::from(task.title.clone()),
                    Cell::from(detail_for(task)),
                ])
            })
            .collect();

        let table = Table::new(
            rows,
            [
                Constraint::Length(4),
                Constraint::Length(16),
                Constraint::Percentage(40),
                Constraint::Min(10),
            ],
        )
        .header(
            Row::new(vec!["id", "state", "title", "detail"])
                .style(Style::default().add_modifier(Modifier::BOLD | Modifier::DIM)),
        )
        .row_highlight_style(Style::default().add_modifier(Modifier::REVERSED))
        .highlight_symbol("");

        frame.render_stateful_widget(table, area, &mut self.table);
    }

    fn handle_key(&mut self, key: KeyEvent, ctx: &mut Context) -> Result<Action> {
        // Modified keys are not letter bindings. Matching on `code` alone meant
        // ctrl-c -- the universal reflex for "get me out" -- ran the one
        // destructive action on this screen, and the row then vanished from the
        // list because finished tasks are hidden by default.
        if key
            .modifiers
            .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT)
        {
            return Ok(match key.code {
                KeyCode::Char('c') => Action::Quit,
                _ => Action::None,
            });
        }

        match key.code {
            KeyCode::Char('q') => return Ok(Action::Quit),
            KeyCode::Char('n') => return Ok(Action::Push(Box::new(NewTaskView::new()))),
            KeyCode::Char('j') | KeyCode::Down => self.move_by(1),
            KeyCode::Char('k') | KeyCode::Up => self.move_by(-1),
            KeyCode::Char('g') | KeyCode::Home => self.table.select(Some(0)),
            KeyCode::Char('G') | KeyCode::End => {
                self.table.select(Some(self.tasks.len().saturating_sub(1)));
            }
            KeyCode::Char('a') => {
                self.hide_done = !self.hide_done;
                self.reload(ctx)?;
            }
            KeyCode::Char('r') => {
                self.reload(ctx)?;
                ctx.say("refreshed");
            }
            KeyCode::Enter => {
                if let Some(task) = self.selected() {
                    return Ok(Action::Push(Box::new(TaskView::new(task.id))));
                }
            }
            KeyCode::Char('v') => {
                // Review is only meaningful once worktrees exist, which is why
                // it is a separate key rather than what enter does for a task
                // that happens to be finished. A queued task has none, so it
                // gets an explanation rather than an empty screen claiming the
                // agent changed nothing.
                if let Some(task) = self.selected() {
                    if task.state == TaskState::Queued {
                        let id = task.id;
                        ctx.say(format!("task {id} has not started yet"));
                    } else {
                        return Ok(Action::Push(Box::new(ReviewView::new(task.id))));
                    }
                }
            }
            KeyCode::Char('c') => {
                // Cancelling is the one destructive action here, so it is
                // rejected rather than forced when the state disallows it.
                if let Some(task) = self.selected() {
                    let (id, state) = (task.id, task.state);
                    if state.can_transition_to(TaskState::Cancelled) {
                        ctx.store.transition(
                            id,
                            TaskState::Cancelled,
                            Transition::Plain,
                            chrono::Utc::now(),
                        )?;
                        ctx.say(format!("cancelled task {id}"));
                        self.reload(ctx)?;
                    } else {
                        ctx.say(format!("task {id} is already {state}"));
                    }
                }
            }
            _ => {}
        }
        Ok(Action::None)
    }

    fn tick(&mut self, ctx: &mut Context) -> Result<()> {
        // Nothing pushes daemon-side changes here, so the list re-reads itself.
        self.reload(ctx)
    }

    fn keys(&self) -> Vec<(&'static str, &'static str)> {
        vec![
            ("n", "new"),
            ("↵", "open"),
            ("v", "review"),
            ("c", "cancel"),
            ("a", "all"),
            ("r", "refresh"),
            ("q", "quit"),
        ]
    }
}

/// The most useful thing to say about a task in one column.
fn detail_for(task: &Task) -> String {
    match task.state {
        TaskState::Blocked => task
            .blocked_reason
            .clone()
            .or_else(|| task.blocked_kind.map(|k| k.to_string()))
            .unwrap_or_default(),
        TaskState::Failed => task.failure_reason.clone().unwrap_or_default(),
        TaskState::Running => task.session_name.clone().unwrap_or_default(),
        _ => String::new(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::domain::BlockedKind;
    use crate::store::{BlockedInfo, Store};
    use crate::tui::testing::{press, render_view};
    use chrono::{DateTime, Utc};
    use ratatui::crossterm::event::{KeyCode, KeyModifiers};
    use std::path::Path;

    fn at(secs: i64) -> DateTime<Utc> {
        DateTime::from_timestamp(secs, 0).unwrap()
    }

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

    fn store_with(titles: &[&str]) -> (Store, Vec<i64>) {
        let mut store = Store::open_in_memory().unwrap();
        let ids = titles
            .iter()
            .map(|t| {
                store
                    .create_task(t, "p", Path::new("/tmp/tasks"), &[], at(0))
                    .unwrap()
                    .id
            })
            .collect();
        (store, ids)
    }

    #[test]
    fn an_empty_list_says_what_to_do_next() {
        let mut store = Store::open_in_memory().unwrap();
        let mut view = TasksView::new();
        let screen = render_view(&mut view, &mut store, 60, 8);
        assert!(
            screen.iter().any(|l| l.contains("Press n")),
            "an empty screen should not be a dead end: {screen:?}"
        );
    }

    #[test]
    fn tasks_are_listed_newest_first_with_their_state() {
        let (mut store, _) = store_with(&["older", "newer"]);
        let mut view = TasksView::new();
        let screen = render_view(&mut view, &mut store, 70, 8);
        let body: Vec<&String> = screen.iter().filter(|l| !l.is_empty()).collect();

        assert!(body[1].contains("newer"), "{screen:?}");
        assert!(body[2].contains("older"), "{screen:?}");
        assert!(body[1].contains("queued"), "{screen:?}");
    }

    #[test]
    fn a_blocked_task_shows_its_reason_in_the_list() {
        let (mut store, ids) = store_with(&["fix auth"]);
        store
            .transition(ids[0], TaskState::Running, Transition::Plain, at(1))
            .unwrap();
        store
            .transition(
                ids[0],
                TaskState::Blocked,
                Transition::Blocked(BlockedInfo::with_reason(
                    BlockedKind::PermissionPrompt,
                    "edit main.rs",
                )),
                at(2),
            )
            .unwrap();

        let mut view = TasksView::new();
        let screen = render_view(&mut view, &mut store, 80, 8);
        assert!(
            screen.iter().any(|l| l.contains("edit main.rs")),
            "the reason is what makes the row actionable: {screen:?}"
        );
    }

    #[test]
    fn finished_tasks_are_hidden_until_asked_for() {
        let (mut store, ids) = store_with(&["done", "live"]);
        store
            .transition(ids[0], TaskState::Running, Transition::Plain, at(1))
            .unwrap();
        store
            .transition(ids[0], TaskState::AwaitingReview, Transition::Plain, at(2))
            .unwrap();
        store
            .transition(ids[0], TaskState::Committed, Transition::Plain, at(3))
            .unwrap();

        let mut view = TasksView::new();
        let screen = render_view(&mut view, &mut store, 70, 8);
        assert!(!screen.iter().any(|l| l.contains("done")), "{screen:?}");

        press(&mut view, &mut store, key(KeyCode::Char('a')));
        let all = render_view(&mut view, &mut store, 70, 8);
        assert!(all.iter().any(|l| l.contains("done")), "{all:?}");
    }

    #[test]
    fn the_cursor_stays_on_the_same_task_across_a_refresh() {
        let (mut store, ids) = store_with(&["one", "two", "three"]);
        let mut view = TasksView::new();
        render_view(&mut view, &mut store, 70, 8);

        // Newest first, so index 1 is "two".
        press(&mut view, &mut store, key(KeyCode::Char('j')));
        let before = view.selected().map(|t| t.id);
        assert_eq!(before, Some(ids[1]));

        // A new task arrives from the daemon and shifts every row down.
        store
            .create_task("four", "p", Path::new("/tmp/tasks"), &[], at(4))
            .unwrap();
        press(&mut view, &mut store, key(KeyCode::Char('r')));

        assert_eq!(
            view.selected().map(|t| t.id),
            before,
            "a task appearing elsewhere must not move the selection"
        );
    }

    #[test]
    fn navigation_stops_at_the_ends() {
        let (mut store, _) = store_with(&["one", "two"]);
        let mut view = TasksView::new();
        render_view(&mut view, &mut store, 70, 8);

        for _ in 0..5 {
            press(&mut view, &mut store, key(KeyCode::Char('k')));
        }
        assert_eq!(view.table.selected(), Some(0));

        for _ in 0..5 {
            press(&mut view, &mut store, key(KeyCode::Char('j')));
        }
        assert_eq!(view.table.selected(), Some(1), "must not run off the end");
    }

    #[test]
    fn cancelling_moves_the_task_and_removes_it_from_the_list() {
        let (mut store, ids) = store_with(&["doomed"]);
        let mut view = TasksView::new();
        render_view(&mut view, &mut store, 70, 8);

        press(&mut view, &mut store, key(KeyCode::Char('c')));

        assert_eq!(store.get_task(ids[0]).unwrap().state, TaskState::Cancelled);
        assert!(view.tasks.is_empty(), "cancelled tasks are not open work");
    }

    #[test]
    fn ctrl_c_quits_instead_of_cancelling_the_highlighted_task() {
        // The reflex for leaving a terminal program used to destroy work: the
        // bindings matched on `code` alone, so ctrl-c ran the `c` action and
        // the row then disappeared from the list, finished tasks being hidden.
        let (mut store, ids) = store_with(&["precious"]);
        let mut view = TasksView::new();
        render_view(&mut view, &mut store, 70, 8);

        let chord = KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL);
        assert!(matches!(press(&mut view, &mut store, chord), Action::Quit));
        assert_eq!(
            store.get_task(ids[0]).unwrap().state,
            TaskState::Queued,
            "ctrl-c must not cancel anything"
        );
    }

    #[test]
    fn other_modified_letters_do_nothing() {
        let (mut store, _) = store_with(&["one"]);
        let mut view = TasksView::new();
        render_view(&mut view, &mut store, 70, 8);

        for code in [KeyCode::Char('n'), KeyCode::Char('a'), KeyCode::Char('q')] {
            let chord = KeyEvent::new(code, KeyModifiers::CONTROL);
            assert!(
                matches!(press(&mut view, &mut store, chord), Action::None),
                "ctrl+{code:?} is not the {code:?} binding"
            );
        }
    }

    #[test]
    fn cancelling_a_finished_task_is_refused_rather_than_erroring() {
        let (mut store, ids) = store_with(&["done"]);
        store
            .transition(ids[0], TaskState::Running, Transition::Plain, at(1))
            .unwrap();
        store
            .transition(ids[0], TaskState::AwaitingReview, Transition::Plain, at(2))
            .unwrap();
        store
            .transition(ids[0], TaskState::Committed, Transition::Plain, at(3))
            .unwrap();

        let mut view = TasksView::new();
        view.hide_done = false;
        render_view(&mut view, &mut store, 70, 8);
        press(&mut view, &mut store, key(KeyCode::Char('c')));

        assert_eq!(
            store.get_task(ids[0]).unwrap().state,
            TaskState::Committed,
            "a committed task must stay committed"
        );
    }

    #[test]
    fn n_opens_the_new_task_screen_and_enter_opens_a_task() {
        let (mut store, _) = store_with(&["one"]);
        let mut view = TasksView::new();
        render_view(&mut view, &mut store, 70, 8);

        assert!(matches!(
            press(&mut view, &mut store, key(KeyCode::Char('n'))),
            Action::Push(_)
        ));
        assert!(matches!(
            press(&mut view, &mut store, key(KeyCode::Enter)),
            Action::Push(_)
        ));
        assert!(matches!(
            press(&mut view, &mut store, key(KeyCode::Char('q'))),
            Action::Quit
        ));
    }

    #[test]
    fn enter_on_an_empty_list_does_nothing() {
        let mut store = Store::open_in_memory().unwrap();
        let mut view = TasksView::new();
        render_view(&mut view, &mut store, 70, 8);
        assert!(matches!(
            press(&mut view, &mut store, key(KeyCode::Enter)),
            Action::None
        ));
    }
}