marver 0.0.11

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
//! One task: its state, its worktrees, and its agent's live terminal.
//!
//! The terminal is the point of this screen, so it captures every key. Leaving
//! needs a chord (`ctrl-]`) rather than `esc` or `q`, both of which an agent
//! session legitimately wants — `esc` interrupts Claude, and `q` is just a
//! letter.

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, Paragraph};

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

use chrono::Utc;

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

/// How many events to drain per tick before giving the screen back.
///
/// A busy agent produces output faster than 4 redraws a second, so an unbounded
/// drain would stall rendering while it caught up.
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>,
}

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,
        }
    }

    /// Use a specific tmux server.
    ///
    /// Test-only. A real screen attaches to the session the daemon made on the
    /// user's own tmux; pointing it elsewhere only makes sense for a test on a
    /// private socket, which must never reach the real 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()
            .unwrap_or_else(|| tmux::session_name(task.id));
        self.task = Some(task);

        if !self.tmux.has_session(&session) {
            self.dirty = true;
            self.unavailable = Some(match self.task.as_ref().map(|t| t.state) {
                Some(TaskState::Queued) => {
                    "not started yet — the daemon will launch it when a slot frees".into()
                }
                _ => format!("no tmux session named {session}"),
            });
            return Ok(());
        }

        // 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.
    ///
    /// Claude Code emits no hook when a prompt is answered, so the keystroke
    /// that answers it is the only evidence marver ever gets. Without this a
    /// task sat in `blocked` or `awaiting-review` while its agent was plainly
    /// working — and worse for `awaiting-review`, which holds no concurrency
    /// slot, so the scheduler could start another agent on top of it. The
    /// closing `Stop` did not rescue it either: it asks for `awaiting-review`,
    /// which is where the task already was, so it was recorded and discarded.
    ///
    /// Enter, not any key. It is what submits in every Claude Code prompt —
    /// a message, a permission choice, a menu selection — while the keys that
    /// merely move around inside one should not claim the agent is working.
    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. The keystroke has already gone to the agent and there
            // is nothing useful to say about it here.
            Err(_) => self.task = ctx.store.get_task(id).ok(),
        }
    }

    /// Move whatever the agent produced into the emulator.
    ///
    /// Sets [`Self::dirty`] when anything arrived, which is what tells the event
    /// loop a frame is owed. Nothing arriving is the common case while the user
    /// reads, and it must not cost a redraw.
    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.unavailable = Some("the session ended".into());
                        self.client = None;
                        return;
                    }
                    self.panes.apply(&event);
                }
                Err(_) => 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) {
        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. Anything `drain` picked up above is about
        // to be drawn, so it does not carry over.
        self.dirty = false;

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

        if let Some(task) = &self.task {
            let mut spans = vec![
                Span::styled(
                    format!(" {} ", task.state),
                    state_style(task.state).add_modifier(Modifier::BOLD),
                ),
                Span::styled(
                    task.workspace_dir.display().to_string(),
                    Style::default().add_modifier(Modifier::DIM),
                ),
            ];
            if let Some(reason) = task
                .blocked_reason
                .as_ref()
                .or(task.failure_reason.as_ref())
            {
                spans.push(Span::styled(
                    format!("  {reason}"),
                    Style::default().fg(Color::Yellow),
                ));
            }
            frame.render_widget(Paragraph::new(Line::from(spans)), 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,
                );
            }
        }
    }

    fn handle_key(&mut self, key: KeyEvent, ctx: &mut Context) -> Result<Action> {
        // The only key this screen keeps for itself. `esc` belongs to the agent
        // and `q` is a letter.
        //
        // Both spellings, because a terminal without the keyboard-enhancement
        // flags cannot say "ctrl and a bracket": it sends 0x1d, and crossterm
        // reports that as `Char('5') + CONTROL`. Matching only `']'` meant the
        // one way out of this screen never fired, and since the encoder dropped
        // the key too it was not even forwarded — the user had to kill marver.
        if key.modifiers.contains(KeyModifiers::CONTROL)
            && matches!(key.code, KeyCode::Char(']') | KeyCode::Char('5'))
        {
            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)
        {
            let _ = client.send_command(&command);
            if key.code == KeyCode::Enter {
                self.answered(ctx);
            }
        }
        Ok(Action::None)
    }

    fn tick(&mut self, ctx: &mut Context) -> Result<()> {
        // How a state change made by the daemon reaches the header. Re-read on
        // its own schedule rather than every poll: this screen is now polled at
        // `LIVE_TICK`, and a query 125 times a second to notice something that
        // changes a few times an hour would be a poor trade.
        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 [`super::LIVE_TICK`].
    fn poll_interval(&self) -> Duration {
        if self.client.is_some() {
            super::LIVE_TICK
        } else {
            super::TICK
        }
    }

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

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

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

#[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};
    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"),
            )
            .agent(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. Without this the task
        // sat in blocked or awaiting-review while its agent was plainly working.
        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 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. At TICK the loop was asleep when a keystroke
        // echoed back, so every character appeared up to 250ms after typing.
        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"
            );
        }

        // Both spellings of the chord. A terminal in legacy encoding — which is
        // what marver asks for — sends 0x1d, which crossterm reports as
        // `Char('5') + CONTROL`; `Char(']')` is what a synthesised event looks
        // like, and testing only that is how this screen became inescapable.
        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::Pop),
                "ctrl+{code:?} must leave; there is no other way out"
            );
        }
    }

    #[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(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:?}"
        );
    }
}