marver 0.0.25

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
//! Describing a task: which repos it touches, what the agent should do, and —
//! only if you want to say — what to call it.

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::filter::{Filter, Handled};
use super::{Action, Context, Result, View};
use crate::domain::{Repo, Todo};

/// A one-line label from a body of 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_LENGTH {
        return line.to_string();
    }
    let cut: String = line.chars().take(TITLE_LENGTH).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 {
    Repos,
    Prompt,
    Title,
}

pub struct NewTaskView {
    title: String,
    prompt: String,
    field: Field,
    /// Every repo the scan found.
    all: Vec<Repo>,
    /// Those the filter lets through, which is what the list shows and what
    /// the cursor indexes.
    repos: Vec<Repo>,
    /// `/` narrows the repo list, for a scan root with more repos than fit.
    filter: Filter,
    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 written from a prompt before it is cut at a word boundary.
const TITLE_LENGTH: 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::Repos,
            all: Vec::new(),
            repos: Vec::new(),
            filter: Filter::default(),
            chosen: BTreeSet::new(),
            list: ListState::default().with_selected(Some(0)),
            loaded: false,
            origin: None,
        }
    }

    /// Start from a global todo, whose text is already the prompt.
    pub fn from_todo(todo: &Todo) -> Self {
        Self {
            prompt: todo.text.clone(),
            origin: Some(todo.id),
            ..Self::new()
        }
    }

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

    /// Rebuild the visible repos from the filter. Selection is by id, so what
    /// is already chosen survives being filtered out of sight.
    fn narrow(&mut self) {
        self.repos = self
            .all
            .iter()
            .filter(|repo| {
                self.filter
                    .matches_any([repo.name.as_str(), repo.path.to_str().unwrap_or("")])
            })
            .cloned()
            .collect();
        let last = self.repos.len().saturating_sub(1);
        if self.list.selected().unwrap_or(0) > last {
            self.list.select(Some(last));
        }
    }

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

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

    /// What the task will be called: what was typed, or what the prompt says.
    fn resolved_title(&self) -> String {
        let typed = self.title.trim();
        if !typed.is_empty() {
            return typed.to_string();
        }
        let from_prompt = title_from(self.prompt.trim());
        if from_prompt.chars().any(char::is_alphanumeric) {
            return from_prompt;
        }
        // `all`, not the filtered view: a repo chosen and then filtered out of
        // sight is still one this task targets.
        self.all
            .iter()
            .filter(|repo| self.chosen.contains(&repo.id))
            .map(|repo| repo.name.as_str())
            .collect::<Vec<_>>()
            .join(", ")
    }

    /// Why the task cannot be created yet, if it cannot.
    fn blocker(&self) -> Option<&'static str> {
        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");
        }
        if self.prompt.trim().is_empty() {
            return Some("describe what the agent should do");
        }
        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.resolved_title(),
            self.prompt.trim(),
            &ctx.config.workspace_root,
            &ids,
            chrono::Utc::now(),
        )?;
        Ok(task.id)
    }
}

impl NewTaskView {
    /// The title field's contents: what was typed, or the offer, dimmed.
    fn title_line(&self) -> Line<'static> {
        let focused = self.field == Field::Title;
        if !self.title.is_empty() {
            return Line::from(caret(&self.title, focused));
        }

        let dim = Style::default().add_modifier(Modifier::DIM);
        let mut spans = Vec::new();
        if focused {
            spans.push(Span::raw(""));
        }
        spans.push(match self.resolved_title() {
            // Before there is a prompt there is nothing to derive from, so the
            // field says what will happen rather than sitting empty.
            name if name.is_empty() => Span::styled("named after the prompt", dim),
            name => Span::styled(name, dim),
        });
        Line::from(spans)
    }

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

        // Repos first, and given the room that grows, because it is the field
        // you land on and the only one whose size is not up to you.
        let [repos_area, prompt_area, title_area, filter_area, hint_area] = Layout::vertical([
            Constraint::Min(4),
            Constraint::Length(6),
            Constraint::Length(3),
            Constraint::Length(self.filter.height()),
            Constraint::Length(1),
        ])
        .areas(area);
        self.filter.render(frame, filter_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 ({} of {} · {} selected){}",
                        self.repos.len(),
                        self.all.len(),
                        self.chosen.len(),
                        self.filter.label()
                    ),
                    self.field == Field::Repos,
                ))
                .highlight_style(Style::default().add_modifier(Modifier::REVERSED)),
            repos_area,
            &mut self.list,
        );

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

        frame.render_widget(
            Paragraph::new(self.title_line())
                .block(bordered("Title (optional)", self.field == Field::Title)),
            title_area,
        );

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

        // Every field on this screen is part of one form, so there is no field
        // to drop without dropping the screen: ctrl-c discards it, as esc
        // does.
        if key
            .modifiers
            .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT)
        {
            return Ok(match key.code {
                KeyCode::Char('c') => Action::Pop,
                _ => Action::None,
            });
        }

        // Only the repo list is filterable — in the other two, `/` is a
        // character someone is typing.
        if self.field == Field::Repos {
            match self.filter.handle_key(key) {
                Handled::Changed => {
                    self.narrow();
                    return Ok(Action::None);
                }
                Handled::Yes => return Ok(Action::None),
                Handled::Leave => return Ok(Action::Pop),
                Handled::No => {}
            }
        }

        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.
                    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"),
            ("/", "filter repos"),
            ("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, leaving the title to be written for us.
    fn fill(view: &mut NewTaskView, store: &mut Store) {
        press(view, store, key(KeyCode::Char(' ')));
        press(view, store, key(KeyCode::Tab));
        type_str(view, store, "fix the auth flow");
    }

    #[test]
    fn the_screen_opens_on_the_repos_and_tab_walks_down_it() {
        // Where the work goes, then what to do, then what to call it — the
        // order the decisions happen in, and the order they are drawn in.
        let mut store = store_with_repos(&["api"]);
        let mut view = NewTaskView::new();
        render_view(&mut view, &mut store, 70, 20);

        assert_eq!(view.field, Field::Repos);
        press(&mut view, &mut store, key(KeyCode::Tab));
        assert_eq!(view.field, Field::Prompt);
        press(&mut view, &mut store, key(KeyCode::Tab));
        assert_eq!(view.field, Field::Title);
        press(&mut view, &mut store, key(KeyCode::Tab));
        assert_eq!(view.field, Field::Repos, "and round again");
    }

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

        press(&mut view, &mut store, key(KeyCode::Tab));
        type_str(&mut view, &mut store, "do it");
        assert_eq!(view.prompt, "do it");
        assert!(view.title.is_empty());

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

    #[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);
        press(&mut view, &mut store, key(KeyCode::Tab));
        type_str(&mut view, &mut store, "quick fix");
        assert_eq!(view.prompt, "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);
        press(&mut view, &mut store, key(KeyCode::Tab));
        type_str(&mut view, &mut store, "abc");
        press(&mut view, &mut store, key(KeyCode::Backspace));
        assert_eq!(view.prompt, "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 repos, 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");

        press(&mut view, &mut store, key(KeyCode::Char(' ')));
        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));
        let action = press(&mut view, &mut store, key(KeyCode::Enter));

        assert!(matches!(action, Action::Pop), "enter queues from the title");
        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);
        press(&mut view, &mut store, key(KeyCode::Char(' ')));
        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 ctrl_c_discards_the_screen_and_other_chords_type_nothing() {
        // Every field here is part of one form, so there is no field to drop
        // without dropping the screen — ctrl-c is esc.
        let mut store = store_with_repos(&["api"]);
        let mut view = NewTaskView::new();
        render_view(&mut view, &mut store, 70, 20);
        press(&mut view, &mut store, key(KeyCode::Tab));
        type_str(&mut view, &mut store, "do it");
        press(&mut view, &mut store, ctrl('x'));

        assert_eq!(view.prompt, "do it", "ctrl-x must not spell an x");

        let action = press(&mut view, &mut store, ctrl('c'));
        assert!(matches!(action, Action::Pop));
        assert!(store.list_tasks().unwrap().is_empty(), "and queues nothing");
    }

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

        // Choose api, then filter it out of sight.
        press(&mut view, &mut store, key(KeyCode::Char(' ')));
        press(&mut view, &mut store, key(KeyCode::Char('/')));
        type_str(&mut view, &mut store, "wor");

        assert_eq!(view.repos.len(), 1, "only worker matches");
        assert_eq!(view.chosen.len(), 1, "api is still chosen");

        press(&mut view, &mut store, key(KeyCode::Enter));
        press(&mut view, &mut store, key(KeyCode::Char(' ')));
        assert_eq!(view.chosen.len(), 2, "and worker joins it");

        press(&mut view, &mut store, key(KeyCode::Esc));
        assert_eq!(view.repos.len(), 3, "esc puts the list back");
    }

    #[test]
    fn the_filter_is_only_on_the_repo_field() {
        // In the prompt, `/` is a character someone is typing.
        let mut store = store_with_repos(&["api"]);
        let mut view = NewTaskView::new();
        render_view(&mut view, &mut store, 70, 20);
        press(&mut view, &mut store, key(KeyCode::Tab));

        type_str(&mut view, &mut store, "src/main.rs");

        assert_eq!(view.prompt, "src/main.rs");
    }

    #[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::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("choose at least one repo with space"),
            "a task with no repos has nowhere to work"
        );
        press(&mut view, &mut store, key(KeyCode::Char(' ')));
        assert_eq!(view.blocker(), Some("describe what the agent should do"));

        // And never a word about the title, which is the point of the change.
        press(&mut view, &mut store, key(KeyCode::Tab));
        press(&mut view, &mut store, key(KeyCode::Backspace));

        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);
        press(&mut view, &mut store, key(KeyCode::Tab));
        type_str(&mut view, &mut store, "Fix auth");

        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", "a typed title wins");
        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);

        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, key(KeyCode::Tab));
        type_str(&mut view, &mut store, "change both");
        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("choose at least one repo")),
            "{screen:?}"
        );
    }

    #[test]
    fn a_task_with_no_title_is_named_after_its_prompt() {
        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);

        press(&mut view, &mut store, ctrl('s'));

        let tasks = store.list_tasks().unwrap();
        assert_eq!(tasks[0].title, "fix the auth flow");
        assert_eq!(tasks[0].prompt, "fix the auth flow", "and keeps the prompt");
    }

    #[test]
    fn a_long_prompt_is_cut_to_a_label_at_a_word() {
        let mut store = store_with_repos(&["api"]);
        let mut view = NewTaskView::new();
        render_view(&mut view, &mut store, 70, 20);
        press(&mut view, &mut store, key(KeyCode::Char(' ')));
        press(&mut view, &mut store, key(KeyCode::Tab));
        type_str(
            &mut view,
            &mut store,
            "rewrite the scheduler so a blocked agent releases its slot the \
             moment the user answers rather than on the next tick",
        );

        let title = view.resolved_title();
        assert!(title.chars().count() <= TITLE_LENGTH, "{title}");
        assert!(!title.ends_with(' '));
        assert!(
            !title.contains(''),
            "a name for a row, not a summary to read"
        );
        assert!(view.prompt.len() > title.len(), "the prompt is untouched");
    }

    #[test]
    fn only_the_first_line_of_a_prompt_becomes_the_title() {
        let mut store = store_with_repos(&["api"]);
        let mut view = NewTaskView::new();
        render_view(&mut view, &mut store, 70, 20);
        press(&mut view, &mut store, key(KeyCode::Char(' ')));
        press(&mut view, &mut store, key(KeyCode::Tab));
        type_str(&mut view, &mut store, "fix auth");
        press(&mut view, &mut store, key(KeyCode::Enter));
        type_str(&mut view, &mut store, "and the tests");

        assert_eq!(view.resolved_title(), "fix auth");
    }

    #[test]
    fn a_prompt_with_no_name_in_it_falls_back_to_the_repos() {
        // A pasted stack trace or a line of punctuation.
        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::Char(' ')));
        press(&mut view, &mut store, key(KeyCode::Char('j')));
        press(&mut view, &mut store, key(KeyCode::Char(' ')));
        press(&mut view, &mut store, key(KeyCode::Tab));
        type_str(&mut view, &mut store, "!!! ???");

        assert_eq!(view.resolved_title(), "api, web");
    }

    #[test]
    fn the_name_it_would_use_is_on_screen_before_it_is_used() {
        // The offer has to be visible, or a task named from the prompt is a
        // surprise found later in the list.
        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);
        let screen = render_view(&mut view, &mut store, 70, 20);

        assert!(
            screen.iter().any(|l| l.contains("Title (optional)")),
            "the field must say it is optional: {screen:?}"
        );
        assert!(
            screen
                .iter()
                .filter(|l| l.contains("fix the auth flow"))
                .count()
                >= 2,
            "once as the prompt, once as the name it would take: {screen:?}"
        );
    }

    #[test]
    fn an_empty_screen_says_the_title_will_be_written_for_you() {
        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("named after the prompt")),
            "with no prompt yet there is nothing to derive, so say so: {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 ctrl_s() -> KeyEvent {
        KeyEvent::new(KeyCode::Char('s'), KeyModifiers::CONTROL)
    }

    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_becomes_the_prompt_and_names_the_task() {
        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!(view.title.is_empty(), "nothing to clear before typing");
        assert_eq!(view.resolved_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);
        let title = view.resolved_title();

        assert!(title.chars().count() <= TITLE_LENGTH, "{title}");
        assert!(!title.ends_with(' '));
        assert!(
            !title.contains(''),
            "a name for a row, 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());

        // Repo, prompt, queue -- the whole screen, with nothing to tick.
        press(&mut view, &mut store, key(KeyCode::Char(' ')));
        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, ctrl_s());

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