marver 0.0.19

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

use std::collections::HashMap;

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, DETAIL_WORDS, Result, View, first_words, new_task::NewTaskView,
    review::ReviewView, state_style, task::TaskView, todos::TodosView,
};
use crate::domain::{Task, TaskState};
use crate::pause;
use crate::store::Transition;
use crate::tmux::Tmux;

/// How the list is ordered.
///
/// Cycled rather than configured: three arrangements is few enough that a key
/// is faster than anything that would let you name one.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Arrangement {
    /// Newest first. What you just started is what you care about.
    Recent,
    /// Oldest first, for working through a backlog in the order it arrived.
    Oldest,
    /// Grouped by repo, newest first inside each.
    Repo,
}

impl Arrangement {
    pub const ALL: &'static [Arrangement] = &[Self::Recent, Self::Oldest, Self::Repo];

    fn label(self) -> &'static str {
        match self {
            Self::Recent => "newest",
            Self::Oldest => "oldest",
            Self::Repo => "by repo",
        }
    }

    fn next(self) -> Self {
        match self {
            Self::Recent => Self::Oldest,
            Self::Oldest => Self::Repo,
            Self::Repo => Self::Recent,
        }
    }
}

pub struct TasksView {
    tasks: Vec<Task>,
    /// Repo names per task, read in one query rather than one per row.
    repos: HashMap<i64, Vec<String>>,
    /// Outstanding todos per task, for the badge on the title.
    todos: HashMap<i64, usize>,
    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,
    arrangement: Arrangement,
    loaded: bool,
}

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

impl TasksView {
    pub fn new() -> Self {
        Self {
            tasks: Vec::new(),
            repos: HashMap::new(),
            todos: HashMap::new(),
            table: TableState::default().with_selected(Some(0)),
            hide_done: true,
            arrangement: Arrangement::Recent,
            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));
        }
        self.repos = ctx.store.repo_names_by_task().unwrap_or_default();
        self.todos = ctx.store.open_todo_counts().unwrap_or_default();
        self.arrange(&mut tasks);

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

    /// Put `tasks` in the order the current arrangement asks for.
    ///
    /// `list_tasks` returns them by id, which ascends with creation, so the
    /// creation order is already there to be reversed or grouped.
    fn arrange(&self, tasks: &mut [Task]) {
        match self.arrangement {
            Arrangement::Oldest => {}
            Arrangement::Recent => tasks.reverse(),
            // Sorted rather than sectioned: identical repo names end up
            // adjacent, which reads as a group without a header row that the
            // selection would then have to know how to skip over.
            Arrangement::Repo => {
                tasks.sort_by(|a, b| {
                    self.repo_label(a)
                        .cmp(&self.repo_label(b))
                        .then(b.id.cmp(&a.id))
                });
            }
        }
    }

    /// The repos a task targets, as one string. Empty sorts last, not first:
    /// a task with no repo yet is the least useful thing to lead with.
    fn repo_label(&self, task: &Task) -> (bool, String) {
        match self.repos.get(&task.id) {
            Some(names) if !names.is_empty() => (false, names.join(", ")),
            _ => (true, String::new()),
        }
    }

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

    /// What `p` would do to the selected task, for the footer.
    fn pause_label(&self) -> &'static str {
        match self.selected() {
            Some(task) if task.state == TaskState::Paused => "resume",
            _ => "pause",
        }
    }

    /// Pause or resume, whichever the task's state calls for.
    ///
    /// Both directions on one key: from here the user is deciding whether to
    /// look at this task now or later, and which state it is in is marver's
    /// problem rather than theirs.
    fn set_aside(&mut self, task: &Task, ctx: &mut Context) -> Result<()> {
        let tmux = Tmux::new();
        let now = chrono::Utc::now();
        let outcome = if task.state == TaskState::Paused {
            pause::resume(ctx.store, &tmux, task, now).map(|task| match task.state {
                // Said plainly, because the two resumes are different events:
                // one re-enters the queue and waits, the other starts an agent
                // working again this second.
                TaskState::Queued => format!("task {} is queued again", task.id),
                _ => format!("task {} resumed", task.id),
            })
        } else {
            pause::pause(ctx.store, &tmux, task, now).map(|task| format!("paused task {}", task.id))
        };
        match outcome {
            Ok(message) => {
                ctx.say(message);
                self.reload(ctx)?;
            }
            // Reported rather than swallowed: pausing reaches a live agent, and
            // "nothing happened" is the one thing the user must not conclude
            // when the agent was never told.
            Err(err) => ctx.say(err.to_string()),
        }
        Ok(())
    }

    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();
        let counted = if self.hide_done {
            format!("{shown} open")
        } else {
            shown.to_string()
        };
        format!("Tasks ({counted}) · {}", self.arrangement.label())
    }

    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 mut previous: Option<String> = None;
        let rows: Vec<Row> = self
            .tasks
            .iter()
            .map(|task| {
                let repo = self.repo_label(task).1;
                // A repeat of the line above is dimmed rather than repeated at
                // full weight, so a run of one repo reads as one block. This is
                // what stands in for a group header.
                let style = if previous.as_deref() == Some(repo.as_str()) {
                    Style::default().add_modifier(Modifier::DIM)
                } else {
                    Style::default()
                };
                previous = Some(repo.clone());

                // The title carries the todo count, because without it a note
                // left on a task is invisible from here — you would have to open
                // every task in turn to find out which ones have any.
                let title = match self.todos.get(&task.id) {
                    Some(0) | None => Line::from(task.title.clone()),
                    Some(count) => Line::from(vec![
                        Span::raw(task.title.clone()),
                        Span::styled(
                            format!("{count}"),
                            Style::default().add_modifier(Modifier::DIM),
                        ),
                    ]),
                };

                Row::new(vec![
                    Cell::from(format!("{}", task.id)),
                    Cell::from(Span::styled(
                        task.state.as_str().to_string(),
                        state_style(task.state),
                    )),
                    Cell::from(Span::styled(repo, style)),
                    Cell::from(title),
                    Cell::from(detail_for(task)),
                ])
            })
            .collect();

        let table = Table::new(
            rows,
            [
                Constraint::Length(4),
                Constraint::Length(16),
                Constraint::Length(16),
                Constraint::Percentage(35),
                Constraint::Min(10),
            ],
        )
        .header(
            Row::new(vec!["id", "state", "repo", "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 {
                // ctrl-q leaves every screen in marver, including the agent's,
                // where `esc` cannot because the agent needs it.
                KeyCode::Char('c') | KeyCode::Char('q') => Action::Quit,
                _ => Action::None,
            });
        }

        match key.code {
            // esc leaves every screen; on the root there is nothing under it,
            // so leaving is quitting. `q` stays because it always has.
            KeyCode::Char('q') | KeyCode::Esc => 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::Char('s') => {
                self.arrangement = self.arrangement.next();
                self.reload(ctx)?;
                ctx.say(self.arrangement.label());
            }
            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))));
                    }
                }
            }
            // One key for both directions, because the user is thinking "set
            // this aside" and "pick it back up", not about which state it is in.
            KeyCode::Char('p') => {
                if let Some(task) = self.selected().cloned() {
                    self.set_aside(&task, ctx)?;
                }
            }
            // Opens on the selected task's todos, and `tab` there reaches the
            // global ones. One key rather than two, so the footer can show the
            // whole truth about this screen.
            KeyCode::Char('t') => {
                return Ok(Action::Push(Box::new(match self.selected() {
                    Some(task) => TodosView::for_task(task.id),
                    None => TodosView::global(),
                })));
            }
            // `x` rather than `c`: `c` was cancel here and commit in review, and
            // muscle memory does not stop at the edge of a screen. `x` is
            // "discard this" in both places now — a task here, a diff there.
            KeyCode::Char('x') => {
                // 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"),
            ("p", self.pause_label()),
            ("t", "todos"),
            ("x", "cancel"),
            ("a", "all"),
            ("s", "sort"),
            ("r", "refresh"),
            ("esc", "quit"),
        ]
    }
}

/// The most useful thing to say about a task in one column.
///
/// Cut to [`DETAIL_WORDS`], because the text underneath is whatever git, tmux,
/// or Claude Code had to say: an unbounded reason pushed every other column off
/// the screen, and a reason with a newline in it turned one row into several.
fn detail_for(task: &Task) -> String {
    let full = 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(),
    };
    first_words(&full, DETAIL_WORDS)
}

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

    /// The titles currently on screen, in order.
    fn titles(view: &TasksView) -> Vec<String> {
        view.tasks.iter().map(|t| t.title.clone()).collect()
    }

    /// Tasks against named repos, so grouping has something to group by.
    fn store_with_repos(rows: &[(&str, &str)]) -> (Store, tempfile::TempDir) {
        let tmp = tempfile::TempDir::new().unwrap();
        let mut store = Store::open_in_memory().unwrap();
        for (index, (title, repo_name)) in rows.iter().enumerate() {
            let path = tmp.path().join(repo_name);
            let repo = store.upsert_repo(&path, repo_name, at(0)).unwrap();
            store
                .create_task(
                    title,
                    "p",
                    Path::new("/tmp/tasks"),
                    &[repo.id],
                    at(index as i64),
                )
                .unwrap();
        }
        (store, tmp)
    }

    /// The repo column of every task row, top to bottom.
    fn repo_column(screen: &[String]) -> Vec<String> {
        screen
            .iter()
            .skip(1)
            .filter(|line| !line.trim().is_empty())
            .filter_map(|line| line.split_whitespace().nth(2).map(str::to_string))
            .collect()
    }

    #[test]
    fn the_list_names_the_repo_each_task_is_for() {
        let (mut store, _tmp) = store_with_repos(&[("first", "api"), ("second", "web")]);
        let mut view = TasksView::new();

        let screen = render_view(&mut view, &mut store, 100, 8);
        assert!(screen[0].contains("repo"), "a column for it: {screen:?}");
        assert!(screen.iter().any(|l| l.contains("api")), "{screen:?}");
        assert!(screen.iter().any(|l| l.contains("web")), "{screen:?}");
    }

    #[test]
    fn sorting_cycles_through_the_arrangements() {
        let (mut store, _tmp) =
            store_with_repos(&[("oldest", "web"), ("middle", "api"), ("newest", "web")]);
        let mut view = TasksView::new();
        render_view(&mut view, &mut store, 100, 10);

        // Newest first, the default.
        assert_eq!(titles(&view), ["newest", "middle", "oldest"]);
        assert!(view.title().contains("newest"), "{}", view.title());

        press(&mut view, &mut store, key(KeyCode::Char('s')));
        assert_eq!(titles(&view), ["oldest", "middle", "newest"]);
        assert!(view.title().contains("oldest"), "{}", view.title());

        press(&mut view, &mut store, key(KeyCode::Char('s')));
        // api before web, and inside web the newer one first.
        assert_eq!(titles(&view), ["middle", "newest", "oldest"]);
        assert!(view.title().contains("by repo"), "{}", view.title());

        press(&mut view, &mut store, key(KeyCode::Char('s')));
        assert_eq!(titles(&view), ["newest", "middle", "oldest"], "it wraps");
    }

    #[test]
    fn cycling_the_whole_set_comes_back_to_where_it_started() {
        // No arrangement is a dead end, and none is unreachable by pressing `s`
        // enough times — which is the only way to reach any of them.
        let (mut store, _tmp) = store_with_repos(&[("only", "api")]);
        let mut view = TasksView::new();
        render_view(&mut view, &mut store, 100, 8);
        let start = view.arrangement;

        for _ in Arrangement::ALL {
            press(&mut view, &mut store, key(KeyCode::Char('s')));
        }
        assert_eq!(view.arrangement, start);
    }

    #[test]
    fn grouping_puts_a_repo_together() {
        let (mut store, _tmp) =
            store_with_repos(&[("a", "web"), ("b", "api"), ("c", "web"), ("d", "api")]);
        let mut view = TasksView::new();
        render_view(&mut view, &mut store, 100, 10);
        press(&mut view, &mut store, key(KeyCode::Char('s')));
        press(&mut view, &mut store, key(KeyCode::Char('s')));

        let screen = render_view(&mut view, &mut store, 100, 10);
        let repos = repo_column(&screen);
        let mut runs = repos.clone();
        runs.dedup();
        assert_eq!(
            runs.len(),
            2,
            "each repo should appear as one run, not scattered: {repos:?}"
        );
    }

    #[test]
    fn the_cursor_stays_on_its_task_when_the_order_changes() {
        // Re-sorting under someone is only acceptable if it does not also move
        // what they had selected.
        let (mut store, _tmp) =
            store_with_repos(&[("first", "api"), ("second", "web"), ("third", "api")]);
        let mut view = TasksView::new();
        render_view(&mut view, &mut store, 100, 10);

        press(&mut view, &mut store, key(KeyCode::Char('j')));
        let held = view.selected().map(|t| t.id);
        assert!(held.is_some());

        press(&mut view, &mut store, key(KeyCode::Char('s')));
        assert_eq!(view.selected().map(|t| t.id), held, "the cursor followed");
    }

    #[test]
    fn a_task_with_no_repo_sorts_last_rather_than_first() {
        let (mut store, _tmp) = store_with_repos(&[("has one", "api")]);
        store
            .create_task("has none", "p", Path::new("/tmp/tasks"), &[], at(9))
            .unwrap();
        let mut view = TasksView::new();
        render_view(&mut view, &mut store, 100, 10);
        press(&mut view, &mut store, key(KeyCode::Char('s')));
        press(&mut view, &mut store, key(KeyCode::Char('s')));

        assert_eq!(titles(&view), ["has one", "has none"]);
    }

    #[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 a_task_with_todos_says_so_on_the_list() {
        // Without this, a note left on a task is invisible from here: the only
        // way to find out which tasks have any would be to open each in turn.
        use crate::domain::TodoScope;
        let (mut store, ids) = store_with(&["fix auth"]);
        store
            .add_todo(TodoScope::Task(ids[0]), "also handle nulls", at(1))
            .unwrap();
        let done = store
            .add_todo(TodoScope::Task(ids[0]), "already sent", at(2))
            .unwrap();
        store.set_todo_done(done.id, true).unwrap();
        store
            .add_todo(TodoScope::Global, "not this task's", at(3))
            .unwrap();

        let mut view = TasksView::new();
        let screen = render_view(&mut view, &mut store, 100, 12).join("\n");

        assert!(screen.contains("☐1"), "one outstanding todo: {screen}");
    }

    #[test]
    fn a_task_with_nothing_outstanding_carries_no_badge() {
        let (mut store, _) = store_with(&["fix auth"]);
        let mut view = TasksView::new();
        let screen = render_view(&mut view, &mut store, 100, 12).join("\n");
        assert!(!screen.contains(""), "{screen}");
    }

    #[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('x')));

        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_and_bare_c_no_longer_destroys_anything() {
        // 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.
        // Cancel has since moved to `x`, so `c` is inert here either way.
        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"
        );

        press(&mut view, &mut store, key(KeyCode::Char('c')));
        assert_eq!(
            store.get_task(ids[0]).unwrap().state,
            TaskState::Queued,
            "`c` is commit in review; here it must do nothing at all"
        );
    }

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

        // Nothing sits under the root, so leaving it is quitting.
        assert!(matches!(
            press(&mut view, &mut store, key(KeyCode::Esc)),
            Action::Quit
        ));
    }

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

        // Not `q`: ctrl-q is the one binding that leaves every screen.
        for code in [KeyCode::Char('n'), KeyCode::Char('a'), KeyCode::Char('v')] {
            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('x')));

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

#[cfg(test)]
mod pause_tests {
    use super::*;
    use crate::store::Store;
    use crate::tui::testing::{press, render_view, tick_view};
    use chrono::{DateTime, Utc};
    use ratatui::crossterm::event::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_a_queued_task() -> (Store, i64) {
        let mut store = Store::open_in_memory().unwrap();
        let id = store
            .create_task("not yet", "do it", Path::new("/tmp/tasks"), &[], at(0))
            .unwrap()
            .id;
        (store, id)
    }

    #[test]
    fn p_holds_a_queued_task_and_gives_it_back() {
        // One key both ways: from here the user is deciding whether to look at
        // this now or later, not which state the task happens to be in.
        let (mut store, id) = store_with_a_queued_task();
        let mut view = TasksView::new();
        render_view(&mut view, &mut store, 80, 12);

        press(&mut view, &mut store, key(KeyCode::Char('p')));
        assert_eq!(store.get_task(id).unwrap().state, TaskState::Paused);

        press(&mut view, &mut store, key(KeyCode::Char('p')));
        assert_eq!(
            store.get_task(id).unwrap().state,
            TaskState::Queued,
            "a task that never launched goes back to waiting its turn"
        );
    }

    #[test]
    fn the_footer_says_which_way_p_goes() {
        let (mut store, id) = store_with_a_queued_task();
        let mut view = TasksView::new();
        render_view(&mut view, &mut store, 80, 12);
        assert!(view.keys().contains(&("p", "pause")));

        store
            .transition(id, TaskState::Paused, Transition::Plain, at(1))
            .unwrap();
        // Ticked, not just redrawn: the list re-reads the store on tick, which
        // is how a change made by the daemon reaches the screen too.
        tick_view(&mut view, &mut store);

        assert!(view.keys().contains(&("p", "resume")));
    }

    #[test]
    fn pausing_something_that_cannot_be_paused_explains_rather_than_throws() {
        let (mut store, id) = store_with_a_queued_task();
        store
            .transition(id, TaskState::Cancelled, Transition::Plain, at(1))
            .unwrap();
        let mut view = TasksView::new();
        view.hide_done = false;
        render_view(&mut view, &mut store, 80, 12);

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

        assert_eq!(
            store.get_task(id).unwrap().state,
            TaskState::Cancelled,
            "a finished task stays finished"
        );
    }

    #[test]
    fn t_opens_the_selected_tasks_todos() {
        let (mut store, id) = store_with_a_queued_task();
        let mut view = TasksView::new();
        render_view(&mut view, &mut store, 80, 12);

        let action = press(&mut view, &mut store, key(KeyCode::Char('t')));

        let Action::Push(pushed) = action else {
            panic!("t should open the todo screen");
        };
        assert!(
            pushed.title().contains(&format!("task {id}")),
            "{}",
            pushed.title()
        );
    }

    #[test]
    fn t_on_an_empty_board_opens_the_global_todos() {
        let mut store = Store::open_in_memory().unwrap();
        let mut view = TasksView::new();
        render_view(&mut view, &mut store, 80, 12);

        let action = press(&mut view, &mut store, key(KeyCode::Char('t')));

        let Action::Push(pushed) = action else {
            panic!("t should still open a todo screen");
        };
        assert!(pushed.title().contains("global"), "{}", pushed.title());
    }
}