capo-cli 0.1.0

Capo — a Rust-native coding agent CLI.
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
mod cli;

use anyhow::{Context, Result};
use capo_agent::{AppBuilder, UiEvent};
use clap::Parser;
use cli::{Cli, Mode};
use futures::StreamExt;
use tracing_subscriber::EnvFilter;

fn main() -> Result<()> {
    color_eyre::install().ok();

    let rt = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .context("failed to start tokio runtime")?;
    rt.block_on(async_main())
}

fn resolve_permissions_path(
    agent_dir: &std::path::Path,
    cwd: &std::path::Path,
) -> std::path::PathBuf {
    let canonical = agent_dir.join("permissions.toml");
    if canonical.exists() {
        return canonical;
    }

    // Legacy locations from earlier milestones.
    let home_config = std::env::var("HOME")
        .ok()
        .map(|h| std::path::PathBuf::from(h).join(".config/capo/permissions.toml"));
    let project_legacy = cwd.join(".capo").join("permissions.toml");

    for legacy in [home_config.as_ref(), Some(&project_legacy)]
        .into_iter()
        .flatten()
    {
        if legacy.exists() {
            tracing::warn!(
                "permissions.toml found at {}; please mv to {}",
                legacy.display(),
                canonical.display()
            );
            return legacy.clone();
        }
    }

    // No file anywhere — return canonical; AppBuilder treats absent as "default empty policy".
    canonical
}

async fn async_main() -> Result<()> {
    let cli = Cli::parse();
    init_tracing(cli.verbosity);

    let cwd = std::env::current_dir().context("cannot read cwd")?;
    let agent_dir = capo_agent::agent_dir();

    let overrides = capo_agent::CliOverrides {
        model: cli.model.clone(),
    };
    let mut settings = capo_agent::Settings::load(&overrides).context("failed to load settings")?;
    if let Some(provider) = &cli.provider {
        settings.model.provider = provider.clone();
    }
    let auth = capo_agent::Auth::load(&agent_dir).context("failed to load auth.json")?;

    let skills = if cli.no_skills {
        Vec::new()
    } else {
        let result = capo_agent::skills::load_all(&cwd, &capo_agent::paths::agent_dir());
        for d in &result.diagnostics {
            tracing::warn!(target: "skills", path = %d.file_path.display(), "{}", d.message);
        }
        eprintln!("  skills: {} loaded", result.skills.len());
        result.skills
    };

    // Permissions config: try new location first, warn on legacy paths.
    let permissions_path = resolve_permissions_path(&agent_dir, &cwd);

    // M3 Phase A: per-cwd session bucket.
    let session_paths = capo_agent::SessionPaths::for_cwd(agent_dir.clone(), &cwd);

    // `--resume / -r`: print-and-exit list. Phase A scope-locks out a picker UI;
    // interactive picker is deferred to M4 (per the briefing §6 decision).
    if cli.resume {
        return run_resume_list(&session_paths).await;
    }

    let resume_session_id: Option<capo_agent::SessionId> = if let Some(s) = &cli.session {
        Some(
            capo_agent::SessionLookup::resolve(&session_paths, s)
                .await
                .context("--session resolution failed")?,
        )
    } else if cli.continue_session {
        Some(
            capo_agent::SessionLookup::most_recent(&session_paths)
                .await
                .context("--continue: no prior session in this directory")?,
        )
    } else {
        None
    };

    eprintln!("⚠ capo M3 preview: TUI session persistence + AGENTS.md walk-up.");
    eprintln!(
        "  provider: {} | model: {}",
        settings.model.provider, settings.model.name
    );
    if let Some(id) = &resume_session_id {
        eprintln!("  resuming session: {}", id.as_str());
    }

    let (mcp_cfg, mcp_diags) =
        match capo_agent::mcp::load_config(&cwd, &capo_agent::paths::agent_dir(), &|k| {
            std::env::var(k).ok()
        }) {
            Ok(out) => out,
            Err(err) => {
                eprintln!("  mcp: config load failed: {err}");
                (capo_agent::mcp::McpConfig::default(), Vec::new())
            }
        };
    for d in &mcp_diags {
        eprintln!("  mcp: {d}");
    }

    let started = capo_agent::mcp::connect_all(&mcp_cfg, &capo_agent::paths::agent_dir()).await;
    eprintln!("  mcp: {} server(s) connected", started.len());

    let mcp_tools: Vec<std::sync::Arc<dyn motosan_agent_tool::Tool>> = {
        let mut acc = Vec::new();
        for s in &started {
            match motosan_agent_loop::mcp::McpToolAdapter::from_server(std::sync::Arc::clone(
                &s.server,
            ))
            .await
            {
                Ok(mut tools) => acc.append(&mut tools),
                Err(e) => {
                    tracing::error!(target: "mcp", server = %s.name, "list_tools failed: {e}")
                }
            }
        }
        acc
    };

    let mcp_pairs = capo_agent::mcp::into_pairs(started);

    // Best-effort: motosan FileSessionStore creates the dir on first write,
    // but pre-creating avoids a confusing error when listing an empty bucket.
    session_paths.ensure_bucket().ok();
    let store: std::sync::Arc<dyn motosan_agent_loop::SessionStore> = std::sync::Arc::new(
        motosan_agent_loop::FileSessionStore::new(session_paths.bucket_dir.clone()),
    );

    match cli.mode() {
        Mode::Print(prompt) => {
            let mut builder = AppBuilder::new()
                .with_settings(settings)
                .with_auth(auth)
                .with_cwd(&cwd)
                .with_builtin_tools()
                .with_permissions_config(permissions_path)
                .with_session_store(store)
                .with_autocompact()
                .with_skills(skills.clone());
            if cli.no_context_files {
                builder = builder.disable_context_discovery();
            }
            builder = builder
                .with_extra_tools(mcp_tools.clone())
                .with_mcp_servers(mcp_pairs.clone());
            let app = match builder.build_with_session(resume_session_id).await {
                Ok(app) => app,
                Err(err) => {
                    disconnect_mcp_pairs(&mcp_pairs).await;
                    return Err(err).context("failed to build App");
                }
            };
            let result = tokio::select! {
                res = run_print_mode(&app, prompt) => res,
                _ = tokio::signal::ctrl_c() => {
                    eprintln!("\n  shutting down (ctrl-C)…");
                    Err(anyhow::anyhow!("interrupted"))
                }
            };
            app.disconnect_mcp().await;
            result
        }
        Mode::InteractiveStub => {
            run_interactive(
                settings,
                auth,
                cwd,
                permissions_path,
                store,
                resume_session_id,
                skills,
                mcp_tools,
                mcp_pairs,
                &cli,
            )
            .await
        }
    }
}

/// `--resume` Phase-A UX: list the sessions in this cwd's bucket, print
/// short ids + timestamps + first-message preview, and exit. Interactive
/// picker lands in M4 alongside skills.
async fn run_resume_list(paths: &capo_agent::SessionPaths) -> Result<()> {
    use motosan_agent_loop::{FileSessionStore, SessionStore};

    if !paths.bucket_dir.exists() {
        println!(
            "No sessions yet for this directory (looked in {}).",
            paths.bucket_dir.display()
        );
        return Ok(());
    }

    let store = FileSessionStore::new(paths.bucket_dir.clone());
    let metas = store
        .list_meta()
        .await
        .context("failed to list session metadata")?;
    if metas.is_empty() {
        println!("No sessions yet in {}.", paths.bucket_dir.display());
        return Ok(());
    }

    println!("Sessions in {}:", paths.bucket_dir.display());
    println!("  {:<12} {:<20} NAME", "ID-PREFIX", "UPDATED-AT-MS");
    for meta in metas {
        let prefix = meta.session_id.chars().take(10).collect::<String>();
        let name = meta.name.as_deref().unwrap_or("(unnamed)");
        let updated = meta.updated_at_ms;
        println!("  {prefix:<12} {updated:<20} {name}");
    }
    println!("\nResume with: capo --session <id-prefix>");
    println!("(Interactive picker UI lands in M4.)");
    Ok(())
}

#[allow(clippy::too_many_arguments)]
async fn run_interactive(
    settings: capo_agent::Settings,
    auth: capo_agent::Auth,
    cwd: std::path::PathBuf,
    permissions_path: std::path::PathBuf,
    store: std::sync::Arc<dyn motosan_agent_loop::SessionStore>,
    resume_session_id: Option<capo_agent::SessionId>,
    skills: Vec<capo_agent::Skill>,
    mcp_tools: Vec<std::sync::Arc<dyn motosan_agent_tool::Tool>>,
    mcp_pairs: Vec<(
        String,
        std::sync::Arc<dyn motosan_agent_loop::mcp::McpServer>,
    )>,
    cli: &Cli,
) -> Result<()> {
    use tokio::sync::mpsc;

    let (ui_tx, ui_rx) = mpsc::channel::<capo_agent::UiEvent>(256);
    let (cmd_tx, cmd_rx) = mpsc::channel::<capo_agent::Command>(64);

    let mut builder = AppBuilder::new()
        .with_settings(settings.clone())
        .with_auth(auth)
        .with_cwd(&cwd)
        .with_builtin_tools()
        .with_permissions_config(permissions_path)
        .with_ui_channel(ui_tx.clone())
        .with_session_store(store)
        .with_autocompact()
        .with_skills(skills.clone());
    if cli.no_context_files {
        builder = builder.disable_context_discovery();
    }
    builder = builder
        .with_extra_tools(mcp_tools.clone())
        .with_mcp_servers(mcp_pairs.clone());
    let app = match builder.build_with_session(resume_session_id).await {
        Ok(app) => app,
        Err(err) => {
            disconnect_mcp_pairs(&mcp_pairs).await;
            return Err(err).context("failed to build App");
        }
    };

    // Seed the TUI transcript with persisted history when resuming. The
    // agent already has full context (loaded by `AgentSession::resume`
    // and observed inside `send_user_message` via `session.history()`),
    // but the TUI's `state.messages` starts empty — so users on
    // `--continue` / `--session` would see a blank screen and have to
    // ask "what did I just say" to verify context loaded. Replaying
    // User / Assistant text entries here closes that UX gap.
    //
    // System messages are skipped (prompt, not transcript). Tool-call /
    // tool-result replay is deferred — would need bridging
    // `motosan::Message.content_blocks` → capo-tui's
    // `MessageBlock::ToolCall { id, name, args }` shape.
    let history = match app.session_history().await {
        Ok(history) => history,
        Err(err) => {
            app.disconnect_mcp().await;
            return Err(err).context("failed to load session history for transcript replay");
        }
    };

    let mut state = capo_tui::state::AppState::default();
    state.footer.cwd = cwd.display().to_string();
    state.footer.model = settings.model.name.clone();
    state.footer.skills_loaded = skills.len();
    for msg in &history {
        let text = msg.text();
        if text.is_empty() {
            continue;
        }
        match msg.role() {
            motosan_agent_loop::Role::User => state
                .messages
                .push(capo_tui::state::MessageBlock::User(text)),
            motosan_agent_loop::Role::Assistant => state
                .messages
                .push(capo_tui::state::MessageBlock::Assistant(text)),
            _ => {}
        }
    }

    let app = std::sync::Arc::new(app);
    tokio::spawn(forward_commands(
        std::sync::Arc::clone(&app),
        ui_tx.clone(),
        cmd_rx,
    ));

    let ui_stream = Box::pin(futures::stream::unfold(ui_rx, |mut rx| async move {
        rx.recv().await.map(|event| (event, rx))
    }));
    let result = tokio::select! {
        res = capo_tui::run_tui(state, ui_stream, cmd_tx) => {
            res.map(|_| ()).map_err(|e| anyhow::anyhow!("TUI error: {e}"))
        }
        _ = tokio::signal::ctrl_c() => {
            eprintln!("\n  shutting down (ctrl-C)…");
            Err(anyhow::anyhow!("interrupted"))
        }
    };
    app.disconnect_mcp().await;
    result
}

async fn disconnect_mcp_pairs(
    servers: &[(
        String,
        std::sync::Arc<dyn motosan_agent_loop::mcp::McpServer>,
    )],
) {
    for (name, server) in servers {
        let _ = tokio::time::timeout(std::time::Duration::from_secs(2), server.disconnect()).await;
        tracing::debug!(target: "mcp", server = %name, "disconnected after build failure");
    }
}

async fn forward_commands(
    app: std::sync::Arc<capo_agent::App>,
    ui_tx: tokio::sync::mpsc::Sender<capo_agent::UiEvent>,
    mut cmd_rx: tokio::sync::mpsc::Receiver<capo_agent::Command>,
) {
    use capo_agent::Command;

    let mut active_turn: Option<tokio::task::JoinHandle<()>> = None;
    while let Some(cmd) = cmd_rx.recv().await {
        if active_turn
            .as_ref()
            .map(|handle| handle.is_finished())
            .unwrap_or(false)
        {
            active_turn = None;
        }

        match cmd {
            Command::SendUserMessage(text) => {
                if active_turn.is_some() {
                    tracing::debug!("turn already running; ignoring extra SendUserMessage");
                    continue;
                }

                let app = std::sync::Arc::clone(&app);
                let ui_tx = ui_tx.clone();
                active_turn = Some(tokio::spawn(async move {
                    let mut stream = Box::pin(app.send_user_message(text));
                    while let Some(ev) = stream.next().await {
                        if ui_tx.send(ev).await.is_err() {
                            break;
                        }
                    }
                }));
            }
            Command::CancelAgent => app.cancel(),
            Command::Quit => {
                if let Some(handle) = active_turn.take() {
                    handle.abort();
                }
                return;
            }
            Command::ResolvePermission(resolution) => {
                use capo_agent::PermissionChoice;

                if resolution.choice == PermissionChoice::AllowSession {
                    let key = capo_agent::permissions::SessionCache::key(
                        &resolution.tool,
                        &resolution.args,
                    );
                    app.permissions_cache()
                        .insert(key, capo_agent::Decision::Allowed);
                }
                // AllowOnce and Deny are already communicated via the
                // oneshot channel inside the modal; no cache write needed.
            }
        }
    }
}

async fn run_print_mode(app: &capo_agent::App, prompt: String) -> Result<()> {
    let events: Vec<UiEvent> = app.send_user_message(prompt).collect().await;
    let rendered = render_print_mode_events(&events)?;
    print!("{}", rendered.stdout);
    eprint!("{}", rendered.stderr);
    Ok(())
}

#[derive(Debug, Default, PartialEq, Eq)]
struct RenderedPrintMode {
    stdout: String,
    stderr: String,
}

fn render_print_mode_events(events: &[UiEvent]) -> Result<RenderedPrintMode> {
    let mut rendered = RenderedPrintMode::default();
    let mut saw_text_delta = false;

    for event in events {
        match event {
            UiEvent::AgentTurnStarted => {}
            UiEvent::AgentThinking => rendered.stderr.push_str("[thinking]\n"),
            UiEvent::AgentTextDelta(chunk) => {
                saw_text_delta = true;
                rendered.stdout.push_str(chunk);
            }
            UiEvent::AgentMessageComplete(text) => {
                if !saw_text_delta && !text.is_empty() {
                    rendered.stdout.push_str(text);
                    rendered.stdout.push('\n');
                }
            }
            UiEvent::ToolCallStarted { name, args, .. } => {
                rendered
                    .stderr
                    .push_str(&format!("[tool:start] {name} {args}\n"));
            }
            // Progress chunks are TUI-only for M2; print mode intentionally
            // ignores them to keep stdout/stderr stable and non-stream-fragmented.
            UiEvent::ToolCallProgress { .. } => {}
            UiEvent::ToolCallCompleted { result, .. } => {
                if result.is_error {
                    rendered
                        .stderr
                        .push_str(&format!("[tool:error] {}\n", result.text));
                } else {
                    rendered.stderr.push_str("[tool:done]\n");
                }
            }
            UiEvent::AgentTurnComplete => {
                if saw_text_delta {
                    rendered.stdout.push('\n');
                }
            }
            UiEvent::PermissionRequested { .. } => {
                // Phase A protocol surface only; permission UX lands in Phase E/F.
            }
            UiEvent::Error(msg) => {
                rendered.stderr.push_str(&format!("[error] {msg}\n"));
                return Err(anyhow::anyhow!("agent error: {msg}"));
            }
        }
    }

    Ok(rendered)
}

fn init_tracing(verbosity: u8) {
    let default_level = match verbosity {
        0 => "info",
        1 => "debug",
        _ => "trace",
    };
    let filter =
        EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(default_level));
    tracing_subscriber::fmt()
        .with_env_filter(filter)
        .with_writer(std::io::stderr)
        .with_target(false)
        .compact()
        .init();
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;
    use std::time::Duration;

    use async_trait::async_trait;
    use capo_agent::{
        AppBuilder, Command, Config, PermissionChoice, PermissionResolution, UiToolResult,
    };
    use motosan_agent_loop::{ChatOutput, LlmClient, Message};
    use motosan_agent_tool::ToolDef;

    use super::*;

    #[test]
    fn print_mode_does_not_duplicate_streamed_final_text() {
        let events = vec![
            UiEvent::AgentTurnStarted,
            UiEvent::AgentThinking,
            UiEvent::AgentTextDelta("hello".into()),
            UiEvent::AgentTextDelta(" world".into()),
            UiEvent::AgentMessageComplete("hello world".into()),
            UiEvent::AgentTurnComplete,
        ];

        let rendered = render_print_mode_events(&events)
            .unwrap_or_else(|e| panic!("unexpected render error: {e}"));

        assert_eq!(rendered.stdout, "hello world\n");
        assert_eq!(rendered.stderr, "[thinking]\n");
    }

    #[test]
    fn print_mode_prints_non_streamed_final_text_once() {
        let events = vec![
            UiEvent::AgentTurnStarted,
            UiEvent::AgentMessageComplete("hello world".into()),
            UiEvent::AgentTurnComplete,
        ];

        let rendered = render_print_mode_events(&events)
            .unwrap_or_else(|e| panic!("unexpected render error: {e}"));

        assert_eq!(rendered.stdout, "hello world\n");
        assert!(rendered.stderr.is_empty());
    }

    #[test]
    fn print_mode_renders_tool_events_to_stderr() {
        let events = vec![
            UiEvent::ToolCallStarted {
                id: "tool_1".into(),
                name: "bash".into(),
                args: serde_json::json!({"command": "echo hi"}),
            },
            UiEvent::ToolCallCompleted {
                id: "tool_1".into(),
                result: UiToolResult {
                    is_error: false,
                    text: "ok".into(),
                },
            },
        ];

        let rendered = render_print_mode_events(&events)
            .unwrap_or_else(|e| panic!("unexpected render error: {e}"));

        assert!(rendered.stderr.contains("[tool:start] bash"));
        assert!(rendered.stderr.contains("[tool:done]"));
    }

    struct PendingLlm;

    #[async_trait]
    impl LlmClient for PendingLlm {
        async fn chat(
            &self,
            _messages: &[Message],
            _tools: &[ToolDef],
        ) -> motosan_agent_loop::Result<ChatOutput> {
            futures::future::pending::<motosan_agent_loop::Result<ChatOutput>>().await
        }
    }

    #[tokio::test]
    async fn command_forwarder_handles_resolution_while_turn_is_running() {
        let dir = tempfile::tempdir().unwrap_or_else(|e| panic!("tempdir: {e}"));
        let mut cfg = Config::default();
        cfg.anthropic.api_key = Some("sk-unused".into());
        let app = match AppBuilder::new()
            .with_config(cfg)
            .with_cwd(dir.path())
            .with_llm(Arc::new(PendingLlm))
            .build()
            .await
        {
            Ok(app) => Arc::new(app),
            Err(err) => panic!("build: {err}"),
        };

        let (ui_tx, _ui_rx) = tokio::sync::mpsc::channel::<UiEvent>(16);
        let (cmd_tx, cmd_rx) = tokio::sync::mpsc::channel::<Command>(16);
        let forwarder = tokio::spawn(forward_commands(Arc::clone(&app), ui_tx, cmd_rx));

        if cmd_tx
            .send(Command::SendUserMessage("hi".into()))
            .await
            .is_err()
        {
            panic!("command channel closed");
        }
        tokio::task::yield_now().await;

        let args = serde_json::json!({"command": "echo hi"});
        let key = capo_agent::permissions::SessionCache::key("bash", &args);
        if cmd_tx
            .send(Command::ResolvePermission(PermissionResolution {
                tool: "bash".into(),
                args,
                choice: PermissionChoice::AllowSession,
            }))
            .await
            .is_err()
        {
            panic!("command channel closed");
        }

        let observed = tokio::time::timeout(Duration::from_millis(200), async {
            loop {
                if app.permissions_cache().get(&key).is_some() {
                    break true;
                }
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .unwrap_or(false);

        if cmd_tx.send(Command::Quit).await.is_err() {
            panic!("command channel closed");
        }
        match tokio::time::timeout(Duration::from_millis(200), forwarder).await {
            Ok(Ok(())) => {}
            Ok(Err(err)) => panic!("forwarder join failed: {err}"),
            Err(_) => panic!("forwarder did not exit"),
        }
        assert!(observed, "session cache was not updated while turn ran");
    }

    #[tokio::test]
    async fn command_forwarder_ignores_second_send_while_turn_is_running() {
        let dir = tempfile::tempdir().unwrap_or_else(|e| panic!("tempdir: {e}"));
        let mut cfg = Config::default();
        cfg.anthropic.api_key = Some("sk-unused".into());
        let app = match AppBuilder::new()
            .with_config(cfg)
            .with_cwd(dir.path())
            .with_llm(Arc::new(PendingLlm))
            .build()
            .await
        {
            Ok(app) => Arc::new(app),
            Err(err) => panic!("build: {err}"),
        };

        let (ui_tx, mut ui_rx) = tokio::sync::mpsc::channel::<UiEvent>(16);
        let (cmd_tx, cmd_rx) = tokio::sync::mpsc::channel::<Command>(16);
        let forwarder = tokio::spawn(forward_commands(app, ui_tx, cmd_rx));

        if cmd_tx
            .send(Command::SendUserMessage("first".into()))
            .await
            .is_err()
        {
            panic!("command channel closed");
        }
        match tokio::time::timeout(Duration::from_millis(200), ui_rx.recv()).await {
            Ok(Some(UiEvent::AgentTurnStarted)) => {}
            Ok(Some(other)) => panic!("expected turn start, got {other:?}"),
            Ok(None) => panic!("ui channel closed"),
            Err(_) => panic!("timed out waiting for first turn"),
        }

        if cmd_tx
            .send(Command::SendUserMessage("second".into()))
            .await
            .is_err()
        {
            panic!("command channel closed");
        }

        let mut saw_concurrency_error = false;
        let mut extra_turn_starts = 0;
        while let Ok(Some(event)) =
            tokio::time::timeout(Duration::from_millis(25), ui_rx.recv()).await
        {
            match event {
                UiEvent::Error(message) if message.contains("another turn") => {
                    saw_concurrency_error = true;
                }
                UiEvent::AgentTurnStarted => extra_turn_starts += 1,
                _ => {}
            }
        }

        if cmd_tx.send(Command::Quit).await.is_err() {
            panic!("command channel closed");
        }
        match tokio::time::timeout(Duration::from_millis(200), forwarder).await {
            Ok(Ok(())) => {}
            Ok(Err(err)) => panic!("forwarder join failed: {err}"),
            Err(_) => panic!("forwarder did not exit"),
        }
        assert!(!saw_concurrency_error, "second send leaked to App");
        assert_eq!(extra_turn_starts, 0, "second send started another turn");
    }
}