xcodeai 2.1.0

Autonomous AI coding agent — zero human intervention, sbox sandboxed, OpenAI-compatible
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
// src/repl/mod.rs
// REPL loop and related state for xcodeai interactive mode.
// Extracted from main.rs for clarity and modularity.
//
// This module contains:
// - REPL loop (repl_command)
// - REPL state enums and structs
// - Provider presets for /connect
// - Session picker and connect menu
// - crossterm-based readline with live slash-command suggestions (input.rs)
//
// For Rust learners: This file demonstrates how to organize a REPL loop and related state in a separate module. It also shows how to use enums and structs to manage interactive CLI state.

use crate::context::AgentContext;
use crate::llm::openai::COPILOT_API_BASE;
use crate::session::{Session, SessionStore};
use crate::ui::{err, info, ok, print_banner, print_separator, print_status_bar, warn};
use anyhow::Result;
use console::style;
// rustyline is no longer used — all input goes through src/repl/input.rs.
use std::path::PathBuf;

pub mod commands;
pub mod input;
use commands::{handle_command, CommandAction, ReplState};

// SlashHelper and rustyline editor removed — superseded by crossterm readline.
#[derive(Clone, Copy, PartialEq)]
pub enum ReplMode {
    Act,
    Plan,
}

/// Built-in provider presets shown in /connect menu
pub struct ProviderPreset {
    pub label: &'static str,
    pub api_base: &'static str,
    pub needs_key: bool,
}

pub const PROVIDER_PRESETS: &[ProviderPreset] = &[
    ProviderPreset {
        label: "GitHub Copilot       (subscription, no key needed)",
        api_base: "copilot",
        needs_key: false,
    },
    ProviderPreset {
        label: "OpenAI               https://api.openai.com/v1",
        api_base: "https://api.openai.com/v1",
        needs_key: true,
    },
    ProviderPreset {
        label: "Anthropic            (claude-3-5-sonnet-20241022)",
        api_base: "anthropic",
        needs_key: true,
    },
    ProviderPreset {
        label: "Google Gemini        (gemini-2.0-flash)",
        api_base: "gemini",
        needs_key: true,
    },
    ProviderPreset {
        label: "DeepSeek             https://api.deepseek.com/v1",
        api_base: "https://api.deepseek.com/v1",
        needs_key: true,
    },
    ProviderPreset {
        label: "Qwen (Alibaba Cloud) https://dashscope.aliyuncs.com/compatible-mode/v1",
        api_base: "https://dashscope.aliyuncs.com/compatible-mode/v1",
        needs_key: true,
    },
    ProviderPreset {
        label: "GLM (Zhipu AI)       https://open.bigmodel.cn/api/paas/v4",
        api_base: "https://open.bigmodel.cn/api/paas/v4",
        needs_key: true,
    },
    ProviderPreset {
        label: "Ollama (local)       http://localhost:11434/v1",
        api_base: "http://localhost:11434/v1",
        needs_key: false,
    },
    ProviderPreset {
        label: "Custom URL…",
        api_base: "",
        needs_key: true,
    },
];

/// Show a /command picker. Returns the chosen command string (e.g. "/session"), or None if the user pressed Esc / Ctrl-C.
pub fn show_command_menu() -> Option<String> {
    commands::show_command_menu()
}

pub enum SessionPickResult {
    /// User chose to start a brand-new session
    NewSession,
    /// User selected an existing session to resume
    Resume(Session),
    /// User cancelled (Esc)
    Cancelled,
}

/// Show an interactive session picker.
pub fn session_picker(store: &SessionStore) -> SessionPickResult {
    // Implementation copied from main.rs
    use dialoguer::{theme::ColorfulTheme, Select};
    let sessions = match store.list_sessions(30) {
        Ok(s) => s,
        Err(e) => {
            err(&format!("Failed to load sessions: {:#}", e));
            return SessionPickResult::Cancelled;
        }
    };
    let mut labels: Vec<String> = vec![format!("  {} New session", style("+").green().bold())];
    for s in &sessions {
        let date = s.updated_at.format("%Y-%m-%d %H:%M").to_string();
        let title = s.title.as_deref().unwrap_or("(untitled)");
        let short_title = if title.chars().count() > 50 {
            let end = title.char_indices().nth(49).map(|(i, _)| i).unwrap_or(title.len());
            format!("{}", &title[..end])
        } else {
            title.to_string()
        };
        labels.push(format!("  {}  {}", style(date).dim(), short_title));
    }
    println!();
    let selection = Select::with_theme(&ColorfulTheme::default())
        .with_prompt("Session")
        .items(&labels)
        .default(0)
        .interact_opt();
    println!();
    match selection {
        Ok(Some(0)) => SessionPickResult::NewSession,
        Ok(Some(i)) => SessionPickResult::Resume(sessions[i - 1].clone()),
        _ => SessionPickResult::Cancelled,
    }
}

/// Interactive /connect menu — lets user pick a provider from a numbered list.
/// Prompts for URL and API key using plain stdin (no rustyline needed).
pub fn connect_menu() -> Option<(String, String)> {
    use dialoguer::{theme::ColorfulTheme, Select};
    use std::io::{self, BufRead, Write};
    println!();
    info("Select a provider:");
    println!();
    let labels: Vec<&str> = PROVIDER_PRESETS.iter().map(|p| p.label).collect();
    let selection = Select::with_theme(&ColorfulTheme::default())
        .items(&labels)
        .default(0)
        .interact_opt();
    let idx = match selection {
        Ok(Some(i)) => i,
        _ => {
            info("Cancelled.");
            return None;
        }
    };
    let preset = &PROVIDER_PRESETS[idx];
    println!();
    // Helper: read a line from stdin with a visible prompt.
    let read_line = |prompt_str: &str| -> Option<String> {
        print!("{} ", console::style(prompt_str).cyan());
        io::stdout().flush().ok()?;
        let stdin = io::stdin();
        let mut line = String::new();
        stdin.lock().read_line(&mut line).ok()?;
        Some(line.trim().to_string())
    };
    let api_base = if preset.api_base.is_empty() {
        match read_line("  API base URL:") {
            Some(url) if !url.is_empty() => url,
            Some(_) => { info("Cancelled."); return None; }
            None => return None,
        }
    } else {
        preset.api_base.to_string()
    };
    if api_base == COPILOT_API_BASE {
        return Some(("copilot_do_login".to_string(), String::new()));
    }
    let api_key = if preset.needs_key {
        match read_line("  API key:") {
            Some(k) => {
                if k.is_empty() {
                    warn("No key entered — provider set, but API calls will fail without a key.");
                }
                k
            }
            None => return None,
        }
    } else {
        String::new()
    };
    Some((api_base, api_key))
}

/// Main REPL loop for interactive mode.
#[allow(clippy::too_many_arguments)]
pub async fn repl_command(
    project: Option<PathBuf>,
    no_sandbox: bool,
    model: Option<String>,
    provider_url: Option<String>,
    api_key: Option<String>,
    confirm: bool,
    no_agents_md: bool,
    // When true, enables compact mode for this REPL session.
    compact: bool,
    // When true, disable markdown rendering of agent output in the terminal.
    no_markdown: bool,
) -> Result<()> {
    // ─── REPL loop implementation ───────────────────────────────────────────────
    use crate::agent::coder::run_plan_turn;
    use crate::agent::director::Director;
    use crate::agent::Agent;
    use crate::auth;
    use crate::context::update_session_title;
    use crate::llm;
    use crate::session::auto_title;
    use crate::repl::input::{InputHistory, ReadResult};
    use std::sync::mpsc;
    use std::time::Duration;

    let io: std::sync::Arc<dyn crate::io::AgentIO> = if confirm {
        // --confirm flag: prompt before destructive operations.
        std::sync::Arc::new(crate::io::terminal::TerminalIO { no_markdown })
    } else {
        // Default: fully autonomous — auto-approve all destructive calls.
        std::sync::Arc::new(crate::io::AutoApproveIO)
    };
    let mut ctx = AgentContext::new(
        project,
        no_sandbox,
        model,
        provider_url,
        api_key,
        compact,
        io,
    )
    .await?;
    let mut sess = ctx.store.create_session(Some("REPL session"))?;

    // Auth status string with colour
    let auth_status: String = if ctx.llm.is_copilot() {
        match auth::CopilotOAuthToken::load() {
            Ok(Some(_)) => style("GitHub Copilot  ✓ authenticated").green().to_string(),
            _ => style("GitHub Copilot  ✗ not authenticated — run /login")
                .yellow()
                .to_string(),
        }
    } else if ctx.config.provider.api_key.is_empty() {
        style("no API key — run /connect to configure")
            .yellow()
            .to_string()
    } else {
        format!(
            "{} {}",
            style("provider:").dim(),
            style(&ctx.config.provider.api_base).cyan()
        )
    };

    print_banner(
        env!("CARGO_PKG_VERSION"),
        &ctx.config.model,
        &ctx.project_dir.display().to_string(),
        &auth_status,
    );

    // ── Crossterm-based line editor with live slash-command suggestions ────
    // `InputHistory` owns the in-process history list.  We load it from a
    // text file at start and save it back on clean exit.
    let mut history = InputHistory::new();
    let history_path = dirs::data_local_dir()
        .unwrap_or_else(|| PathBuf::from("."))
        .join("xcode")
        .join("repl_history.txt");
    history.load_from_file(&history_path);

    let director = Director::new(ctx.config.agent.clone());
    let mut mode = ReplMode::Act;

    // When the command-menu returns a choice, we store it here instead of
    // calling rl.readline() again.  At the top of every loop iteration we
    // drain this slot first; only if it is empty do we ask readline for
    // actual user input.  This eliminates the ~100-line duplicate dispatch
    // block that previously lived inside the menu handler.
    let mut pending_line: Option<String> = None;

    // Plan mode conversation history (discuss, no tools)
    let mut conversation_messages: Vec<llm::Message> = Vec::new();

    // Act mode conversation history — seeded with CoderAgent system prompt.
    // Persists across turns so the agent has full context of previous work.
    let coder_system_prompt = {
        use crate::agent::agents_md::load_agents_md;
        use crate::agent::coder::CoderAgent;
        // Load AGENTS.md unless --no-agents-md was passed.
        // The content is prepended to the system prompt for the entire REPL session.
        let agents_md = if no_agents_md {
            None
        } else {
            load_agents_md(&ctx.project_dir)
        };
        if agents_md.is_some() {
            // We can't easily .await here inside a sync block, so we print directly.
            // show_status uses eprintln internally; this is the REPL init path.
            eprintln!("  \u{1F4CB} Loaded project rules from AGENTS.md");
        }
        CoderAgent::new_with_agents_md(ctx.config.agent.clone(), agents_md).system_prompt()
    };
    let mut act_messages: Vec<llm::Message> = vec![llm::Message::system(&coder_system_prompt)];
    let mut last_user_message: Option<String> = None;

    // ── Undo stack ────────────────────────────────────────────────────────────
    // The undo history is persisted in the SQLite DB (undo_history table).
    // Before each Act-mode run we push a unique stash label; after each run we
    // record the label in the DB if git actually created a stash entry.
    // /undo pops entries from the DB and calls `git stash pop stash@{N}` to
    // restore the matching stash.
    //
    // If the project is not inside a git repo (or git is not installed) the
    // commands fail silently and undo is simply unavailable.
    //
    // Session-level token tracker — accumulates usage across all task runs this REPL session.
    let mut session_tracker = crate::tracking::SessionTracker::new(ctx.config.model.clone());
    loop {
        let prompt = match mode {
            ReplMode::Act => format!("{} ", style("xcodeai›").cyan().bold()),
            ReplMode::Plan => format!("{} ", style("[plan] xcodeai›").yellow().bold()),
        };

        // ── Status bar ─────────────────────────────────────────────────────────
        // Print a compact info line above the prompt showing cumulative token
        // usage, MCP servers, and LSP state.  Skipped on first prompt (no tokens).
        //
        // We gather the three pieces of data the bar needs:
        //   1. session_tracker — already in scope above, accumulates token/cost.
        //   2. MCP server names — from ctx.mcp_clients (a Vec of (name, Arc<Mutex<McpClient>>)).
        //   3. LSP: check if lsp_client is Some, and what server_command is configured.
        //
        // NOTE: ctx.tool_ctx.lsp_client is Arc<Mutex<Option<LspClient>>>.
        // We use try_lock() (non-blocking) to avoid deadlocking the async runtime.
        // If the lock is held (very unlikely at prompt time), we conservatively
        // assume no LSP is active rather than blocking.
        let mcp_names: Vec<String> = ctx
            .mcp_clients
            .iter()
            .map(|(name, _)| name.clone())  // extract just the display name
            .collect();

        // Check if the LSP client is currently running.
        // try_lock() returns Ok(guard) immediately or Err if already locked.
        let lsp_active = ctx
            .tool_ctx
            .lsp_client
            .try_lock()  // non-blocking attempt
            .map(|guard| guard.is_some())  // Some(LspClient) means it is running
            .unwrap_or(false);  // if locked, assume not active (safe fallback)

        // LSP server name from config (e.g. "rust-analyzer", or empty if not set).
        let lsp_server_name = ctx
            .config
            .lsp
            .server_command
            .as_deref()  // Option<String> → Option<&str>
            .unwrap_or("");  // use empty string when not configured

        // Print the bar.  If there's nothing to show yet, this is a no-op.
        print_status_bar(&session_tracker, &mcp_names, lsp_active, lsp_server_name);

        // Drain a pending command from the menu, or read a new line from the user.
        let line = if let Some(p) = pending_line.take() {
            p
        } else {
            match input::readline_with_suggestions(&prompt, &mut history, Some(&ctx.project_dir))
                .map_err(anyhow::Error::from)?
            {
                ReadResult::Line(raw) => {
                    let trimmed = raw.trim().to_string();
                    if trimmed.is_empty() {
                        continue;
                    }
                    history.push(&trimmed);
                    trimmed
                }
                ReadResult::Interrupted => {
                    info("Ctrl-C — type /exit or press Ctrl-D to quit.");
                    continue;
                }
                ReadResult::Eof => break,
            }
        };

        // ── REPL commands ──────────────────────────────────────────────────
        // If the line starts with '/' or is a plain exit word, route it to
        // handle_command().  The function returns:
        //   Ok(None)          → command handled, continue the loop
        //   Ok(Some(mode))    → mode changed (not used currently, mode is mutated in place)
        //   Err(e)            → propagate fatal error
        // Special case: '/' with a menu selection needs to buffer the chosen
        // command into `pending_line` so the loop processes it next iteration.
        if line.starts_with('/')
            || matches!(
                line.as_str(),
                "exit" | "quit" | "q" | "bye" | "bye!" | "exit!" | "quit!"
            )
        {
            // handle_command mutates mode/sess/ctx/messages in place.
            // For the '/' bare-slash case, commands.rs returns the chosen label
            // via rl history — but we need pending_line.  We special-case that
            // here: if show_command_menu() returns something, buffer it.
            if line == "/"
                || (line.starts_with('/')
                    && !line.starts_with("/model")
                    && !line.starts_with("/login")
                    && !line.starts_with("/undo")
                    && !line.starts_with("/init")
                    && !line.starts_with("/redo")
                    && !matches!(
                        line.as_str(),
                        "/plan"
                            | "/act"
                            | "/tokens"
                            | "/session"
                            | "/connect"
                            | "/clear"
                            | "/compact"
                            | "/help"
                            | "/logout"
                            | "/exit"
                            | "/quit"
                            | "/q"
                    ))
            {
                // Unknown /xxx command — show the interactive picker.
                if let Some(chosen) = show_command_menu() {
                    history.push(&chosen);
                    pending_line = Some(chosen);
                }
                continue;
            }
            // Clone the session ID before constructing ReplState so that
            // Rust doesn't see simultaneous mutable (&mut sess) and
            // immutable (&sess.id) borrows of the same binding.
            let sess_id = sess.id.clone();
            let action = handle_command(
                &line,
                &mut ReplState {
                    mode: &mut mode,
                    sess: &mut sess,
                    ctx: &mut ctx,
                    history: &mut history,
                    conversation_messages: &mut conversation_messages,
                    act_messages: &mut act_messages,
                    coder_system_prompt: &coder_system_prompt,
                    session_id: &sess_id,
                    session_tracker: &session_tracker,
                    last_user_message: &mut last_user_message,
                },
            )
            .await?;
            if let CommandAction::InjectLine(msg) = action {
                pending_line = Some(msg);
            }
            continue;
        }
        // ── Lazy auth guard ────────────────────────────────────────
        if !ctx.llm.is_copilot() && ctx.config.provider.api_key.is_empty() {
            err("No API key configured. Run /connect to pick a provider.");
            continue;
        }
        if ctx.llm.is_copilot() {
            if let Ok(None) | Err(_) = auth::CopilotOAuthToken::load() {
                err("Not authenticated with GitHub Copilot. Run /login first.");
                continue;
            }
        }

        // ── Save message & run agent ───────────────────────────────
        ctx.store
            .add_message(&sess.id, &llm::Message::user(&line))?;
        let title = auto_title(&line);
        let _ = ctx.store.update_session_timestamp(&sess.id);
        let _ = update_session_title(&ctx.store, &sess.id, &title);

        println!();
        match mode {
            ReplMode::Act => {
                // Append the user message to Act-mode history before calling the agent.
                act_messages.push(llm::Message::user(&line));
                last_user_message = Some(line.clone());

                // ── Pre-run git stash (enables /undo) ────────────────
                // Use a unique UUID-based label so we can identify this
                // specific stash later, even if the user created their own
                // stashes in the meantime.
                let stash_ref = format!("xcodeai-undo-{}", uuid::Uuid::new_v4());
                // Capture the first 80 chars of the user's message for the
                // undo history description shown in `/undo list`.
                let short_desc: String = line.chars().take(80).collect();
                let (stash_tx, stash_rx) = mpsc::channel::<std::io::Result<std::process::Output>>();
                {
                    let project_dir_clone = ctx.project_dir.clone();
                    // Clone stash_ref into the thread so we can move it.
                    let stash_ref_clone = stash_ref.clone();
                    std::thread::spawn(move || {
                        let out = std::process::Command::new("git")
                            .args(["stash", "push", "-m", &stash_ref_clone])
                            .current_dir(&project_dir_clone)
                            .output();
                        let _ = stash_tx.send(out);
                    });
                }

                // Stash is now running concurrently.  Start the agent immediately.
                let result = director
                    .execute(
                        &mut act_messages,
                        ctx.registry.as_ref(),
                        ctx.llm.as_ref(),
                        &ctx.tool_ctx,
                    )
                    .await;

                // Agent finished.  Collect the stash result (with a 30-second grace period).
                let stash_was_created = match stash_rx.recv_timeout(Duration::from_secs(30)) {
                    Ok(Ok(out)) if out.status.success() => {
                        let stdout = String::from_utf8_lossy(&out.stdout);
                        !stdout.contains("No local changes to save")
                    }
                    _ => false,
                };
                // Persist the undo entry in the DB so the user can restore
                // this state later with /undo (or /undo N).
                if stash_was_created {
                    let _ = ctx.store.push_undo(&sess.id, &stash_ref, &short_desc);
                    let _ = ctx
                        .store
                        .trim_undo_history(&sess.id, crate::session::store::MAX_UNDO_HISTORY);
                }

                println!();

                match result {
                    Ok(mut agent_result) => {
                        ctx.store.add_message(
                            &sess.id,
                            &llm::Message::assistant(
                                Some(agent_result.final_message.clone()),
                                None,
                            ),
                        )?;
                        ctx.store.update_session_timestamp(&sess.id)?;

                        print_separator("done");

                        // Fill in model name now (CoderAgent left it empty) so
                        // cost estimation in summary_line() can look up the price.
                        agent_result.tracker.model = ctx.config.model.clone();

                        // Merge this task's turns into the session-level tracker so
                        // /tokens shows cumulative stats across all runs this session.
                        for turn in &agent_result.tracker.turns {
                            session_tracker.record(Some(&crate::llm::Usage {
                                prompt_tokens: turn.prompt_tokens,
                                completion_tokens: turn.completion_tokens,
                                total_tokens: turn.prompt_tokens + turn.completion_tokens,
                            }));
                        }
                        // Keep the session tracker's model current (user may have used /model).
                        session_tracker.model = ctx.config.model.clone();

                        // Persist the accumulated token counts for this task run to SQLite.
                        // Non-fatal — don't crash on DB write failure, just silently ignore.
                        let _ = ctx.store.update_session_tokens(
                            &sess.id,
                            agent_result.tracker.total_prompt_tokens(),
                            agent_result.tracker.total_completion_tokens(),
                        );

                        // Build a stats line showing iterations, tool calls, and auto-continues.
                        let mut stats_parts: Vec<String> = vec![
                            format!("{} iterations", agent_result.iterations),
                            format!("{} tool calls", agent_result.tool_calls_total),
                        ];
                        if agent_result.auto_continues > 0 {
                            stats_parts
                                .push(format!("{} auto-continues", agent_result.auto_continues));
                        }
                        // Append token summary when the provider returned usage data.
                        let token_summary = agent_result.tracker.summary_line();
                        if !token_summary.is_empty() {
                            stats_parts.push(token_summary);
                        }
                        let stats_str = stats_parts
                            .iter()
                            .map(|s| format!("{}", style(s).dim()))
                            .collect::<Vec<_>>()
                            .join(&format!("  {}  ", style("·").dim()));

                        println!(
                            "   {} {}  {}  {}",
                            style("").green().bold(),
                            style("task complete").green(),
                            style("·").dim(),
                            stats_str,
                        );
                        print_separator("");

                        // ── Git diff summary ──────────────────────
                        let diff_output = std::process::Command::new("git")
                            .args(["diff", "--stat", "HEAD"])
                            .current_dir(&ctx.project_dir)
                            .output();
                        if let Ok(out) = diff_output {
                            let text = String::from_utf8_lossy(&out.stdout);
                            let trimmed = text.trim();
                            if !trimmed.is_empty() {
                                println!(
                                    "  {} {}",
                                    style("").dim(),
                                    style("git diff --stat HEAD").dim()
                                );
                                for line in trimmed.lines() {
                                    println!("   {}", style(line).dim());
                                }
                                println!();
                            }
                        }

                        println!();
                    }
                    Err(e) => {
                        act_messages.pop();
                        err(&format!("{:#}", e));
                        info("Try a different task, or type /exit to quit.");
                    }
                }
            }
            ReplMode::Plan => {
                // Add user message to plan conversation history
                conversation_messages.push(llm::Message::user(&line));

                // Disable streaming stdout so we can post-process the reply
                ctx.llm.set_stream_print(false);
                let plan_result = run_plan_turn(
                    &conversation_messages,
                    ctx.llm.as_ref(),
                    ctx.registry.as_ref(),
                    &ctx.tool_ctx,
                )
                .await;
                ctx.llm.set_stream_print(true);

                match plan_result {
                    Ok(reply) => {
                        if !reply.trim().is_empty() {
                            println!("{}", reply.trim_end());
                            println!();
                        }

                        // Save to conversation history and session store.
                        conversation_messages
                            .push(llm::Message::assistant(Some(reply.clone()), None));
                        ctx.store
                            .add_message(&sess.id, &llm::Message::assistant(Some(reply), None))?;
                        ctx.store.update_session_timestamp(&sess.id)?;
                    }
                    Err(e) => {
                        err(&format!("{:#}", e));
                        info("Plan mode error. Try again or type /act to switch back.");
                        conversation_messages.pop();
                    }
                }
            }
        }
    }

    history.save_to_file(&history_path);
    println!();
    ok(&format!("Session saved: {}", style(&sess.id).dim()));
    info(&format!("xcodeai session show {}", sess.id));
    println!();

    Ok(())
}