marver 0.0.28

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
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
//! One task: its state, its worktrees, and its agent's live terminal.

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

use std::time::{Duration, Instant};

use chrono::Utc;

use super::{Action, Context, DETAIL_WORDS, Result, View, first_words, state_style};
use crate::domain::{Task, TaskState, TaskUsage};
use crate::store::Transition;
use crate::term::{DEFAULT_SCROLLBACK, Panes, keys};
use crate::tmux::{self, ControlClient, Tmux};
use crate::usage::{compact, short_model};

/// How many events to drain per tick before giving the screen back.
const DRAIN_LIMIT: usize = 512;

pub struct TaskView {
    task_id: i64,
    task: Option<Task>,
    tmux: Tmux,
    client: Option<ControlClient>,
    panes: Panes,
    pane: Option<String>,
    /// Why there is no terminal, when there is not.
    unavailable: Option<String>,
    size: (u16, u16),
    /// Whether anything has moved since the last render. Starts true so the
    /// first frame is drawn before anything has happened at all.
    dirty: bool,
    /// When the task row was last re-read, so a fast poll does not become a
    /// fast query.
    checked_task: Option<Instant>,
    /// Names of the repos this task targets, for the header.
    repos: Vec<String>,
    /// The branch its worktrees are on, once it has been launched.
    branch: Option<String>,
}

impl TaskView {
    pub fn new(task_id: i64) -> Self {
        Self {
            task_id,
            task: None,
            tmux: Tmux::new(),
            client: None,
            panes: Panes::new(tmux::DEFAULT_SIZE, DEFAULT_SCROLLBACK),
            pane: None,
            unavailable: None,
            size: tmux::DEFAULT_SIZE,
            dirty: true,
            checked_task: None,
            repos: Vec::new(),
            branch: None,
        }
    }

    /// Use a specific tmux server.
    #[cfg(test)]
    pub(crate) fn with_tmux(mut self, tmux: Tmux) -> Self {
        self.tmux = tmux;
        self
    }

    pub fn is_attached(&self) -> bool {
        self.client.is_some()
    }

    /// Attach to the task's session if it has one and we are not already on
    /// it.
    fn ensure_attached(&mut self, ctx: &mut Context) -> Result<()> {
        if self.client.is_some() {
            return Ok(());
        }
        let task = ctx.store.get_task(self.task_id)?;
        let session = task.session_name.clone();
        self.task = Some(task);

        // A name is only recorded once a session exists, so having none and
        // having a dead one are the same thing to look at. A tmux that cannot
        // be reached is a third thing, and says so rather than posing as an
        // agent that has finished.
        let live = match session.as_deref() {
            None => false,
            Some(name) => match self.tmux.session_exists(name) {
                Ok(live) => live,
                Err(err) => {
                    self.say_unavailable(format!("cannot reach tmux: {err}"));
                    return Ok(());
                }
            },
        };
        if !live {
            self.say_unavailable(match self.task.as_ref().map(|t| t.state) {
                Some(TaskState::Queued) => {
                    "not started yet — the daemon will launch it when a slot frees".to_string()
                }
                _ => match &session {
                    Some(name) => format!("no tmux session named {name}"),
                    None => "no tmux session was ever started for this task".to_string(),
                },
            });
            return Ok(());
        }
        let session = session.expect("live implies a name");

        // Either way the screen now says something different from before.
        self.dirty = true;
        match ControlClient::attach(&self.tmux, &session, self.size) {
            Ok(client) => {
                self.pane = self.tmux.list_panes(&session)?.into_iter().next();
                self.client = Some(client);
                self.unavailable = None;
            }
            Err(err) => self.unavailable = Some(format!("could not attach: {err}")),
        }
        Ok(())
    }

    /// Note that the user just answered the agent, and put the task back to
    /// work.
    fn answered(&mut self, ctx: &mut Context) {
        let Some(task) = &self.task else { return };
        if !matches!(task.state, TaskState::Blocked | TaskState::AwaitingReview) {
            return;
        }
        let id = task.id;
        self.dirty = true;
        match ctx
            .store
            .transition(id, TaskState::Running, Transition::Plain, Utc::now())
        {
            Ok(task) => self.task = Some(task),
            // Lost a race with the daemon, or the task was cancelled from
            // elsewhere.
            Err(_) => self.task = ctx.store.get_task(id).ok(),
        }
    }

    /// Re-read what the store says about this task, at most every
    /// [`super::TICK`].
    fn refresh(&mut self, ctx: &mut Context) {
        if self
            .checked_task
            .is_some_and(|at| at.elapsed() < super::TICK)
        {
            return;
        }
        // Before the read, so what it finds is in the copy this screen keeps.
        self.catch_up_on_usage(ctx);

        let task = ctx.store.get_task(self.task_id).ok();
        if task != self.task {
            self.task = task;
            self.dirty = true;
        }
        // Alongside, because a queued task names its repos before it owns a
        // worktree, and gains the branch at launch.
        self.load_repos(ctx);
        self.checked_task = Some(Instant::now());
    }

    /// Read whatever the transcript has added since anyone last looked.
    fn catch_up_on_usage(&mut self, ctx: &mut Context) {
        // Read fresh, never from `self.task`.
        let Ok(task) = ctx.store.get_task(self.task_id) else {
            return;
        };
        let Some(path) = task.usage.transcript_path.clone() else {
            return;
        };
        let Ok(usage) = crate::usage::read_from(&path, task.usage.transcript_offset) else {
            return;
        };
        // Nothing new: the offset has not moved, so writing would be a query
        // per tick to store what is already there.
        if usage.offset == task.usage.transcript_offset {
            return;
        }
        let _ = ctx.store.record_usage(task.id, &usage);
    }

    /// Read the repo names and branch this task is working in.
    fn load_repos(&mut self, ctx: &mut Context) {
        let Ok(links) = ctx.store.list_task_repos(self.task_id) else {
            return;
        };
        let names: Vec<String> = links
            .iter()
            .filter_map(|link| ctx.store.get_repo(link.repo_id).ok())
            .map(|repo| repo.name)
            .collect();
        // One branch across every repo in a task, so the first is the answer.
        let branch = links.iter().find_map(|link| link.branch.clone());
        if names != self.repos || branch != self.branch {
            self.repos = names;
            self.branch = branch;
            self.dirty = true;
        }
    }

    /// Move the view back through what the agent printed, in the emulator's own
    /// scrollback rather than tmux's — this screen is a copy of the pane, and
    /// scrolling a copy is a local matter the agent never hears about.
    fn scroll_by(&mut self, lines: isize) -> bool {
        match self.emulated() {
            Some(terminal) => terminal.scroll_by(lines),
            None => false,
        }
    }

    /// Come back to what the agent is printing now.
    fn scroll_to_live(&mut self) -> bool {
        match self.emulated() {
            Some(terminal) if terminal.scrollback() > 0 => {
                terminal.scroll_to_bottom();
                true
            }
            _ => false,
        }
    }

    /// This screen's copy of the pane it is showing.
    fn emulated(&mut self) -> Option<&mut crate::term::PaneTerminal> {
        let pane = self.pane.clone()?;
        self.panes.get_mut(&pane)
    }

    /// Say why there is nothing to show, marking a frame owed only if that is
    /// news. This path runs on every tick of a task with no session, and
    /// claiming a change each time redrew the whole screen four times a second
    /// for as long as it was open.
    fn say_unavailable(&mut self, reason: String) {
        if self.unavailable.as_deref() != Some(reason.as_str()) {
            self.dirty = true;
            self.unavailable = Some(reason);
        }
    }

    /// The agent's session is gone: stop showing it.
    ///
    /// The emulated pane goes with the client. Keeping it meant the frozen last
    /// frame kept rendering as though the agent were still there — so the
    /// message saying otherwise was never reachable, and every key typed at it
    /// was swallowed without a word.
    fn ended(&mut self) {
        self.dirty = true;
        self.unavailable = Some("the session ended".into());
        self.client = None;
        if let Some(pane) = self.pane.take() {
            self.panes.remove(&pane);
        }
    }

    /// Move whatever the agent produced into the emulator.
    fn drain(&mut self) {
        let Some(client) = &self.client else {
            return;
        };
        for _ in 0..DRAIN_LIMIT {
            match client.try_event() {
                Ok(event) => {
                    self.dirty = true;
                    if let tmux::Event::Exit { .. } = event {
                        self.ended();
                        return;
                    }
                    self.panes.apply(&event);
                }
                Err(std::sync::mpsc::TryRecvError::Empty) => return,
                // The reader thread is gone: the control connection closed
                // without an `%exit` to announce it. Treated as "nothing to
                // read" this was indistinguishable from an idle agent, so
                // `client` stayed `Some` for a session that no longer existed
                // and every key typed into it went nowhere in silence.
                Err(std::sync::mpsc::TryRecvError::Disconnected) => {
                    self.ended();
                    return;
                }
            }
        }
        // Hit the limit with more still queued: come straight back rather than
        // waiting out a poll, or a burst would arrive in visible steps.
        self.dirty = true;
    }
}

impl View for TaskView {
    fn title(&self) -> String {
        match &self.task {
            Some(task) => format!("Task {} — {}", task.id, task.title),
            None => format!("Task {}", self.task_id),
        }
    }

    fn render(&mut self, frame: &mut Frame, area: Rect, ctx: &mut Context) {
        self.refresh(ctx);
        let _ = self.ensure_attached(ctx);
        self.drain();
        // Cleared here because this is the only place that can honestly say
        // the screen now matches the view.
        self.dirty = false;

        let [info, body] =
            Layout::vertical([Constraint::Length(2), Constraint::Min(1)]).areas(area);

        if let Some(task) = &self.task {
            // Two lines, because the area has always been two tall and the
            // second was going spare.
            let mut first = vec![Span::styled(
                format!(" {} ", task.state),
                state_style(task.state).add_modifier(Modifier::BOLD),
            )];
            if !self.repos.is_empty() {
                first.push(Span::styled(
                    format!(" {}", self.repos.join(", ")),
                    Style::default().fg(Color::Cyan),
                ));
            }
            if let Some(branch) = &self.branch {
                first.push(Span::styled(
                    format!("  {branch}"),
                    Style::default().add_modifier(Modifier::DIM),
                ));
            }
            // Last on the line, so a narrow terminal drops the numbers before
            // it drops the state or the repo.
            if let Some(spent) = usage_summary(&task.usage) {
                first.push(Span::styled(
                    format!("  {spent}"),
                    Style::default().fg(Color::Magenta),
                ));
            }

            // The reason leads and the path follows, so that when the line
            // runs out of terminal it is the path that gets clipped.
            let mut second = Vec::new();
            if let Some(reason) = task
                .blocked_reason
                .as_ref()
                .or(task.failure_reason.as_ref())
            {
                // Cut like the list's detail column.
                second.push(Span::styled(
                    format!(" {}", first_words(reason, DETAIL_WORDS)),
                    Style::default().fg(Color::Yellow),
                ));
            }
            second.push(Span::styled(
                format!(" {}", task.workspace_dir.display()),
                Style::default().add_modifier(Modifier::DIM),
            ));

            frame.render_widget(
                Paragraph::new(vec![Line::from(first), Line::from(second)]),
                info,
            );
        }

        // Keep the emulator the same size as the area it is drawn into, or the
        // agent's own redraws will not line up with what is on screen.
        let inner = (body.width.saturating_sub(2), body.height.saturating_sub(2));
        if inner.0 > 0 && inner.1 > 0 && inner != self.size {
            self.size = inner;
            self.panes.resize(inner);
            if let Some(client) = &mut self.client {
                let _ = client.resize(inner.0, inner.1);
            }
        }

        let block = Block::default()
            .borders(Borders::ALL)
            .border_style(Style::default().add_modifier(Modifier::DIM))
            .title(match &self.pane {
                Some(pane) => format!("agent {pane}"),
                None => "agent".to_string(),
            });

        match self.pane.clone().and_then(|p| self.panes.get(&p)) {
            Some(term) => {
                let area = block.inner(body);
                frame.render_widget(block, body);
                frame.render_widget(term, area);
            }
            None => {
                let message = self
                    .unavailable
                    .clone()
                    .unwrap_or_else(|| "waiting for output…".into());
                frame.render_widget(
                    Paragraph::new(Line::from(Span::styled(
                        format!("  {message}"),
                        Style::default().add_modifier(Modifier::DIM),
                    )))
                    .block(block),
                    body,
                );
            }
        }
    }

    /// The wheel scrolls this screen's copy of the pane. Three lines a notch,
    /// which is what a terminal sends when it is doing the scrolling itself.
    fn handle_mouse(&mut self, mouse: MouseEvent, _ctx: &mut Context) -> Result<Action> {
        let lines = match mouse.kind {
            MouseEventKind::ScrollUp => 3,
            MouseEventKind::ScrollDown => -3,
            _ => return Ok(Action::None),
        };
        self.dirty |= self.scroll_by(lines);
        Ok(Action::None)
    }

    fn handle_key(&mut self, key: KeyEvent, ctx: &mut Context) -> Result<Action> {
        // The only key this screen keeps for itself.
        if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('q') {
            return Ok(Action::Pop);
        }

        // Typing at an agent means wanting to see what it says back, so any key
        // headed for the pane also returns the view to the live screen.
        self.dirty |= self.scroll_to_live();

        // Modified `esc`, for the terminals that can say it.
        if key
            .modifiers
            .intersects(KeyModifiers::SUPER | KeyModifiers::CONTROL)
            && key.code == KeyCode::Esc
        {
            return Ok(Action::Pop);
        }

        if let (Some(client), Some(pane)) = (self.client.as_mut(), self.pane.as_ref())
            && let Some(command) = keys::send_keys_command(pane, key)
        {
            // Only a keystroke that actually left claims anything on the
            // agent's behalf. `answered` moves a task into `running`, which
            // holds a concurrency slot, so asserting it for a write that
            // failed hands the slot to nobody. That the pane behind a
            // successful write may still have died is left to the daemon:
            // `reconcile` runs every tick and takes the slot back.
            match client.send_command(&command) {
                Ok(()) => {
                    if key.code == KeyCode::Enter {
                        self.answered(ctx);
                    }
                }
                Err(err) => {
                    self.unavailable = Some(format!("the session stopped listening: {err}"));
                    self.client = None;
                    self.dirty = true;
                }
            }
        }
        Ok(Action::None)
    }

    fn tick(&mut self, ctx: &mut Context) -> Result<()> {
        // How a state change made by the daemon reaches the header.
        if self
            .checked_task
            .is_none_or(|at| at.elapsed() >= super::TICK)
        {
            let task = ctx.store.get_task(self.task_id).ok();
            if task != self.task {
                self.task = task;
                self.dirty = true;
            }
            self.checked_task = Some(Instant::now());
        }
        self.ensure_attached(ctx)?;
        self.drain();
        Ok(())
    }

    /// The pane's output arrives on a channel the event loop cannot wait on,
    /// so the loop has to come back and look. See [`crate::tui::LIVE_TICK`].
    fn poll_interval(&self) -> Duration {
        if self.client.is_some() {
            crate::tui::LIVE_TICK
        } else {
            super::TICK
        }
    }

    fn dirty(&self) -> bool {
        self.dirty
    }

    fn keys(&self) -> Vec<(&'static str, &'static str)> {
        vec![("^esc/^q", "back"), ("any", "→ agent")]
    }

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

/// What the agent has spent, in one short phrase — `opus-5 · 310k ctx · 334k
/// out`.
pub(super) fn usage_summary(usage: &TaskUsage) -> Option<String> {
    if !usage.is_known() {
        return None;
    }
    let mut parts = Vec::new();
    if let Some(model) = &usage.model {
        parts.push(short_model(model));
    }
    if let Some(context) = usage.context_tokens {
        parts.push(format!("{} ctx", compact(context)));
    }
    if let Some(output) = usage.output_tokens {
        parts.push(format!("{} out", compact(output)));
    }
    Some(parts.join(" · "))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::domain::Repo;
    use crate::git::testing::init_repo;
    use crate::launcher::Launcher;
    use crate::store::{Store, Transition};
    use crate::tmux::testing::TestServer;
    use crate::tui::testing::{press, render_view, tick_view, wheel};
    use crate::worktree::WorktreeManager;
    use chrono::{DateTime, Utc};
    use std::path::PathBuf;
    use tempfile::TempDir;

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

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

    struct Fixture {
        _tmp: TempDir,
        server: TestServer,
        store: Store,
        launcher: Launcher,
        tasks_dir: PathBuf,
        repos_dir: PathBuf,
    }

    impl Fixture {
        fn new() -> Self {
            let tmp = TempDir::new().unwrap();
            let server = TestServer::new();
            let repos_dir = tmp.path().join("repos");
            let tasks_dir = tmp.path().join("tasks");
            std::fs::create_dir_all(&repos_dir).unwrap();
            let launcher = Launcher::new(
                server.tmux.clone(),
                WorktreeManager::new(&tasks_dir),
                PathBuf::from("/bin/marver"),
                tmp.path().join("m.sock"),
            )
            .harness(crate::launcher::testing::stub_agent(tmp.path()));
            Self {
                store: Store::open_in_memory().unwrap(),
                launcher,
                tasks_dir,
                repos_dir,
                server,
                _tmp: tmp,
            }
        }

        fn repo(&self, name: &str) -> Repo {
            let path = self.repos_dir.join(name);
            init_repo(&path, "main");
            self.store.upsert_repo(&path, name, at(0)).unwrap()
        }

        fn queued(&mut self, title: &str, repos: &[Repo]) -> Task {
            let ids: Vec<i64> = repos.iter().map(|r| r.id).collect();
            self.store
                .create_task(title, "do it", &self.tasks_dir, &ids, at(0))
                .unwrap()
        }

        fn launched(&mut self, title: &str) -> Task {
            let repo = self.repo("api");
            let task = self.queued(title, std::slice::from_ref(&repo));
            self.launcher.launch(&mut self.store, &task, at(1)).unwrap();
            self.store
                .transition(task.id, TaskState::Running, Transition::Plain, at(2))
                .unwrap();
            self.store.get_task(task.id).unwrap()
        }

        fn view(&self, task: &Task) -> TaskView {
            TaskView::new(task.id).with_tmux(self.server.tmux.clone())
        }
    }

    /// Walk a launched task to `state`, and give the view its current copy.
    fn sitting_in(fx: &mut Fixture, task: &Task, state: TaskState) -> TaskView {
        if state == TaskState::AwaitingReview {
            fx.store
                .transition(task.id, TaskState::AwaitingReview, Transition::Plain, at(3))
                .unwrap();
        } else {
            fx.store
                .transition(
                    task.id,
                    TaskState::Blocked,
                    Transition::Blocked(crate::store::BlockedInfo::new(
                        crate::domain::BlockedKind::PermissionPrompt,
                    )),
                    at(3),
                )
                .unwrap();
        }
        let mut view = fx.view(task);
        render_view(&mut view, &mut fx.store, 80, 12);
        view
    }

    #[test]
    fn answering_the_agent_puts_the_task_back_to_work() {
        // Claude Code emits no hook when a prompt is answered, so the
        // keystroke answering it is the only evidence marver gets.
        for state in [TaskState::Blocked, TaskState::AwaitingReview] {
            let mut fx = Fixture::new();
            let task = fx.launched("fix auth");
            let mut view = sitting_in(&mut fx, &task, state);
            assert!(view.is_attached(), "the pane must be live for {state}");

            for c in "carry on".chars() {
                press(&mut view, &mut fx.store, key(KeyCode::Char(c)));
            }
            assert_eq!(
                fx.store.get_task(task.id).unwrap().state,
                state,
                "typing alone is not an answer"
            );

            press(&mut view, &mut fx.store, key(KeyCode::Enter));

            assert_eq!(
                fx.store.get_task(task.id).unwrap().state,
                TaskState::Running,
                "submitting from {state} should resume the task"
            );
        }
    }

    #[test]
    fn the_wheel_scrolls_this_screens_copy_and_never_reaches_the_agent() {
        // A wheel notch used to arrive as `↑`, which this screen forwards to
        // the agent — in Claude Code that recalls the previous prompt into the
        // input box instead of scrolling anything.
        let mut fx = Fixture::new();
        let task = fx.launched("fix auth");
        let mut view = fx.view(&task);
        // A pane with more output than fits, without needing a live agent.
        view.pane = Some("%0".into());
        let pane = view.panes.ensure("%0");
        for n in 0..60 {
            pane.feed(format!("line {n}\r\n").as_bytes());
        }

        wheel(&mut view, &mut fx.store, true);

        assert_eq!(
            view.panes.get("%0").unwrap().scrollback(),
            3,
            "three lines a notch, as a terminal would scroll"
        );
        assert!(view.client.is_none(), "and nothing was sent to the agent");
    }

    #[test]
    fn typing_at_the_agent_comes_back_to_what_it_is_saying_now() {
        // Scrolled up and then answering means wanting to see the reply.
        let mut fx = Fixture::new();
        let task = fx.launched("fix auth");
        let mut view = fx.view(&task);
        view.pane = Some("%0".into());
        let pane = view.panes.ensure("%0");
        for n in 0..60 {
            pane.feed(format!("line {n}\r\n").as_bytes());
        }
        wheel(&mut view, &mut fx.store, true);
        assert_eq!(view.panes.get("%0").unwrap().scrollback(), 3);

        press(&mut view, &mut fx.store, key(KeyCode::Char('h')));

        assert_eq!(view.panes.get("%0").unwrap().scrollback(), 0);
    }

    #[test]
    fn the_header_says_what_the_agent_has_spent() {
        let mut fx = Fixture::new();
        let task = fx.launched("fix auth");
        fx.store
            .record_usage(
                task.id,
                &crate::usage::Usage {
                    model: Some("claude-opus-5".into()),
                    context_tokens: Some(309_115),
                    output_tokens: 333_355,
                    offset: 2_027_264,
                    start: 0,
                },
            )
            .unwrap();
        let mut view = fx.view(&task);

        let screen = render_view(&mut view, &mut fx.store, 120, 12);

        assert!(screen[0].contains("opus-5"), "{screen:?}");
        assert!(screen[0].contains("310k ctx"), "{screen:?}");
        assert!(screen[0].contains("334k out"), "{screen:?}");
    }

    #[test]
    fn opening_a_finished_task_reads_the_tokens_no_hook_ever_reported() {
        // A task in `awaiting-review` has finished, so no further hook is
        // coming and its last turn was never accounted for.
        use std::io::Write;
        let mut fx = Fixture::new();
        let task = fx.launched("fix auth");
        let path = fx._tmp.path().join("session.jsonl");
        let mut file = std::fs::File::create(&path).unwrap();
        writeln!(
            file,
            r#"{{"type":"assistant","message":{{"model":"claude-opus-5","usage":{{"input_tokens":900,"cache_read_input_tokens":100,"cache_creation_input_tokens":0,"output_tokens":42}}}}}}"#
        )
        .unwrap();
        fx.store.set_transcript_path(task.id, &path).unwrap();

        let mut view = fx.view(&task);
        // First pass reads the task and finds the path; the second, past the
        // throttle, is the one that can use it.
        render_view(&mut view, &mut fx.store, 120, 12);
        view.checked_task = None;
        let screen = render_view(&mut view, &mut fx.store, 120, 12);

        assert!(screen[0].contains("opus-5"), "{screen:?}");
        assert!(screen[0].contains("1000 ctx"), "{screen:?}");
        assert!(screen[0].contains("42 out"), "{screen:?}");
    }

    #[test]
    fn a_screen_left_open_stops_rereading_once_it_has_caught_up() {
        // Refresh runs every TICK for as long as the screen is open.
        use std::io::Write;
        let mut fx = Fixture::new();
        let task = fx.launched("fix auth");
        let path = fx._tmp.path().join("session.jsonl");
        let mut file = std::fs::File::create(&path).unwrap();
        writeln!(
            file,
            r#"{{"type":"assistant","message":{{"model":"claude-opus-5","usage":{{"output_tokens":42}}}}}}"#
        )
        .unwrap();
        fx.store.set_transcript_path(task.id, &path).unwrap();
        let mut view = fx.view(&task);

        for _ in 0..4 {
            view.checked_task = None;
            render_view(&mut view, &mut fx.store, 120, 12);
        }

        assert_eq!(
            fx.store.get_task(task.id).unwrap().usage.output_tokens,
            Some(42),
            "the same turn must not be counted once per tick"
        );
    }

    #[test]
    fn catching_up_does_not_recount_what_the_daemon_already_read() {
        // Both the daemon and this screen read the same transcript -- one on
        // every hook, the other on every tick.
        use std::io::Write;
        let mut fx = Fixture::new();
        let task = fx.launched("fix auth");
        let path = fx._tmp.path().join("session.jsonl");
        let turn = |file: &mut std::fs::File, out: u64| {
            writeln!(
                file,
                r#"{{"type":"assistant","message":{{"model":"claude-opus-5","usage":{{"output_tokens":{out}}}}}}}"#
            )
            .unwrap();
        };
        let mut file = std::fs::File::create(&path).unwrap();
        turn(&mut file, 100);
        fx.store.set_transcript_path(task.id, &path).unwrap();

        // The screen reads the first turn and caches the task as it then was.
        let mut view = fx.view(&task);
        render_view(&mut view, &mut fx.store, 120, 12);
        assert_eq!(
            fx.store.get_task(task.id).unwrap().usage.output_tokens,
            Some(100)
        );

        // The agent produces another turn, and the daemon's hook reads it.
        let mut file = std::fs::OpenOptions::new()
            .append(true)
            .open(&path)
            .unwrap();
        turn(&mut file, 50);
        let offset = fx.store.get_task(task.id).unwrap().usage.transcript_offset;
        let read = crate::usage::read_from(&path, offset).unwrap();
        fx.store.record_usage(task.id, &read).unwrap();
        assert_eq!(
            fx.store.get_task(task.id).unwrap().usage.output_tokens,
            Some(150)
        );

        // Now the screen refreshes, holding a copy from before that hook.
        view.checked_task = None;
        render_view(&mut view, &mut fx.store, 120, 12);

        assert_eq!(
            fx.store.get_task(task.id).unwrap().usage.output_tokens,
            Some(150),
            "the second turn must not be counted once per reader"
        );
    }

    #[test]
    fn a_task_that_has_spent_nothing_yet_says_nothing() {
        // Unknown is not zero.
        let mut fx = Fixture::new();
        let task = fx.launched("fix auth");
        let mut view = fx.view(&task);

        let screen = render_view(&mut view, &mut fx.store, 120, 12);

        assert!(!screen[0].contains("ctx"), "{screen:?}");
        assert!(!screen[0].contains(" out"), "{screen:?}");
    }

    #[test]
    fn the_summary_shows_whatever_is_known_and_leaves_out_what_is_not() {
        // The transcript format carries no promises, so any field may be
        // missing.
        assert_eq!(usage_summary(&TaskUsage::default()), None);
        assert_eq!(
            usage_summary(&TaskUsage {
                model: Some("claude-sonnet-5".into()),
                ..TaskUsage::default()
            }),
            Some("sonnet-5".to_string())
        );
        assert_eq!(
            usage_summary(&TaskUsage {
                context_tokens: Some(12_000),
                output_tokens: Some(400),
                ..TaskUsage::default()
            }),
            Some("12k ctx · 400 out".to_string())
        );
    }

    #[test]
    fn the_header_names_the_repo_being_worked_in() {
        // The workspace path names the task, not what is inside it.
        let mut fx = Fixture::new();
        let task = fx.launched("fix auth");
        let mut view = fx.view(&task);

        let screen = render_view(&mut view, &mut fx.store, 100, 12);
        assert!(
            screen[0].contains("api"),
            "the repo should be on the first line: {screen:?}"
        );
        assert!(
            screen[0].contains(&format!("marver/{}", task.id)),
            "and the branch it is on: {screen:?}"
        );
        assert!(
            screen[1].contains(&task.workspace_dir.display().to_string()),
            "the path moves to the second line: {screen:?}"
        );
    }

    #[test]
    fn a_multi_repo_task_names_every_repo() {
        let mut fx = Fixture::new();
        let api = fx.repo("api");
        let web = fx.repo("web");
        let task = fx.queued("cross-cutting", &[api, web]);
        let mut view = fx.view(&task);

        let screen = render_view(&mut view, &mut fx.store, 100, 12);
        assert!(screen[0].contains("api"), "{screen:?}");
        assert!(screen[0].contains("web"), "{screen:?}");
    }

    #[test]
    fn a_long_reason_is_cut_instead_of_taking_the_header_with_it() {
        let mut fx = Fixture::new();
        let task = fx.launched("fix auth");
        fx.store
            .transition(
                task.id,
                TaskState::Blocked,
                Transition::Blocked(crate::store::BlockedInfo::with_reason(
                    crate::domain::BlockedKind::PermissionPrompt,
                    "Claude needs your permission to run a command that will\ntouch \
                     several files across the repository and cannot be undone",
                )),
                at(3),
            )
            .unwrap();
        let mut view = fx.view(&task);

        let screen = render_view(&mut view, &mut fx.store, 100, 12);
        let header = format!("{}{}", screen[0], screen[1]);

        assert!(header.contains("Claude needs your"), "{header:?}");
        assert!(header.contains('…'), "it should say it was cut: {header:?}");
        assert!(
            !header.contains("cannot be undone"),
            "the tail belongs in the pane, not the header: {header:?}"
        );
        // The newline in the middle must not have become a third line.
        assert!(
            screen[2].trim().is_empty() || screen[2].contains('┌'),
            "the header stayed two lines: {screen:?}"
        );
    }

    /// What one wakeup of an attached-but-quiet pane costs.
    #[test]
    #[ignore = "measures, does not assert"]
    fn bench_idle_wakeup() {
        let mut fx = Fixture::new();
        let task = fx.launched("fix auth");
        let mut view = fx.view(&task);
        render_view(&mut view, &mut fx.store, 120, 40);
        // Let the agent's startup output finish arriving, so "quiet" is true.
        for _ in 0..40 {
            tick_view(&mut view, &mut fx.store);
            render_view(&mut view, &mut fx.store, 120, 40);
            std::thread::sleep(std::time::Duration::from_millis(25));
        }

        let rounds = 10_000;
        let started = std::time::Instant::now();
        for _ in 0..rounds {
            tick_view(&mut view, &mut fx.store);
        }
        let each = started.elapsed() / rounds;
        let duty = each.as_secs_f64() / crate::tui::LIVE_TICK.as_secs_f64() * 100.0;
        println!(
            "idle wakeup: {each:?} each, {duty:.3}% of one core at {:?} polling",
            crate::tui::LIVE_TICK
        );
        assert!(!view.dirty(), "a quiet pane should still owe no frame");

        // And the same screen when it does have to draw.
        let rounds = 500;
        let started = std::time::Instant::now();
        for _ in 0..rounds {
            render_view(&mut view, &mut fx.store, 120, 40);
        }
        println!(
            "full render: {:?} each at 120x40",
            started.elapsed() / rounds
        );
    }

    #[test]
    fn a_live_pane_asks_to_be_looked_at_often() {
        // event::poll watches stdin only, and pane output arrives on a channel
        // the loop cannot wait on.
        let mut fx = Fixture::new();
        // Not "api": `launched` creates that one itself, and re-initialising a
        // repo that already has its first commit fails.
        let repo = fx.repo("web");
        let queued = fx.queued("waiting", std::slice::from_ref(&repo));
        let mut idle = fx.view(&queued);
        render_view(&mut idle, &mut fx.store, 80, 12);
        assert!(!idle.is_attached());
        assert_eq!(
            idle.poll_interval(),
            crate::tui::TICK,
            "a screen with nothing live behind it should not spin"
        );

        let task = fx.launched("fix auth");
        let mut live = fx.view(&task);
        render_view(&mut live, &mut fx.store, 80, 12);
        assert!(live.is_attached());
        assert_eq!(live.poll_interval(), crate::tui::LIVE_TICK);
    }

    #[test]
    fn a_quiet_pane_costs_no_redraws() {
        // The other half of polling at 8ms: looking often must not mean
        // drawing often, or the fix for latency becomes 125 frames a second of
        // nothing.
        let mut fx = Fixture::new();
        let task = fx.launched("fix auth");
        let mut view = fx.view(&task);

        render_view(&mut view, &mut fx.store, 80, 12);
        // Settle: the agent's own startup output has to finish arriving before
        // "quiet" means anything.
        for _ in 0..40 {
            tick_view(&mut view, &mut fx.store);
            render_view(&mut view, &mut fx.store, 80, 12);
            std::thread::sleep(std::time::Duration::from_millis(25));
        }

        assert!(!view.dirty(), "a rendered view owes nothing");
        tick_view(&mut view, &mut fx.store);
        assert!(
            !view.dirty(),
            "a tick that drained nothing must not ask for a frame"
        );
    }

    #[test]
    fn output_from_the_agent_asks_for_a_frame() {
        let mut fx = Fixture::new();
        let task = fx.launched("fix auth");
        let mut view = fx.view(&task);
        render_view(&mut view, &mut fx.store, 80, 12);

        // Make the agent say something, then let it arrive.
        let pane = view.pane.clone().unwrap();
        fx.server
            .tmux
            .send_keys(&pane, "echo MARVERECHO")
            .expect("type");
        fx.server.tmux.send_key(&pane, "Enter").expect("enter");

        let mut asked = false;
        for _ in 0..80 {
            tick_view(&mut view, &mut fx.store);
            if view.dirty() {
                asked = true;
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(25));
        }
        assert!(asked, "output must mark the view as owing a frame");
    }

    #[test]
    fn answering_a_task_that_is_already_running_changes_nothing() {
        let mut fx = Fixture::new();
        let task = fx.launched("fix auth");
        let mut view = fx.view(&task);
        render_view(&mut view, &mut fx.store, 80, 12);

        let before = fx.store.get_task(task.id).unwrap();
        press(&mut view, &mut fx.store, key(KeyCode::Enter));
        let after = fx.store.get_task(task.id).unwrap();

        // A no-op, not a self-transition: the store forbids those, and writing
        // a `task.transition` event per keystroke would bury the real ones.
        assert_eq!(after.state, TaskState::Running);
        assert_eq!(after.updated_at, before.updated_at);
    }

    #[test]
    fn a_finished_task_is_not_revived_by_a_keystroke() {
        let mut fx = Fixture::new();
        let task = fx.launched("fix auth");
        fx.store
            .transition(task.id, TaskState::Cancelled, Transition::Plain, at(3))
            .unwrap();
        let mut view = fx.view(&task);
        render_view(&mut view, &mut fx.store, 80, 12);

        press(&mut view, &mut fx.store, key(KeyCode::Enter));

        assert_eq!(
            fx.store.get_task(task.id).unwrap().state,
            TaskState::Cancelled,
            "terminal states never resume"
        );
    }

    #[test]
    fn a_queued_task_explains_why_there_is_no_terminal() {
        let mut fx = Fixture::new();
        let repo = fx.repo("api");
        let task = fx.queued("waiting", std::slice::from_ref(&repo));
        let mut view = fx.view(&task);

        let screen = render_view(&mut view, &mut fx.store, 70, 12);
        assert!(
            screen.iter().any(|l| l.contains("not started yet")),
            "an empty pane should not look broken: {screen:?}"
        );
        assert!(!view.is_attached());
    }

    #[test]
    fn the_header_shows_the_state_and_workspace() {
        let mut fx = Fixture::new();
        let task = fx.launched("fix auth");
        let mut view = fx.view(&task);

        let screen = render_view(&mut view, &mut fx.store, 100, 12);
        assert!(screen[0].contains("running"), "{screen:?}");
        assert!(
            screen[0].contains(&task.id.to_string()),
            "the workspace path names the task: {screen:?}"
        );
    }

    #[test]
    fn a_launched_task_attaches_and_shows_its_agent() {
        let mut fx = Fixture::new();
        let task = fx.launched("fix auth");
        let mut view = fx.view(&task);

        // Poll: the agent's output arrives asynchronously over control mode.
        let mut screen = Vec::new();
        for _ in 0..80 {
            screen = render_view(&mut view, &mut fx.store, 100, 16);
            if screen.iter().any(|l| l.contains("ARG[do it]")) {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(50));
        }

        assert!(view.is_attached(), "should have a control connection");
        assert!(
            screen.iter().any(|l| l.contains("ARG[do it]")),
            "the agent's output should reach the screen: {screen:?}"
        );
    }

    #[test]
    fn typing_reaches_the_agents_pane() {
        let mut fx = Fixture::new();
        let task = fx.launched("fix auth");
        let mut view = fx.view(&task);
        for _ in 0..40 {
            render_view(&mut view, &mut fx.store, 100, 16);
            if view.is_attached() {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(50));
        }
        assert!(view.is_attached());

        for c in "printf MARVERTYPED".chars() {
            press(&mut view, &mut fx.store, key(KeyCode::Char(c)));
        }
        press(&mut view, &mut fx.store, key(KeyCode::Enter));

        let pane = view.pane.clone().unwrap();
        let mut captured = String::new();
        for _ in 0..80 {
            captured = fx.server.tmux.capture_pane(&pane).unwrap();
            if captured.contains("MARVERTYPED") {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(50));
        }
        assert!(
            captured.contains("MARVERTYPED"),
            "keys must reach the real pane: {captured:?}"
        );
    }

    #[test]
    fn ctrl_bracket_leaves_but_ordinary_keys_do_not() {
        let mut fx = Fixture::new();
        let task = fx.launched("fix auth");
        let mut view = fx.view(&task);
        render_view(&mut view, &mut fx.store, 80, 12);

        // These all belong to the agent.
        for code in [KeyCode::Char('q'), KeyCode::Esc, KeyCode::Char('c')] {
            assert!(
                matches!(press(&mut view, &mut fx.store, key(code)), Action::None),
                "{code:?} must go to the agent, not close the screen"
            );
        }

        // cmd-esc, where the terminal can report it.
        let mut fx = Fixture::new();
        let task = fx.launched("fix auth");
        let mut view = fx.view(&task);
        render_view(&mut view, &mut fx.store, 80, 12);
        let chord = KeyEvent::new(KeyCode::Esc, KeyModifiers::SUPER);
        assert!(matches!(
            press(&mut view, &mut fx.store, chord),
            Action::Pop
        ));

        let mut view = fx.view(&task);
        render_view(&mut view, &mut fx.store, 80, 12);
        let chord = KeyEvent::new(KeyCode::Char('q'), KeyModifiers::CONTROL);
        assert!(
            matches!(press(&mut view, &mut fx.store, chord), Action::Pop),
            "ctrl-q must leave; there is no other way out"
        );

        // ctrl-] was a second way out and is not one any more, so it belongs
        // to the agent like every other key.
        for code in [KeyCode::Char(']'), KeyCode::Char('5')] {
            let mut view = fx.view(&task);
            render_view(&mut view, &mut fx.store, 80, 12);
            let chord = KeyEvent::new(code, KeyModifiers::CONTROL);
            assert!(
                matches!(press(&mut view, &mut fx.store, chord), Action::None),
                "ctrl+{code:?} is the agent's now"
            );
        }
    }

    #[test]
    fn killing_the_session_is_reported_rather_than_hanging() {
        let mut fx = Fixture::new();
        let task = fx.launched("fix auth");
        let mut view = fx.view(&task);
        for _ in 0..40 {
            render_view(&mut view, &mut fx.store, 80, 12);
            if view.is_attached() {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(50));
        }

        fx.server
            .tmux
            .kill_session(&tmux::session_name(None, task.id))
            .unwrap();

        let mut screen = Vec::new();
        for _ in 0..80 {
            screen = render_view(&mut view, &mut fx.store, 80, 12);
            if screen.iter().any(|l| l.contains("session ended")) {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(50));
        }
        assert!(
            screen.iter().any(|l| l.contains("session ended")),
            "a vanished agent should say so: {screen:?}"
        );
    }
}