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
//! Describing a task: title, prompt, and which repos it touches.
//!
//! The task is created in `queued`. Nothing is provisioned here — the daemon
//! picks it up on its next tick and launches it if a slot is free. That keeps
//! this screen instant and means a queue of twenty tasks holds no worktrees.

use std::collections::BTreeSet;

use ratatui::Frame;
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, List, ListItem, ListState, Paragraph};

use super::{Action, Context, Result, View};
use crate::domain::{Repo, Todo};

/// A one-line label from a todo's text, cut at a word boundary.
fn title_from(text: &str) -> String {
    let line = text.lines().next().unwrap_or("").trim();
    if line.chars().count() <= TITLE_FROM_TODO {
        return line.to_string();
    }
    let cut: String = line.chars().take(TITLE_FROM_TODO).collect();
    match cut.rsplit_once(char::is_whitespace) {
        Some((head, _)) if !head.trim().is_empty() => head.trim().to_string(),
        _ => cut,
    }
}

/// Which field has focus.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Field {
    Title,
    Prompt,
    Repos,
}

pub struct NewTaskView {
    title: String,
    prompt: String,
    field: Field,
    repos: Vec<Repo>,
    chosen: BTreeSet<i64>,
    list: ListState,
    loaded: bool,
    /// The global todo this came from, ticked off once the task is queued.
    origin: Option<i64>,
}

/// Longest title taken from a todo before it is cut at a word boundary.
///
/// A todo is a sentence and a title is a label, so the whole text goes in the
/// prompt and only the beginning becomes the title. Cut without an ellipsis:
/// this is a starting point to be edited, not a summary to be read.
const TITLE_FROM_TODO: usize = 60;

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

impl NewTaskView {
    pub fn new() -> Self {
        Self {
            title: String::new(),
            prompt: String::new(),
            field: Field::Title,
            repos: Vec::new(),
            chosen: BTreeSet::new(),
            list: ListState::default().with_selected(Some(0)),
            loaded: false,
            origin: None,
        }
    }

    /// Start from a global todo.
    ///
    /// Opens on the repo list, because the text is already written and choosing
    /// where it applies is the only thing left that the todo could not say.
    pub fn from_todo(todo: &Todo) -> Self {
        Self {
            title: title_from(&todo.text),
            prompt: todo.text.clone(),
            field: Field::Repos,
            origin: Some(todo.id),
            ..Self::new()
        }
    }

    fn load(&mut self, ctx: &mut Context) -> Result<()> {
        self.repos = ctx.store.list_repos(false)?;
        self.loaded = true;
        Ok(())
    }

    fn next_field(&mut self) {
        self.field = match self.field {
            Field::Title => Field::Prompt,
            Field::Prompt => Field::Repos,
            Field::Repos => Field::Title,
        };
    }

    fn toggle_selected(&mut self) {
        if let Some(repo) = self.list.selected().and_then(|i| self.repos.get(i))
            && !self.chosen.insert(repo.id)
        {
            self.chosen.remove(&repo.id);
        }
    }

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

    /// Why the task cannot be created yet, if it cannot.
    fn blocker(&self) -> Option<&'static str> {
        if self.title.trim().is_empty() {
            return Some("a title is required");
        }
        if self.prompt.trim().is_empty() {
            return Some("describe what the agent should do");
        }
        if self.chosen.is_empty() {
            // A task with no repos has nowhere to work; the launcher would
            // reject it, so it is refused here where it can be explained.
            return Some("choose at least one repo with space");
        }
        None
    }

    fn create(&self, ctx: &mut Context) -> Result<i64> {
        let ids: Vec<i64> = self.chosen.iter().copied().collect();
        let task = ctx.store.create_task(
            self.title.trim(),
            self.prompt.trim(),
            &ctx.config.workspace_root,
            &ids,
            chrono::Utc::now(),
        )?;
        Ok(task.id)
    }
}

impl NewTaskView {
    /// Queue the task, or say what is stopping it.
    fn queue(&mut self, ctx: &mut Context) -> Result<Action> {
        match self.blocker() {
            Some(reason) => {
                ctx.say(reason);
                Ok(Action::None)
            }
            None => {
                let id = self.create(ctx)?;
                // Ticked off now rather than when the screen opened: a todo
                // whose task was abandoned half-written is still outstanding.
                if let Some(todo) = self.origin {
                    ctx.store.set_todo_done(todo, true)?;
                }
                ctx.say(format!("queued task {id}"));
                Ok(Action::Pop)
            }
        }
    }
}

impl View for NewTaskView {
    fn title(&self) -> String {
        "New task".into()
    }

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

        let [title_area, prompt_area, repos_area, hint_area] = Layout::vertical([
            Constraint::Length(3),
            Constraint::Length(6),
            Constraint::Min(4),
            Constraint::Length(1),
        ])
        .areas(area);

        frame.render_widget(
            Paragraph::new(caret(&self.title, self.field == Field::Title))
                .block(bordered("Title", self.field == Field::Title)),
            title_area,
        );

        frame.render_widget(
            Paragraph::new(caret(&self.prompt, self.field == Field::Prompt))
                .block(bordered(
                    "What should the agent do?",
                    self.field == Field::Prompt,
                ))
                .wrap(ratatui::widgets::Wrap { trim: false }),
            prompt_area,
        );

        let items: Vec<ListItem> = if self.repos.is_empty() {
            vec![ListItem::new(Span::styled(
                "  no repos found — is the daemon scanning the right root?",
                Style::default().fg(Color::Yellow),
            ))]
        } else {
            self.repos
                .iter()
                .map(|repo| {
                    let mark = if self.chosen.contains(&repo.id) {
                        "[x] "
                    } else {
                        "[ ] "
                    };
                    ListItem::new(Line::from(vec![
                        Span::styled(mark, Style::default().fg(Color::Green)),
                        Span::raw(repo.name.clone()),
                        Span::styled(
                            format!("  {}", repo.path.display()),
                            Style::default().add_modifier(Modifier::DIM),
                        ),
                    ]))
                })
                .collect()
        };

        frame.render_stateful_widget(
            List::new(items)
                .block(bordered(
                    &format!("Repos ({} selected)", self.chosen.len()),
                    self.field == Field::Repos,
                ))
                .highlight_style(Style::default().add_modifier(Modifier::REVERSED)),
            repos_area,
            &mut self.list,
        );

        let hint = match self.blocker() {
            Some(reason) => Span::styled(format!("  {reason}"), Style::default().fg(Color::Yellow)),
            None => Span::styled(
                "  ready — ctrl-s to queue it",
                Style::default().fg(Color::Green),
            ),
        };
        frame.render_widget(Paragraph::new(Line::from(hint)), hint_area);
    }

    fn handle_key(&mut self, key: KeyEvent, ctx: &mut Context) -> Result<Action> {
        // Ctrl-s submits from any field, so the user never has to tab back.
        // Before the text fields, which would otherwise take it as a letter.
        if key.code == KeyCode::Char('q') && key.modifiers.contains(KeyModifiers::CONTROL) {
            return Ok(Action::Pop);
        }

        if key.code == KeyCode::Char('s') && key.modifiers.contains(KeyModifiers::CONTROL) {
            return self.queue(ctx);
        }

        match key.code {
            KeyCode::Esc => return Ok(Action::Pop),
            KeyCode::Tab => self.next_field(),
            _ => match self.field {
                Field::Title => match key.code {
                    KeyCode::Char(c) => self.title.push(c),
                    KeyCode::Backspace => {
                        self.title.pop();
                    }
                    // A title is one line, so there is nothing else enter
                    // could mean here.
                    KeyCode::Enter => return self.queue(ctx),
                    _ => {}
                },
                Field::Prompt => match key.code {
                    KeyCode::Char(c) => self.prompt.push(c),
                    KeyCode::Backspace => {
                        self.prompt.pop();
                    }
                    // The one field where enter cannot queue. A prompt is what
                    // the agent is told to do and is routinely several
                    // paragraphs; losing the only way to type a newline would
                    // cost more than the shortcut is worth. ctrl-s queues from
                    // here, as it does from anywhere.
                    KeyCode::Enter => self.prompt.push('\n'),
                    _ => {}
                },
                Field::Repos => match key.code {
                    KeyCode::Char(' ') => self.toggle_selected(),
                    KeyCode::Char('j') | KeyCode::Down => self.move_by(1),
                    KeyCode::Char('k') | KeyCode::Up => self.move_by(-1),
                    KeyCode::Enter => return self.queue(ctx),
                    _ => {}
                },
            },
        }
        Ok(Action::None)
    }

    fn keys(&self) -> Vec<(&'static str, &'static str)> {
        vec![
            ("tab", "field"),
            ("space", "toggle repo"),
            ("↵/^s", "queue"),
            ("esc", "cancel"),
        ]
    }

    fn captures_input(&self) -> bool {
        true
    }
}

fn bordered(title: &str, focused: bool) -> Block<'static> {
    let style = if focused {
        Style::default().fg(Color::Magenta)
    } else {
        Style::default().add_modifier(Modifier::DIM)
    };
    Block::default()
        .borders(Borders::ALL)
        .border_style(style)
        .title(title.to_string())
}

/// Show a block caret on the focused field so it is obvious where typing goes.
fn caret(text: &str, focused: bool) -> String {
    if focused {
        format!("{text}")
    } else {
        text.to_string()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::store::Store;
    use crate::tui::testing::{press, render_view};
    use chrono::{DateTime, Utc};
    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 ctrl(c: char) -> KeyEvent {
        KeyEvent::new(KeyCode::Char(c), KeyModifiers::CONTROL)
    }

    fn store_with_repos(names: &[&str]) -> Store {
        let store = Store::open_in_memory().unwrap();
        for name in names {
            store
                .upsert_repo(Path::new(&format!("/w/{name}")), name, at(0))
                .unwrap();
        }
        store
    }

    fn type_str(view: &mut NewTaskView, store: &mut Store, text: &str) {
        for c in text.chars() {
            press(view, store, key(KeyCode::Char(c)));
        }
    }

    /// Fill in a complete, valid task.
    fn fill(view: &mut NewTaskView, store: &mut Store) {
        type_str(view, store, "Fix auth");
        press(view, store, key(KeyCode::Tab));
        type_str(view, store, "fix the auth flow");
        press(view, store, key(KeyCode::Tab));
        press(view, store, key(KeyCode::Char(' ')));
    }

    #[test]
    fn typing_goes_to_the_focused_field_and_tab_moves_on() {
        let mut store = store_with_repos(&["api"]);
        let mut view = NewTaskView::new();
        render_view(&mut view, &mut store, 70, 20);

        type_str(&mut view, &mut store, "Fix auth");
        assert_eq!(view.title, "Fix auth");
        assert!(view.prompt.is_empty());

        press(&mut view, &mut store, key(KeyCode::Tab));
        type_str(&mut view, &mut store, "do it");
        assert_eq!(view.prompt, "do it");
        assert_eq!(view.title, "Fix auth", "the title must not gain the prompt");
    }

    #[test]
    fn q_types_a_q_rather_than_quitting() {
        let mut store = store_with_repos(&["api"]);
        let mut view = NewTaskView::new();
        render_view(&mut view, &mut store, 70, 20);
        type_str(&mut view, &mut store, "quick fix");
        assert_eq!(view.title, "quick fix");
        assert!(
            view.captures_input(),
            "text fields must swallow global keys"
        );
    }

    #[test]
    fn backspace_deletes_from_the_focused_field() {
        let mut store = store_with_repos(&["api"]);
        let mut view = NewTaskView::new();
        render_view(&mut view, &mut store, 70, 20);
        type_str(&mut view, &mut store, "abc");
        press(&mut view, &mut store, key(KeyCode::Backspace));
        assert_eq!(view.title, "ab");
    }

    #[test]
    fn enter_queues_from_every_field_except_the_prompt() {
        let mut store = store_with_repos(&["api"]);
        let mut view = NewTaskView::new();
        render_view(&mut view, &mut store, 70, 20);

        // From the title, with the form not yet fillable, it refuses and says
        // why rather than doing nothing.
        press(&mut view, &mut store, key(KeyCode::Enter));
        assert!(store.list_tasks().unwrap().is_empty(), "nothing queued yet");

        type_str(&mut view, &mut store, "fix auth");
        press(&mut view, &mut store, key(KeyCode::Tab));
        type_str(&mut view, &mut store, "do the thing");

        // A prompt is routinely several paragraphs, so this is the one field
        // where enter has to keep meaning newline.
        press(&mut view, &mut store, key(KeyCode::Enter));
        assert_eq!(view.prompt, "do the thing\n");
        assert!(store.list_tasks().unwrap().is_empty(), "still not queued");

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

        assert!(matches!(action, Action::Pop), "enter queues from the repos");
        assert_eq!(store.list_tasks().unwrap().len(), 1);
    }

    #[test]
    fn ctrl_s_still_queues_from_inside_the_prompt() {
        // The escape hatch for the one field enter cannot submit from.
        let mut store = store_with_repos(&["api"]);
        let mut view = NewTaskView::new();
        render_view(&mut view, &mut store, 70, 20);
        type_str(&mut view, &mut store, "fix auth");
        press(&mut view, &mut store, key(KeyCode::Tab));
        press(&mut view, &mut store, key(KeyCode::Tab));
        press(&mut view, &mut store, key(KeyCode::Char(' ')));
        // Back to the prompt, and submit from there.
        press(&mut view, &mut store, key(KeyCode::Tab));
        press(&mut view, &mut store, key(KeyCode::Tab));
        type_str(&mut view, &mut store, "do it");

        let action = press(&mut view, &mut store, ctrl('s'));
        assert!(matches!(action, Action::Pop));
        assert_eq!(store.list_tasks().unwrap().len(), 1);
    }

    #[test]
    fn space_toggles_a_repo_on_and_off() {
        let mut store = store_with_repos(&["api", "web"]);
        let mut view = NewTaskView::new();
        render_view(&mut view, &mut store, 70, 20);

        press(&mut view, &mut store, key(KeyCode::Tab));
        press(&mut view, &mut store, key(KeyCode::Tab));
        press(&mut view, &mut store, key(KeyCode::Char(' ')));
        assert_eq!(view.chosen.len(), 1);

        press(&mut view, &mut store, key(KeyCode::Char(' ')));
        assert!(view.chosen.is_empty(), "space must toggle, not only select");

        press(&mut view, &mut store, key(KeyCode::Char('j')));
        press(&mut view, &mut store, key(KeyCode::Char(' ')));
        assert_eq!(view.chosen.len(), 1);
    }

    #[test]
    fn an_incomplete_task_explains_what_is_missing_instead_of_being_created() {
        let mut store = store_with_repos(&["api"]);
        let mut view = NewTaskView::new();
        render_view(&mut view, &mut store, 70, 20);

        assert_eq!(view.blocker(), Some("a title is required"));
        type_str(&mut view, &mut store, "Fix auth");
        assert_eq!(view.blocker(), Some("describe what the agent should do"));
        press(&mut view, &mut store, key(KeyCode::Tab));
        type_str(&mut view, &mut store, "do it");
        assert_eq!(
            view.blocker(),
            Some("choose at least one repo with space"),
            "a task with no repos has nowhere to work"
        );

        assert!(matches!(
            press(&mut view, &mut store, ctrl('s')),
            Action::None
        ));
        assert!(store.list_tasks().unwrap().is_empty());
    }

    #[test]
    fn a_complete_task_is_queued_with_its_repos() {
        let mut store = store_with_repos(&["api"]);
        let mut view = NewTaskView::new();
        render_view(&mut view, &mut store, 70, 20);
        fill(&mut view, &mut store);

        assert!(matches!(
            press(&mut view, &mut store, ctrl('s')),
            Action::Pop
        ));

        let tasks = store.list_tasks().unwrap();
        assert_eq!(tasks.len(), 1);
        assert_eq!(tasks[0].title, "Fix auth");
        assert_eq!(tasks[0].prompt, "fix the auth flow");
        assert_eq!(tasks[0].state, crate::domain::TaskState::Queued);

        let links = store.list_task_repos(tasks[0].id).unwrap();
        assert_eq!(links.len(), 1);
        assert!(
            !links[0].is_provisioned(),
            "queuing must not create worktrees; the daemon does that"
        );
    }

    #[test]
    fn a_multi_repo_task_records_every_choice() {
        let mut store = store_with_repos(&["api", "web"]);
        let mut view = NewTaskView::new();
        render_view(&mut view, &mut store, 70, 20);

        type_str(&mut view, &mut store, "Both");
        press(&mut view, &mut store, key(KeyCode::Tab));
        type_str(&mut view, &mut store, "change both");
        press(&mut view, &mut store, key(KeyCode::Tab));
        press(&mut view, &mut store, key(KeyCode::Char(' ')));
        press(&mut view, &mut store, key(KeyCode::Char('j')));
        press(&mut view, &mut store, key(KeyCode::Char(' ')));
        press(&mut view, &mut store, ctrl('s'));

        let task = &store.list_tasks().unwrap()[0];
        assert_eq!(store.list_task_repos(task.id).unwrap().len(), 2);
    }

    #[test]
    fn escape_abandons_without_creating_anything() {
        let mut store = store_with_repos(&["api"]);
        let mut view = NewTaskView::new();
        render_view(&mut view, &mut store, 70, 20);
        fill(&mut view, &mut store);

        assert!(matches!(
            press(&mut view, &mut store, key(KeyCode::Esc)),
            Action::Pop
        ));
        assert!(store.list_tasks().unwrap().is_empty());
    }

    #[test]
    fn a_workspace_without_repos_says_so() {
        let mut store = Store::open_in_memory().unwrap();
        let mut view = NewTaskView::new();
        let screen = render_view(&mut view, &mut store, 80, 20);
        assert!(
            screen.iter().any(|l| l.contains("no repos found")),
            "an empty repo list should not look like a bug in this screen: {screen:?}"
        );
    }

    #[test]
    fn the_screen_shows_what_is_still_missing() {
        let mut store = store_with_repos(&["api"]);
        let mut view = NewTaskView::new();
        let screen = render_view(&mut view, &mut store, 70, 20);
        assert!(
            screen.iter().any(|l| l.contains("a title is required")),
            "{screen:?}"
        );
    }
}

#[cfg(test)]
mod from_todo_tests {
    use super::*;
    use crate::domain::TodoScope;
    use crate::store::Store;
    use crate::tui::testing::{press, render_view};
    use chrono::{DateTime, Utc};
    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_repo() -> Store {
        let store = Store::open_in_memory().unwrap();
        store
            .upsert_repo(Path::new("/repos/api"), "api", at(0))
            .unwrap();
        store
    }

    #[test]
    fn a_todo_fills_in_the_prompt_and_a_title() {
        let store = store_with_a_repo();
        let todo = store
            .add_todo(TodoScope::Global, "upgrade ratatui to 0.30", at(1))
            .unwrap();

        let view = NewTaskView::from_todo(&todo);

        assert_eq!(view.prompt, "upgrade ratatui to 0.30");
        assert_eq!(view.title, "upgrade ratatui to 0.30");
        assert_eq!(
            view.field,
            Field::Repos,
            "the text is written, so what is left is where it applies"
        );
    }

    #[test]
    fn a_long_todo_gives_a_title_cut_at_a_word() {
        let store = store_with_a_repo();
        let text = "rewrite the whole scheduler so that a blocked agent releases \
                    its slot the moment the user answers rather than on the next tick";
        let todo = store.add_todo(TodoScope::Global, text, at(1)).unwrap();

        let view = NewTaskView::from_todo(&todo);

        assert!(view.title.len() <= TITLE_FROM_TODO, "{}", view.title);
        assert!(!view.title.ends_with(' '));
        assert!(
            !view.title.contains(''),
            "a title is a starting point to edit, not a summary to read"
        );
        assert_eq!(view.prompt, text, "the whole note is still the prompt");
    }

    #[test]
    fn queueing_from_a_todo_ticks_it_off() {
        let mut store = store_with_a_repo();
        let todo = store
            .add_todo(TodoScope::Global, "upgrade ratatui", at(1))
            .unwrap();
        let mut view = NewTaskView::from_todo(&todo);
        render_view(&mut view, &mut store, 80, 24);

        // Choose the repo, then queue it.
        press(&mut view, &mut store, key(KeyCode::Char(' ')));
        press(&mut view, &mut store, key(KeyCode::Enter));

        assert_eq!(store.list_tasks().unwrap().len(), 1, "the task exists");
        assert!(
            store.list_todos(TodoScope::Global).unwrap()[0].done,
            "and the note that asked for it is settled"
        );
    }

    #[test]
    fn abandoning_the_screen_leaves_the_todo_outstanding() {
        // Ticking it off when the screen opened would lose the note whenever a
        // task was started and then thought better of.
        let mut store = store_with_a_repo();
        let todo = store
            .add_todo(TodoScope::Global, "upgrade ratatui", at(1))
            .unwrap();
        let mut view = NewTaskView::from_todo(&todo);
        render_view(&mut view, &mut store, 80, 24);

        press(&mut view, &mut store, key(KeyCode::Esc));

        assert!(store.list_tasks().unwrap().is_empty());
        assert!(!store.list_todos(TodoScope::Global).unwrap()[0].done);
    }

    #[test]
    fn an_ordinary_new_task_has_no_todo_to_settle() {
        let mut store = store_with_a_repo();
        let mut view = NewTaskView::new();
        render_view(&mut view, &mut store, 80, 24);
        assert!(view.origin.is_none());

        // Title, prompt, repo, queue -- the whole screen, with nothing to tick.
        for ch in "fix auth".chars() {
            press(&mut view, &mut store, key(KeyCode::Char(ch)));
        }
        press(&mut view, &mut store, key(KeyCode::Tab));
        for ch in "do it".chars() {
            press(&mut view, &mut store, key(KeyCode::Char(ch)));
        }
        press(&mut view, &mut store, key(KeyCode::Tab));
        press(&mut view, &mut store, key(KeyCode::Char(' ')));
        press(&mut view, &mut store, key(KeyCode::Enter));

        assert_eq!(store.list_tasks().unwrap().len(), 1);
    }
}