voc 0.1.1

Voc Agent — the Rust terminal cockpit for Vibecrafted
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
pub mod app;
pub mod config;
pub mod launch;
pub mod mission_control;
pub mod mux;
pub mod polarize;
pub mod skills_catalog;
pub mod state;
pub mod ui;

use anyhow::Context;
use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyModifiers};
use crossterm::execute;
use crossterm::terminal::{
    EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
};
use notify::{Config as NotifyConfig, RecommendedWatcher, RecursiveMode, Watcher};
use ratatui::Terminal;
use ratatui::backend::CrosstermBackend;
use std::io;
use std::path::{Path, PathBuf};
use std::process::Output;
use std::sync::mpsc::{self, Sender};
use std::thread;
use std::time::{Duration, Instant};

pub use app::{App, AppTab, DeepAction, DispatchFocus, LaunchFocus, QueueScope};
pub use config::{AppConfig, CliOptions, build_config, parse_args};
pub use launch::{LaunchCommand, LaunchKind};
pub use mission_control::{
    ActionPriority, ActionQueueItem, ActionQueueKind, ActiveDispatch, AgentStatsRow, DataQuality,
    FailureEntry, FleetHealthSignal, FleetHealthStatus, MissionControlState, SkillStatsRow,
    WaveSegment, WaveState, default_artifact_root,
};
pub use polarize::{PolarizeBand, PolarizeIntent};
pub use skills_catalog::{SkillAgent, SkillEntry, SkillPayload, SkillPayloadKind};

pub fn run_cli() -> anyhow::Result<()> {
    let options = parse_args()?;
    let config = build_config(options);
    let rt = tokio::runtime::Runtime::new()?;
    let _guard = rt.enter();
    run_app(config)
}

fn run_app(config: AppConfig) -> anyhow::Result<()> {
    enable_raw_mode().context("failed to enable raw mode")?;
    let mut stdout = io::stdout();
    execute!(stdout, EnterAlternateScreen)?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;

    let result = (|| -> anyhow::Result<()> {
        let mut app = App::new(config)?;
        let (watch_tx, watch_rx) = mpsc::channel();
        let _watcher = match start_state_watcher(&app.config.state_root, watch_tx) {
            Ok(watcher) => Some(watcher),
            Err(error) => {
                app.append_status(format!("watcher unavailable: {error}"));
                None
            }
        };
        let mut last_tick = Instant::now();
        loop {
            terminal.draw(|frame| ui::draw(frame, &app))?;
            let timeout = app
                .config
                .tick_rate
                .checked_sub(last_tick.elapsed())
                .unwrap_or(Duration::ZERO);

            if event::poll(timeout)?
                && let Event::Key(key) = event::read()?
                && handle_key(&mut app, key)?
            {
                break;
            }

            let mut watched_change = false;
            while watch_rx.try_recv().is_ok() {
                watched_change = true;
            }
            let mut events = Vec::new();
            if let Some(sub) = &app.mux_subscriber {
                while let Ok(event) = sub.rx.try_recv() {
                    events.push(event);
                }
            }
            if !events.is_empty() {
                for event in events {
                    app.handle_ipc_event(event);
                }
                watched_change = true;
            }
            if watched_change {
                app.refresh();
                last_tick = Instant::now();
            }

            if last_tick.elapsed() >= app.config.tick_rate {
                app.refresh();
                last_tick = Instant::now();
            }
        }
        Ok(())
    })();

    shutdown_terminal(&mut terminal)?;
    result
}

fn shutdown_terminal(terminal: &mut Terminal<CrosstermBackend<io::Stdout>>) -> anyhow::Result<()> {
    disable_raw_mode().context("failed to disable raw mode")?;
    execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
    terminal.show_cursor()?;
    Ok(())
}

fn handle_key(app: &mut App, key: KeyEvent) -> anyhow::Result<bool> {
    if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('c') {
        return Ok(true);
    }

    match app.focus {
        LaunchFocus::EditPrompt => match key.code {
            KeyCode::Char('?') => {
                app.focus = LaunchFocus::Help;
            }
            KeyCode::Esc => {
                app.finish_prompt_edit();
            }
            KeyCode::Char('s') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                app.finish_prompt_edit();
            }
            KeyCode::Enter => {
                app.launch_prompt.push('\n');
            }
            KeyCode::Backspace => {
                app.launch_prompt.pop();
            }
            KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
                app.launch_prompt.push(c);
            }
            _ => {}
        },
        LaunchFocus::Search => match key.code {
            KeyCode::Esc | KeyCode::Enter => {
                app.focus = LaunchFocus::Browse;
                if app.search_query.is_empty() {
                    app.append_status("search closed");
                } else {
                    app.append_status(format!(
                        "search: {} ({} runs visible)",
                        app.search_query,
                        app.runs.len()
                    ));
                }
            }
            KeyCode::Backspace => {
                let mut query = app.search_query.clone();
                query.pop();
                app.set_search_query(query);
            }
            KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
                let mut query = app.search_query.clone();
                query.push(c);
                app.set_search_query(query);
            }
            _ => {}
        },
        LaunchFocus::Error => match key.code {
            KeyCode::Char('f') | KeyCode::Char('F')
                if app
                    .error_lines
                    .iter()
                    .any(|l| l.contains("Client drift detected")) =>
            {
                let agent = app.selected_agent().to_string();
                let _ = std::process::Command::new("zellij")
                    .args([
                        "run",
                        "--name",
                        "auto-rewire",
                        "--",
                        "rmcp-mux",
                        "wizard",
                        "--strategy",
                        "auto-rewire",
                        &agent,
                    ])
                    .spawn();
                app.focus = LaunchFocus::Browse;
            }
            KeyCode::Esc | KeyCode::Enter | KeyCode::Char('q') => {
                app.focus = LaunchFocus::Browse;
            }
            _ => {}
        },
        LaunchFocus::Artifact => match key.code {
            KeyCode::Esc | KeyCode::Enter | KeyCode::Char('q') => {
                app.focus = LaunchFocus::Browse;
            }
            _ => {}
        },
        LaunchFocus::Browse => match key.code {
            KeyCode::Char('q') | KeyCode::Esc => return Ok(true),
            KeyCode::Char('?') => app.focus = LaunchFocus::Help,
            KeyCode::Tab => app.next_tab(),
            KeyCode::BackTab => app.previous_tab(),
            KeyCode::Up | KeyCode::Char('k') => match app.active_tab() {
                AppTab::Monitor => app.move_selection(-1),
                AppTab::Dispatch => app.move_dispatch_selection(-1),
                AppTab::Controls => app.move_deep_selection(-1),
                AppTab::MissionControl => app.move_mission_focus(-1),
            },
            KeyCode::Down | KeyCode::Char('j') => match app.active_tab() {
                AppTab::Monitor => app.move_selection(1),
                AppTab::Dispatch => app.move_dispatch_selection(1),
                AppTab::Controls => app.move_deep_selection(1),
                AppTab::MissionControl => app.move_mission_focus(1),
            },
            KeyCode::Char('l') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                app.clear_search();
            }
            KeyCode::Left | KeyCode::Char('h') => match app.active_tab() {
                AppTab::Monitor => {}
                AppTab::Dispatch => app.adjust_dispatch_selection(-1),
                AppTab::Controls => app.move_selection(-1),
                AppTab::MissionControl => app.move_mission_focus(-1),
            },
            KeyCode::Right | KeyCode::Char('l') => match app.active_tab() {
                AppTab::Monitor => {}
                AppTab::Dispatch => app.adjust_dispatch_selection(1),
                AppTab::Controls => app.move_selection(1),
                AppTab::MissionControl => app.move_mission_focus(1),
            },
            KeyCode::Char('1') => app.set_launch_kind(LaunchKind::Workflow),
            KeyCode::Char('2') => app.set_launch_kind(LaunchKind::Research),
            KeyCode::Char('3') => app.set_launch_kind(LaunchKind::Review),
            KeyCode::Char('4') => app.set_launch_kind(LaunchKind::Marbles),
            KeyCode::Char('a') => {
                app.set_active_tab(AppTab::Dispatch);
                app.dispatch_selected = DispatchFocus::Agent as usize;
                app.cycle_agent();
            }
            KeyCode::Char('v') => {
                app.set_active_tab(AppTab::Dispatch);
                app.dispatch_selected = DispatchFocus::Runtime as usize;
                app.cycle_runtime();
            }
            KeyCode::Char('f') => app.toggle_filter(),
            KeyCode::Char('/') => {
                app.focus = LaunchFocus::Search;
                app.append_status("search: type to filter runs, Enter/Esc closes, Ctrl+L clears");
            }
            KeyCode::Char('x') => {
                app.archive_selected_run()?;
            }
            KeyCode::Char('y') => {
                if let Err(error) = app.copy_selected_run_to_clipboard() {
                    app.show_error("clipboard failed", vec![format!("{error:#}")]);
                }
            }
            KeyCode::Char('r') => app.refresh(),
            KeyCode::Char('e') => {
                app.set_active_tab(AppTab::Dispatch);
                app.dispatch_selected = DispatchFocus::Prompt as usize;
                app.focus = LaunchFocus::EditPrompt;
            }
            KeyCode::Enter => match app.active_tab() {
                AppTab::Monitor => {
                    if app.selected_run().is_some() {
                        app.set_active_tab(AppTab::Controls);
                    }
                }
                AppTab::Dispatch => {
                    if app.dispatch_focus() == DispatchFocus::Prompt {
                        app.focus = LaunchFocus::EditPrompt;
                    } else {
                        launch_selected(app)?;
                    }
                }
                AppTab::Controls => {
                    run_selected_deep_control(app)?;
                }
                AppTab::MissionControl => {
                    // Mission Control is a read-only situational-awareness
                    // surface. Enter on a focused panel jumps the operator
                    // to the surface that owns the action: Controls (for
                    // action-queue items, failures, and stalls) or stays
                    // on the dashboard for stats-only panels.
                    let focus = app.mission_focus;
                    if focus == 6 && !app.mission_control.action_queue.is_empty() {
                        let preselected = app.preselect_controls_from_mission_queue();
                        app.set_active_tab(AppTab::Controls);
                        if preselected {
                            app.append_status(
                                "Mission Control → Controls: preselected most relevant action",
                            );
                        } else {
                            app.append_status(
                                "Mission Control → Controls: pick an action from the deck",
                            );
                        }
                    }
                }
            },
            KeyCode::Char('d') => {
                app.set_active_tab(AppTab::Controls);
                if app.deep_actions().is_empty() {
                    app.append_status("No operator actions are available.");
                } else {
                    app.append_status("Controls ready: ↑/↓ select action, Enter runs it.");
                }
            }
            _ => {}
        },
        LaunchFocus::Help => match key.code {
            KeyCode::Char('?') | KeyCode::Esc | KeyCode::Enter => {
                app.focus = LaunchFocus::Browse;
            }
            _ => {}
        },
    }
    Ok(false)
}

fn launch_selected(app: &mut App) -> anyhow::Result<()> {
    if !app.config.no_verify_gate && app.launch_runtime != launch::LaunchRuntime::Headless {
        let client_kind = match app.selected_agent() {
            "claude" => rmcp_mux::ipc::ClientKind::Claude,
            "codex" => rmcp_mux::ipc::ClientKind::Codex,
            "gemini" => rmcp_mux::ipc::ClientKind::Gemini,
            "junie" => rmcp_mux::ipc::ClientKind::Junie,
            other => rmcp_mux::ipc::ClientKind::Generic {
                name: other.to_string(),
            },
        };
        if let Err(halt) = launch::pre_launch_verify(client_kind) {
            let error = LaunchRunError::ClientDrift(halt);
            app.show_error(
                "launch failed: client drift",
                error.detail_lines("".to_string()),
            );

            return Ok(());
        }
    }
    let command = app.launch_command();
    let summary = command.command_line();
    if app.launch_runtime == launch::LaunchRuntime::Headless {
        match command.spawn_detached() {
            Ok(child) => {
                app.push_launch_history(summary.clone());
                app.append_status(format!("spawned pid {}: {summary}", child.id()));
            }
            Err(error) => app.show_error(
                "launch failed before spawn",
                vec![format!("{summary}"), format!("{error:#}")],
            ),
        }
    } else if let Err(error) = suspend_and_run(&command) {
        app.show_error("launch failed", error.detail_lines(summary));
    } else {
        app.push_launch_history(summary.clone());
        app.append_status(format!("launched: {summary}"));
    }
    app.refresh();
    Ok(())
}

fn run_selected_deep_control(app: &mut App) -> anyhow::Result<()> {
    let Some(action) = app.selected_deep_action() else {
        app.append_status("No deep action is available for the selected run.");
        app.focus = LaunchFocus::Browse;
        return Ok(());
    };
    if matches!(
        action,
        DeepAction::OpenReport(_) | DeepAction::OpenTranscript(_) | DeepAction::OpenRoot(_)
    ) {
        if let Err(error) = app.open_artifact(&action) {
            app.show_error("artifact open failed", vec![format!("{error:#}")]);
        }
        return Ok(());
    }
    if matches!(action, DeepAction::PolarizeIntent { .. }) {
        if let Err(error) = app.open_polarize_intent(&action) {
            app.show_error("polarize prism open failed", vec![format!("{error:#}")]);
        }
        return Ok(());
    }
    let command = deep_control_command(app, &action);
    let summary = command.command_line();
    if let Err(error) = suspend_and_run(&command) {
        app.show_error("action failed", error.detail_lines(summary));
    } else {
        app.push_launch_history(summary.clone());
        app.append_status(format!("ran: {summary}"));
        app.focus = LaunchFocus::Browse;
    }
    app.refresh();
    Ok(())
}

fn deep_control_command(app: &App, action: &DeepAction) -> LaunchCommand {
    match action {
        DeepAction::AttachSession(session) => LaunchCommand {
            program: app.config.command_deck.clone(),
            args: vec!["dashboard".into(), "attach".into(), session.clone().into()],
            env: Default::default(),
        },
        DeepAction::ResumeSession { agent, session } => LaunchCommand {
            program: app.config.command_deck.clone(),
            args: vec![
                "resume".into(),
                agent.clone().into(),
                "--session".into(),
                session.clone().into(),
            ],
            env: Default::default(),
        },
        DeepAction::MuxHealth { service } => LaunchCommand {
            // `rmcp-mux` is expected on PATH (installed via the rmcp-mux
            // installer or `cargo install rmcp-mux`). The default config
            // path is `~/.codex/mcp.json`, which `rmcp-mux` resolves on
            // its own. Operators with a non-default config should set
            // `RMCP_MUX_CONFIG` (read by rmcp-mux directly) rather than
            // teach the operator console a second config surface.
            program: PathBuf::from("rmcp-mux"),
            args: vec!["health".into(), "--service".into(), service.clone().into()],
            env: Default::default(),
        },
        DeepAction::SkillLaunch {
            skill,
            agent,
            payload,
        } => crate::skills_catalog::build_skill_launch_command(
            &app.config.command_deck,
            skill,
            *agent,
            crate::skills_catalog::SkillAgent::from_cli_token(app.selected_agent()),
            payload,
            app.launch_env(),
        ),
        DeepAction::OpenReport(_)
        | DeepAction::OpenTranscript(_)
        | DeepAction::OpenRoot(_)
        | DeepAction::PolarizeIntent { .. }
        | DeepAction::MuxRestart(_)
        | DeepAction::MuxVerifyClient(_)
        | DeepAction::MuxFixClientDrift(_) => {
            unreachable!("artifact actions are handled by the native operator viewer")
        }
    }
}

#[derive(Debug)]
pub enum LaunchRunError {
    Exec {
        message: String,
        stderr: String,
        /// First error observed by the zellij readiness probe before the launch
        /// gave up. Distinguishes "session not visible" from "probe could not
        /// run" (bad flags, socket/config errors, missing binary). When None,
        /// the probe either succeeded or was never attempted.
        probe_error: Option<String>,
        /// Probe diagnostic captured at the deadline-kill branch, where stderr
        /// from the killed child is intentionally not drained.
        probe_error_at_deadline: Option<String>,
    },
    ClientDrift(crate::launch::VerifyHalt),
}

impl LaunchRunError {
    pub fn detail_lines(&self, summary: String) -> Vec<String> {
        match self {
            Self::Exec {
                message,
                stderr,
                probe_error,
                probe_error_at_deadline,
            } => {
                let mut lines = vec![format!("command: {summary}"), format!("error: {message}")];
                if let Some(pe) = probe_error {
                    lines.push(format!("readiness probe: {pe}"));
                }
                if let Some(pe) = probe_error_at_deadline {
                    lines.push(format!("readiness timeout probe: {pe}"));
                }
                if !stderr.trim().is_empty() {
                    lines.push(String::new());
                    lines.push("stderr:".to_string());
                    lines.extend(stderr.lines().map(ToOwned::to_owned));
                }
                lines
            }
            Self::ClientDrift(halt) => {
                let mut lines = vec![
                    "Client drift detected. Dispatch halted.".to_string(),
                    "Non-mux servers found:".to_string(),
                ];
                match halt {
                    crate::launch::VerifyHalt::Drift(servers) => {
                        for entry in servers {
                            lines.push(format!(
                                "  {} ({}:{})",
                                entry.client, entry.path, entry.line
                            ));
                        }
                    }
                    crate::launch::VerifyHalt::Timeout => {
                        lines.push(
                            "  Timeout waiting for verify response from rmcp-mux.".to_string(),
                        );
                    }
                }
                lines.push(String::new());
                lines.push("Press F to auto-fix (spawns rmcp-mux wizard).".to_string());
                lines
            }
        }
    }
}

fn suspend_and_run(command: &LaunchCommand) -> Result<(), LaunchRunError> {
    let mut stdout = io::stdout();
    disable_raw_mode()
        .context("failed to disable raw mode before launch")
        .map_err(launch_error)?;
    execute!(stdout, LeaveAlternateScreen).map_err(launch_error)?;

    let launch_result: Result<Output, LaunchRunError> =
        match command.spawn_interactive_with_stderr() {
            Ok(child) => wait_for_interactive_launch(command, child),
            Err(error) => Err(launch_error(error)),
        };

    let leave_result =
        execute!(stdout, EnterAlternateScreen).context("failed to restore alternate screen");
    let raw_result = enable_raw_mode().context("failed to re-enable raw mode after launch");

    leave_result.map_err(launch_error)?;
    raw_result.map_err(launch_error)?;
    let output = launch_result?;
    if output.status.success() {
        Ok(())
    } else {
        Err(LaunchRunError::Exec {
            message: format!("command exited with {}", output.status),
            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
            probe_error: None,
            probe_error_at_deadline: None,
        })
    }
}

/// How long `wait_for_interactive_launch` will keep polling the zellij
/// readiness probe before giving up. Kept short so the operator does not
/// freeze on a launch that never came up; long enough that real interactive
/// launches on the host can register their named socket.
pub const READINESS_DEADLINE: Duration = Duration::from_secs(2);

pub fn wait_for_interactive_launch(
    command: &LaunchCommand,
    mut child: std::process::Child,
) -> Result<Output, LaunchRunError> {
    if let Some(probe) = command.readiness_probe() {
        let deadline = Instant::now() + READINESS_DEADLINE;
        let mut probe_error: Option<String> = None;
        while Instant::now() < deadline {
            match probe.is_session_visible() {
                Ok(true) => {
                    return child
                        .wait_with_output()
                        .map_err(|err| LaunchRunError::Exec {
                            message: format!("launch process failed: {err}"),
                            stderr: String::new(),
                            probe_error: probe_error.clone(),
                            probe_error_at_deadline: None,
                        });
                }
                Ok(false) => {}
                Err(error) => {
                    // Preserve the FIRST probe error (P2-02). Bad flags,
                    // socket/config errors, or permission failures should
                    // surface in the error overlay instead of being
                    // collapsed into a generic "session not visible".
                    if probe_error.is_none() {
                        probe_error = Some(format!("{error:#}"));
                    }
                }
            }
            match child.try_wait() {
                Ok(Some(_)) => {
                    let output = child
                        .wait_with_output()
                        .map_err(|err| LaunchRunError::Exec {
                            message: format!("launch process failed: {err}"),
                            stderr: String::new(),
                            probe_error: probe_error.clone(),
                            probe_error_at_deadline: None,
                        })?;
                    if output.status.success() {
                        return Err(LaunchRunError::Exec {
                            message: format!(
                                "zellij session '{}' exited before the readiness probe saw it",
                                probe.session_name
                            ),
                            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
                            probe_error,
                            probe_error_at_deadline: None,
                        });
                    }
                    return Ok(output);
                }
                Ok(None) => {}
                Err(err) => {
                    return Err(LaunchRunError::Exec {
                        message: format!("failed to inspect launch child: {err}"),
                        stderr: String::new(),
                        probe_error,
                        probe_error_at_deadline: None,
                    });
                }
            }
            thread::sleep(Duration::from_millis(100));
        }
        // Deadline exceeded with the named session never visible AND the
        // child still running. The README contract says a launch that exits
        // before its session appears is reported as failure; we extend that
        // to "a launch whose session never appears within the readiness
        // window is also a failure", and we do NOT silently fall through to
        // `child.wait_with_output()` (which would either hang on a healthy
        // zellij forever or report success once the operator finally quits
        // it manually — both produce false-success class outcomes).
        //
        // Kill the child so we do not leave a hanging zellij socket pointing
        // at the same session name; subsequent launches with the same
        // `--session` value would fight an orphan otherwise.
        let _ = child.kill();
        // Reap the killed child without `wait_with_output()`: any
        // grandchild process (e.g. a long `sleep` inside a launched shell)
        // that inherited our piped stderr would keep the pipe alive past
        // the SIGKILL, defeating the whole readiness timeout. `wait()`
        // blocks only on the direct child's exit, which the kill
        // guarantees promptly.
        let _ = child.wait();
        let probe_error_at_deadline = probe_error.as_ref().map(|error| {
            format!(
                "killed after {}ms, last probe error: {error}",
                READINESS_DEADLINE.as_millis()
            )
        });
        return Err(LaunchRunError::Exec {
            message: format!(
                "zellij session '{}' did not appear within the {}ms readiness window",
                probe.session_name,
                READINESS_DEADLINE.as_millis()
            ),
            stderr: String::new(),
            probe_error,
            probe_error_at_deadline,
        });
    }
    child
        .wait_with_output()
        .map_err(|err| LaunchRunError::Exec {
            message: format!("launch process failed: {err}"),
            stderr: String::new(),
            probe_error: None,
            probe_error_at_deadline: None,
        })
}

fn launch_error(error: impl Into<anyhow::Error>) -> LaunchRunError {
    let error = error.into();
    LaunchRunError::Exec {
        message: format!("{error:#}"),
        stderr: String::new(),
        probe_error: None,
        probe_error_at_deadline: None,
    }
}

fn start_state_watcher(path: &Path, tx: Sender<()>) -> anyhow::Result<RecommendedWatcher> {
    let mut watcher = RecommendedWatcher::new(
        move |_| {
            let _ = tx.send(());
        },
        NotifyConfig::default(),
    )?;
    watcher.watch(path, RecursiveMode::Recursive)?;
    Ok(watcher)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::launch::LaunchRuntime;
    use crate::state::{ControlPlaneState, RenderedRun, RunKind, RunSnapshot};

    fn sample_run(run_id: &str, agent: &str, session: &str) -> RenderedRun {
        RenderedRun {
            snapshot: RunSnapshot {
                run_id: run_id.to_string(),
                session_id: Some(format!("sess-{run_id}")),
                agent: Some(agent.to_string()),
                skill: Some("workflow".to_string()),
                mode: Some("implement".to_string()),
                state: Some("running".to_string()),
                status: None,
                started_at: Some("2026-04-19T10:00:00Z".to_string()),
                updated_at: Some("2026-04-19T10:01:00Z".to_string()),
                last_heartbeat: Some("2026-04-19T10:01:30Z".to_string()),
                root: Some(format!("/tmp/{run_id}")),
                operator_session: Some(session.to_string()),
                latest_report: Some(format!("/tmp/{run_id}/report.md")),
                latest_transcript: Some(format!("/tmp/{run_id}/transcript.log")),
                last_error: None,
                extra: Default::default(),
            },
            kind: RunKind::Active,
            age_label: "just now".to_string(),
            recent_events: Vec::new(),
        }
    }

    fn sample_app() -> App {
        App {
            mux_subscriber: None,
            config: AppConfig {
                no_verify_gate: false,
                state_root: "/tmp/state".into(),
                command_deck: "/usr/bin/vibecrafted".into(),
                launch_root: "/tmp/repo".into(),
                launch_runtime: LaunchRuntime::Terminal,
                terminal_binary: "zellij".into(),
                tick_rate: Duration::from_millis(250),
            },
            state: ControlPlaneState::empty("/tmp/state"),
            runs: vec![
                sample_run("run-1", "codex", "operator-1"),
                sample_run("run-2", "claude", "operator-2"),
            ],
            selected: 0,
            active_tab: AppTab::Monitor.index(),
            launch_kind: LaunchKind::Workflow,
            launch_agent: 0,
            launch_prompt: "Ship the operator surface.".to_string(),
            launch_runtime: LaunchRuntime::Terminal,
            dispatch_selected: DispatchFocus::Kind as usize,
            focus: LaunchFocus::Browse,
            status_line: String::new(),
            launch_history: Vec::new(),
            deep_selected: 0,
            queue_scope: QueueScope::Live,
            search_query: String::new(),
            error_title: String::new(),
            error_lines: Vec::new(),
            artifact_title: String::new(),
            artifact_lines: Vec::new(),
            mux_summaries: Vec::new(),
            polarize_intents: Vec::new(),
            mission_control: crate::mission_control::MissionControlState::default(),
            mission_focus: 0,
            mission_artifact_root: std::path::PathBuf::from("/tmp/vc-op-mission-test"),
        }
    }

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

    #[test]
    fn handle_key_cycles_tabs_with_tab_and_shift_tab() {
        let mut app = sample_app();

        assert_eq!(app.active_tab(), AppTab::Monitor);
        handle_key(&mut app, key(KeyCode::Tab)).unwrap();
        assert_eq!(app.active_tab(), AppTab::Dispatch);

        handle_key(&mut app, key(KeyCode::BackTab)).unwrap();
        assert_eq!(app.active_tab(), AppTab::Monitor);
    }

    #[test]
    fn handle_key_routes_arrows_inside_the_active_tab() {
        let mut app = sample_app();

        handle_key(&mut app, key(KeyCode::Down)).unwrap();
        assert_eq!(app.selected, 1);

        app.set_active_tab(AppTab::Dispatch);
        handle_key(&mut app, key(KeyCode::Down)).unwrap();
        assert_eq!(app.dispatch_focus(), DispatchFocus::Agent);

        handle_key(&mut app, key(KeyCode::Right)).unwrap();
        assert_eq!(app.selected_agent(), "codex");

        app.set_active_tab(AppTab::Controls);
        handle_key(&mut app, key(KeyCode::Down)).unwrap();
        assert_eq!(app.deep_selected, 1);
    }

    #[test]
    fn handle_key_enters_prompt_edit_from_dispatch_prompt_row() {
        let mut app = sample_app();
        app.set_active_tab(AppTab::Dispatch);
        app.dispatch_selected = DispatchFocus::Prompt as usize;

        handle_key(&mut app, key(KeyCode::Enter)).unwrap();

        assert_eq!(app.focus, LaunchFocus::EditPrompt);
    }

    #[test]
    fn handle_key_shortcuts_jump_to_dispatch_controls_and_prime_selection() {
        let mut app = sample_app();

        handle_key(&mut app, key(KeyCode::Char('a'))).unwrap();
        assert_eq!(app.active_tab(), AppTab::Dispatch);
        assert_eq!(app.dispatch_focus(), DispatchFocus::Agent);
        assert_eq!(app.selected_agent(), "codex");

        handle_key(&mut app, key(KeyCode::Char('v'))).unwrap();
        assert_eq!(app.active_tab(), AppTab::Dispatch);
        assert_eq!(app.dispatch_focus(), DispatchFocus::Runtime);
        assert_eq!(app.launch_runtime, LaunchRuntime::Visible);

        app.set_active_tab(AppTab::Monitor);
        handle_key(&mut app, key(KeyCode::Char('d'))).unwrap();
        assert_eq!(app.active_tab(), AppTab::Controls);
        assert!(app.status_line.contains("Controls ready"));
    }

    #[test]
    fn handle_key_controls_can_move_across_run_list_and_prompt_edit_saves_multiline_prompt() {
        let mut app = sample_app();
        app.set_active_tab(AppTab::Controls);

        handle_key(&mut app, key(KeyCode::Right)).unwrap();
        assert_eq!(app.selected, 1);

        handle_key(&mut app, key(KeyCode::Left)).unwrap();
        assert_eq!(app.selected, 0);

        app.set_active_tab(AppTab::Dispatch);
        app.focus = LaunchFocus::EditPrompt;
        handle_key(&mut app, key(KeyCode::Enter)).unwrap();
        handle_key(&mut app, key(KeyCode::Char('n'))).unwrap();
        handle_key(&mut app, key(KeyCode::Esc)).unwrap();
        assert!(app.launch_prompt.contains("\nn"));
        assert_eq!(app.focus, LaunchFocus::Browse);
        assert!(app.status_line.contains("prompt updated"));
    }

    #[test]
    fn set_active_tab_resets_focus_to_browse() {
        let mut app = sample_app();
        app.focus = LaunchFocus::EditPrompt;

        app.set_active_tab(AppTab::Controls);

        assert_eq!(app.active_tab(), AppTab::Controls);
        assert_eq!(app.focus, LaunchFocus::Browse);
    }

    #[test]
    fn launch_run_error_detail_lines_render_probe_error_when_present() {
        let error = LaunchRunError::Exec {
            message: "command exited with status: 1".to_string(),
            stderr: "boom\nstack\n".to_string(),
            probe_error: Some(
                "failed to run zellij readiness probe: No such file or directory".to_string(),
            ),
            probe_error_at_deadline: None,
        };
        let lines = error.detail_lines("zellij --session foo".to_string());
        assert_eq!(lines[0], "command: zellij --session foo");
        assert_eq!(lines[1], "error: command exited with status: 1");
        assert!(
            lines.iter().any(|line| line.contains("readiness probe:")
                && line.contains("No such file or directory")),
            "probe_error must be surfaced in the operator error overlay: lines={lines:?}"
        );
        assert!(lines.iter().any(|line| line == "stderr:"));
        assert!(lines.iter().any(|line| line == "boom"));
    }

    #[test]
    fn launch_run_error_detail_lines_skip_probe_section_when_none() {
        let error = LaunchRunError::Exec {
            message: "command exited with status: 2".to_string(),
            stderr: String::new(),
            probe_error: None,
            probe_error_at_deadline: None,
        };
        let lines = error.detail_lines("zellij --session foo".to_string());
        assert!(
            !lines.iter().any(|line| line.contains("readiness probe:")),
            "probe_error=None must not render an empty probe section: lines={lines:?}"
        );
    }
}