Skip to main content

winx_code_agent/tools/
bash_command.rs

1//! Implementation of the `BashCommand` tool with WCGW parity.
2//!
3//! This module provides the implementation for the `BashCommand` tool, which is used
4//! to execute shell commands, check command status, and interact with the shell.
5//! Matches the behavior of wcgw Python implementation 1:1.
6
7use anyhow::Context as AnyhowContext;
8use rand::RngExt;
9use regex::Regex;
10use std::collections::HashMap;
11use std::fmt::Write as FmtWrite;
12use std::path::{Path, PathBuf};
13use std::sync::{Arc, Mutex as StdMutex};
14use std::time::{Duration, Instant};
15use tokio::sync::Mutex;
16use tokio::time::sleep;
17use tracing::{debug, error, info, warn};
18
19use crate::errors::{Result, WinxError};
20use crate::state::bash_state::BashState;
21use crate::state::live_terminal::ScreenUpdate;
22use crate::state::pty::PtyShell;
23use crate::state::terminal::{render_terminal_output, strip_ansi_codes};
24use crate::types::{normalize_thread_id, BashCommand, BashCommandAction, SpecialKey};
25
26type SharedPtyShell = Arc<Mutex<Option<PtyShell>>>;
27
28// ==================== WCGW-Style Constants ====================
29
30/// Default timeout for command execution (seconds) - matches WCGW Python Config.timeout
31const DEFAULT_TIMEOUT: f64 = 5.0;
32
33/// Extended timeout while output is still being produced - matches WCGW Python `Config.timeout_while_output`
34const TIMEOUT_WHILE_OUTPUT: f64 = 20.0;
35
36/// Number of iterations to wait without new output before giving up - matches WCGW Python `Config.output_wait_patience`
37const OUTPUT_WAIT_PATIENCE: i32 = 3;
38
39/// Async poll interval for adaptive output reads. We drain whatever the reader
40/// thread has queued (non-blocking), release the shell lock, then `await` this
41/// long — yielding the executor instead of pinning it on a blocking sleep.
42const POLL_INTERVAL_MS: u64 = 20;
43
44/// Grace period after the prompt is seen, to capture bytes that land just after
45/// it (mirrors the old `read_output` post-prompt drain) — awaited, not blocked.
46const POST_PROMPT_DRAIN_MS: u64 = 100;
47
48/// Chunk size for sending commands (characters) - matches WCGW Python (64 chars)
49const COMMAND_CHUNK_SIZE: usize = 64;
50
51/// Chunk size for sending text input (characters) - matches WCGW Python (128 chars)
52const TEXT_CHUNK_SIZE: usize = 128;
53
54/// Cheap byte-level safety net. We never even consider token counting if the
55/// raw payload is smaller than this — tokenizing is fast but not free, and
56/// the vast majority of responses are tiny status updates.
57const MAX_OUTPUT_LENGTH: usize = 100_000;
58
59/// Token budget reserved for a single PTY response when token-aware truncation
60/// kicks in. Picked to leave plenty of room for the surrounding context — most
61/// frontier models have 128k+ windows, so 25k for one shell payload is generous
62/// without monopolizing the conversation.
63const MAX_OUTPUT_TOKENS: usize = 25_000;
64
65/// Delay between typing text and the submitting Enter. Ink-based TUIs (Claude
66/// Code) collapse a burst of bytes into a single render tick and drop a CR that
67/// arrives glued to the text — the input box updates but never submits. Sending
68/// the Enter as a separate write after this short pause lets the TUI commit the
69/// typed text first, so `submit: true` reliably submits. ~40ms is imperceptible
70/// yet enough for the event loop to flush; harmless for plain shells.
71const SUBMIT_NUDGE_DELAY: Duration = Duration::from_millis(40);
72
73/// `screen` diff mode emits a per-line delta only when at most this many lines
74/// changed; beyond that the full frame is cheaper to read than a giant diff.
75const SCREEN_DIFF_THRESHOLD: usize = 10;
76
77/// Tail of `text` at most `max_len` bytes long, snapped up to a char boundary so
78/// we never slice through a multibyte UTF-8 sequence (which would panic).
79fn char_safe_tail(text: &str, max_len: usize) -> &str {
80    if text.len() <= max_len {
81        return text;
82    }
83    let mut start = text.len() - max_len;
84    while start < text.len() && !text.is_char_boundary(start) {
85        start += 1;
86    }
87    &text[start..]
88}
89
90/// Truncate `text` so its Claude token count stays under `max_tokens`.
91///
92/// We tokenize the tail of the string only when the raw byte length already
93/// exceeds the byte cap; otherwise we trust the byte budget and return as-is.
94/// When the tail still overshoots, we keep the last `max_tokens - reserve`
95/// tokens and prepend a "(...truncated)" marker — exactly what wcgw does in
96/// `_incremental_text`.
97fn truncate_to_token_budget(text: &str, max_tokens: usize) -> std::borrow::Cow<'_, str> {
98    if text.len() <= MAX_OUTPUT_LENGTH {
99        return std::borrow::Cow::Borrowed(text);
100    }
101
102    let Some(tokens) = crate::utils::encoder::encode_ids(text) else {
103        // Fallback to the byte-based truncation we used before the tokenizer.
104        return std::borrow::Cow::Owned(format!(
105            "(...truncated)\n{}",
106            char_safe_tail(text, MAX_OUTPUT_LENGTH)
107        ));
108    };
109
110    if tokens.len() <= max_tokens {
111        return std::borrow::Cow::Borrowed(text);
112    }
113
114    // Reserve one token slot for the marker overhead.
115    let keep = max_tokens.saturating_sub(1);
116    let tail = &tokens[tokens.len() - keep..];
117    let decoded = crate::utils::encoder::decode_ids(tail).unwrap_or_else(|| {
118        // Tokenizer present but decode failed: fall back to a byte tail.
119        char_safe_tail(text, MAX_OUTPUT_LENGTH).to_string()
120    });
121    std::borrow::Cow::Owned(format!("(...truncated)\n{decoded}"))
122}
123
124/// Message when a command is already running - matches WCGW Python `WAITING_INPUT_MESSAGE`
125const WAITING_INPUT_MESSAGE: &str = "A command is already running. NOTE: You can't run multiple shell commands in main shell, likely a previous program hasn't exited.
1261. Get its output using status check.
1272. Use `send_ascii` or `send_specials` to give inputs to the running program OR
1283. kill the previous program by sending ctrl+c first using `send_ascii` or `send_specials`
1294. Interrupt and run the process in background
130";
131
132// ==================== Background Shell Manager ====================
133
134/// Snapshot of a background shell that has exited but whose final output has not
135/// yet been consumed by the caller. We keep it around so the next call (typically
136/// a `status_check`) can return the trailing output before the entry is gone.
137#[derive(Debug, Clone)]
138pub struct ExitedShellInfo {
139    pub last_command: String,
140    pub final_output: String,
141    pub exited_at: Instant,
142}
143
144/// Manages background shell sessions - matches WCGW Python's `background_shells` dict
145#[derive(Debug, Default)]
146pub struct BackgroundShellManager {
147    shells: HashMap<String, SharedPtyShell>,
148    /// Recently exited shells that still owe their final output to the caller.
149    /// Entries are consumed the first time the caller queries the id, then dropped.
150    tombstones: HashMap<String, ExitedShellInfo>,
151}
152
153impl BackgroundShellManager {
154    /// Tombstones older than this are garbage-collected on the next prune pass.
155    const TOMBSTONE_TTL: Duration = Duration::from_secs(300);
156
157    /// Create a new background shell manager
158    pub fn new() -> Self {
159        Self { shells: HashMap::new(), tombstones: HashMap::new() }
160    }
161
162    /// Start a new background shell and return its command ID
163    /// Register an already-built shell and return its id.
164    ///
165    /// The caller builds the `PtyShell` BEFORE taking the manager lock —
166    /// `PtyShell::new` forks+execs and does a ~300ms blocking prompt init, which
167    /// must not run under the global `std::Mutex` (it would serialize every other
168    /// background-shell op behind one slow spawn).
169    pub fn register_shell(&mut self, shell: PtyShell) -> String {
170        let cid = format!("{:010x}", rand::rng().random::<u32>());
171        self.shells.insert(cid.clone(), Arc::new(Mutex::new(Some(shell))));
172        info!("Started background shell with id: {}", cid);
173        cid
174    }
175
176    /// Get a background shell by its command ID
177    pub fn get_shell(&self, bg_command_id: &str) -> Option<SharedPtyShell> {
178        self.shells.get(bg_command_id).cloned()
179    }
180
181    /// Remove and cleanup a background shell
182    pub fn remove_shell(&mut self, bg_command_id: &str) -> bool {
183        if let Some(shell_arc) = self.shells.remove(bg_command_id) {
184            if let Ok(mut guard) = shell_arc.try_lock() {
185                *guard = None;
186            }
187            info!("Removed background shell: {}", bg_command_id);
188            true
189        } else {
190            false
191        }
192    }
193
194    fn prune_finished_shells(&mut self) {
195        // GC old tombstones first.
196        let now = Instant::now();
197        self.tombstones.retain(|_, info| now.duration_since(info.exited_at) < Self::TOMBSTONE_TTL);
198
199        let mut finished: Vec<(String, Option<ExitedShellInfo>)> = Vec::new();
200
201        for (id, shell_arc) in &self.shells {
202            let Ok(mut guard) = shell_arc.try_lock() else {
203                continue;
204            };
205
206            let Some(shell) = guard.as_mut() else {
207                finished.push((id.clone(), None));
208                continue;
209            };
210
211            if !shell.is_alive() {
212                let tombstone = ExitedShellInfo {
213                    last_command: shell.last_command.clone(),
214                    final_output: std::mem::take(&mut shell.output_buffer),
215                    exited_at: now,
216                };
217                finished.push((id.clone(), Some(tombstone)));
218                continue;
219            }
220
221            // Never prune shells that haven't received a command yet.
222            // The global BG_SHELL_MANAGER is shared across parallel tests; a freshly
223            // spawned shell would otherwise be evicted between start_new_shell and
224            // the first send_command, leading to "Failed to get background shell".
225            if shell.last_command.is_empty() {
226                continue;
227            }
228
229            if shell.command_running {
230                // Non-blocking: draining here must NOT hold the global manager
231                // lock across a 100ms blocking read (that serializes every other
232                // background-shell op behind a single slow PTY).
233                shell.poll_output_nonblocking();
234            }
235
236            if !shell.command_running {
237                let tombstone = ExitedShellInfo {
238                    last_command: shell.last_command.clone(),
239                    final_output: std::mem::take(&mut shell.output_buffer),
240                    exited_at: now,
241                };
242                finished.push((id.clone(), Some(tombstone)));
243            }
244        }
245
246        for (id, tombstone) in finished {
247            self.remove_shell(&id);
248            if let Some(info) = tombstone {
249                self.tombstones.insert(id, info);
250            }
251        }
252    }
253
254    /// Look up the tombstone for a recently-exited shell, if any.
255    ///
256    /// The entry stays in the map until the TTL expires (see
257    /// `prune_finished_shells`), so repeated `status_check` calls on the same
258    /// `bg_command_id` keep returning the cached final output instead of
259    /// flipping to "shell not found" after the first read.
260    pub fn peek_tombstone(&self, bg_command_id: &str) -> Option<ExitedShellInfo> {
261        self.tombstones.get(bg_command_id).cloned()
262    }
263
264    /// Get info about all running background shells - matches WCGW Python `get_bg_running_commandsinfo`
265    pub fn get_running_info(&mut self) -> String {
266        self.prune_finished_shells();
267
268        if self.shells.is_empty() {
269            return "No command running in background.\n".to_string();
270        }
271
272        let mut running = Vec::new();
273        for (id, shell_arc) in &self.shells {
274            if let Ok(guard) = shell_arc.try_lock() {
275                if let Some(bash) = guard.as_ref() {
276                    if bash.command_running {
277                        running
278                            .push(format!("Command: {}, bg_command_id: {}", bash.last_command, id));
279                    }
280                }
281            } else {
282                running.push(format!("Command: <busy>, bg_command_id: {id}"));
283            }
284        }
285
286        if running.is_empty() {
287            "No command running in background.\n".to_string()
288        } else {
289            format!("Following background commands are attached:\n{}\n", running.join("\n"))
290        }
291    }
292}
293
294// Global background shell manager (thread-safe) - matches WCGW Python's BashState.background_shells
295lazy_static::lazy_static! {
296    static ref BG_SHELL_MANAGER: StdMutex<BackgroundShellManager> = StdMutex::new(BackgroundShellManager::new());
297}
298
299/// Lock the global background-shell manager, recovering from poisoning.
300///
301/// A panic while holding this lock (e.g. in the rendering path during a prune)
302/// must NOT permanently brick all background-shell functionality for the rest of
303/// the server's lifetime. The manager's data stays consistent across a panic, so
304/// recovering the inner guard is safe.
305fn lock_bg_manager() -> std::sync::MutexGuard<'static, BackgroundShellManager> {
306    BG_SHELL_MANAGER.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
307}
308
309// ==================== WCGW-Style Helper Functions ====================
310
311/// Get WCGW-style status string - matches WCGW Python's `get_status()`
312fn get_status(
313    bash_state: &BashState,
314    is_bg: bool,
315    bg_id: Option<&str>,
316    is_running: bool,
317    running_for: Option<&str>,
318    exit_code: Option<i32>,
319) -> String {
320    let mut status = "\n\n---\n\n".to_string();
321
322    if is_bg {
323        if let Some(id) = bg_id {
324            let _ = writeln!(status, "bg_command_id = {id}");
325        }
326    }
327
328    if is_running {
329        status.push_str("status = still running\n");
330        if let Some(duration) = running_for {
331            let _ = writeln!(status, "running for = {duration}");
332        }
333    } else {
334        status.push_str("status = process exited\n");
335        // Exit code of the just-finished command, parsed from the prompt marker
336        // (`──➤<nonce>:<code>`). Lets the agent see failure without grepping stderr.
337        if let Some(code) = exit_code {
338            let _ = writeln!(status, "exit code = {code}");
339        }
340    }
341
342    let _ = writeln!(status, "cwd = {}", bash_state.cwd.display());
343
344    if !is_bg {
345        // Add background shell info for main shell - matches WCGW Python
346        {
347            let mut manager = lock_bg_manager();
348            status.push_str("This is the main shell. ");
349            status.push_str(&manager.get_running_info());
350        }
351    }
352
353    status.trim_end().to_string()
354}
355
356/// Process output with WCGW-style incremental text handling - matches WCGW Python _`incremental_text`
357fn wcgw_incremental_text(text: &str, last_pending_output: &str) -> String {
358    let truncated = truncate_to_token_budget(text, MAX_OUTPUT_TOKENS);
359    let text = truncated.as_ref();
360
361    if last_pending_output.is_empty() {
362        let rendered = render_terminal_output(text);
363        return rstrip_lines(&rendered).trim_start().to_string();
364    }
365
366    let last_rendered = render_terminal_output(last_pending_output);
367    if last_rendered.is_empty() {
368        return rstrip_lines(&render_terminal_output(text));
369    }
370
371    // Get text after last pending output. Snap the offset down to a char
372    // boundary: `last_pending_output.len()` is a byte count and may land inside
373    // a multibyte code point of `text`, which would panic on the slice.
374    let text_after_last = if text.len() > last_pending_output.len() {
375        let cut = crate::utils::floor_char_boundary(text, last_pending_output.len());
376        &text[cut..]
377    } else {
378        text
379    };
380
381    let combined = format!("{}\n{}", last_rendered.join("\n"), text_after_last);
382    let new_rendered = render_terminal_output(&combined);
383
384    // Get incremental part - matches WCGW Python get_incremental_output
385    let incremental = get_incremental_output(&last_rendered, &new_rendered);
386    rstrip_lines(&incremental)
387}
388
389fn extract_prompt_cwd(output: &str) -> Option<PathBuf> {
390    static PROMPT_RE: std::sync::OnceLock<Regex> = std::sync::OnceLock::new();
391    // `.expect`, not `.ok()`: a compile-time-literal regex that fails to build is a
392    // dev bug, not a runtime condition. The old `OnceLock<Option<Regex>>` froze
393    // `None` forever on the first failure, silently disabling all CWD tracking for
394    // the rest of the process. Fail loud instead.
395    #[allow(clippy::expect_used)]
396    let prompt_regex = PROMPT_RE
397        .get_or_init(|| Regex::new(r"◉ (?P<cwd>[^\r\n]*?)──➤").expect("prompt regex must compile"));
398    let stripped = strip_ansi_codes(output);
399
400    prompt_regex
401        .captures_iter(&stripped)
402        .filter_map(|captures| captures.name("cwd").map(|cwd| cwd.as_str().trim()))
403        .filter(|cwd| !cwd.is_empty())
404        .last()
405        .map(PathBuf::from)
406}
407
408/// Right-strip each line and join - matches WCGW Python rstrip
409fn rstrip_lines(lines: &[String]) -> String {
410    lines.iter().map(|line| line.trim_end()).collect::<Vec<_>>().join("\n")
411}
412
413/// Get incremental output between old and new - matches WCGW Python `get_incremental_output`
414fn get_incremental_output(old_output: &[String], new_output: &[String]) -> Vec<String> {
415    if old_output.is_empty() {
416        return new_output.to_vec();
417    }
418
419    let nold = old_output.len();
420    let nnew = new_output.len();
421
422    // Find where old output ends in new output
423    for i in (0..nnew).rev() {
424        if new_output[i] != old_output[nold - 1] {
425            continue;
426        }
427
428        let mut matched = true;
429        for j in (0..i).rev() {
430            let old_idx = (nold as i64 - 1 + j as i64 - i as i64) as isize;
431            if old_idx < 0 {
432                break;
433            }
434            if new_output[j] != old_output[old_idx as usize] {
435                matched = false;
436                break;
437            }
438        }
439
440        if matched {
441            return new_output[i + 1..].to_vec();
442        }
443    }
444
445    new_output.to_vec()
446}
447
448fn send_utf8_in_byte_chunks(shell: &mut PtyShell, text: &str, chunk_size: usize) -> Result<()> {
449    let mut start = 0;
450
451    while start < text.len() {
452        let mut end = (start + chunk_size).min(text.len());
453        while !text.is_char_boundary(end) {
454            end -= 1;
455        }
456        if end == start {
457            end = text[start..].char_indices().nth(1).map_or(text.len(), |(idx, _)| start + idx);
458        }
459
460        shell.send_text(&text[start..end]).map_err(|e| {
461            WinxError::CommandExecutionError(format!("Failed to write PTY input: {e}"))
462        })?;
463        start = end;
464    }
465
466    Ok(())
467}
468
469/// Send the submitting Enter as a separate, slightly-delayed write so an
470/// Ink-based TUI doesn't swallow a CR glued to the preceding input. Briefly
471/// drops the shell lock during the pause so the reader thread keeps draining.
472/// See [`SUBMIT_NUDGE_DELAY`].
473async fn submit_enter(shell_arc: &SharedPtyShell) -> Result<()> {
474    tokio::time::sleep(SUBMIT_NUDGE_DELAY).await;
475    let mut guard = shell_arc.lock().await;
476    let bash = guard.as_mut().ok_or(WinxError::BashStateNotInitialized)?;
477    bash.send_special_key("Enter")
478        .map_err(|e| WinxError::CommandExecutionError(format!("Failed to submit: {e}")))?;
479    Ok(())
480}
481
482// ==================== Main Tool Handler ====================
483
484/// Handles the `BashCommand` tool call with WCGW parity
485///
486/// This function processes the `BashCommand` tool call following WCGW Python's
487/// `execute_bash()` function behavior exactly.
488#[tracing::instrument(level = "info", skip(bash_state_arc, bash_command))]
489pub async fn handle_tool_call(
490    bash_state_arc: &Arc<Mutex<Option<BashState>>>,
491    bash_command: BashCommand,
492) -> Result<String> {
493    info!("BashCommand tool called with: {:?}", bash_command);
494
495    let thread_id = normalize_thread_id(&bash_command.thread_id);
496
497    // Check if thread_id is empty
498    if thread_id.is_empty() {
499        error!("Empty thread_id provided in BashCommand");
500        return Err(WinxError::ThreadIdMismatch(
501            "Error: No saved bash state found for thread ID \"\". Please initialize first with this ID.".to_string()
502        ));
503    }
504
505    // Extract bash_state data
506    let mut bash_state: BashState;
507    {
508        let bash_state_guard = bash_state_arc.lock().await;
509
510        let Some(state) = &*bash_state_guard else {
511            error!("BashState not initialized");
512            return Err(WinxError::BashStateNotInitialized);
513        };
514
515        bash_state = state.clone();
516    }
517
518    // Verify thread ID matches - matches WCGW Python thread_id check
519    if thread_id != bash_state.current_thread_id {
520        // Try to load state from thread_id - matches WCGW Python load_state_from_thread_id
521        // Distinguish "no state for this id" (Ok(false)) from a real load failure
522        // (Err: permission denied, corrupt JSON). The old `.unwrap_or(false)`
523        // collapsed both into the misleading "initialize first" message.
524        let loaded = bash_state.load_state_from_disk(&thread_id).map_err(|e| {
525            WinxError::CommandExecutionError(format!(
526                "Failed to load saved bash state for thread_id `{thread_id}`: {e}"
527            ))
528        })?;
529        if !loaded {
530            return Err(WinxError::ThreadIdMismatch(format!(
531                "Error: No saved bash state found for thread_id `{thread_id}`. Please initialize first with this ID."
532            )));
533        }
534        // Promote the loaded state back to the shared slot. The old code only wrote
535        // `cwd` back at the end, so switching thread_id silently dropped the loaded
536        // whitelist/mode/thread_id — the next command re-cloned the stale state.
537        // load_state_from_disk doesn't touch pty_shell (shells aren't serialized),
538        // so the live shell Arc is preserved through the clone.
539        if let Some(state) = bash_state_arc.lock().await.as_mut() {
540            *state = bash_state.clone();
541        }
542    }
543
544    // Calculate effective timeout - matches WCGW Python
545    // SECURITY: Ensure timeout is not negative to prevent unexpected behavior
546    let timeout_s = bash_command
547        .wait_for_seconds
548        .map_or(DEFAULT_TIMEOUT, |t| f64::from(t).max(0.0))
549        .min(TIMEOUT_WHILE_OUTPUT);
550
551    // Execute the action based on type - matches WCGW Python's _execute_bash()
552    let result = execute_bash_action(&mut bash_state, &bash_command.action_json, timeout_s).await;
553
554    {
555        let mut bash_state_guard = bash_state_arc.lock().await;
556        if let Some(state) = bash_state_guard.as_mut() {
557            state.cwd.clone_from(&bash_state.cwd);
558        }
559    }
560
561    // Remove echo if it's a command - matches WCGW Python
562    match result {
563        Ok(mut output) => {
564            if let BashCommandAction::Command { ref command, .. } = bash_command.action_json {
565                let cmd_trimmed = command.trim();
566                if output.starts_with(cmd_trimmed) {
567                    output = output[cmd_trimmed.len()..].to_string();
568                }
569            }
570            Ok(output)
571        }
572        Err(e) => Err(e),
573    }
574}
575
576/// Execute a bash action - matches WCGW Python's _`execute_bash()` function
577#[allow(clippy::too_many_lines)]
578async fn execute_bash_action(
579    bash_state: &mut BashState,
580    action: &BashCommandAction,
581    timeout_s: f64,
582) -> Result<String> {
583    let mut is_bg = false;
584    let mut bg_id: Option<String> = None;
585
586    // Handle bg_command_id routing - matches WCGW Python
587    let bg_shell: Option<SharedPtyShell> = match action {
588        BashCommandAction::Command { .. } => None, // Commands don't use bg_command_id for routing
589        BashCommandAction::StatusCheck { bg_command_id, .. }
590        | BashCommandAction::SendText { bg_command_id, .. }
591        | BashCommandAction::SendSpecials { bg_command_id, .. }
592        | BashCommandAction::SendAscii { bg_command_id, .. }
593        | BashCommandAction::Screen { bg_command_id, .. }
594        | BashCommandAction::WaitForTurn { bg_command_id, .. } => {
595            if let Some(id) = bg_command_id {
596                // Use the recovery helper (poison -> into_inner) like every other
597                // call site, rather than hard-failing this one path on poison.
598                let mut manager = lock_bg_manager();
599                manager.prune_finished_shells();
600
601                if let Some(shell) = manager.get_shell(id) {
602                    is_bg = true;
603                    bg_id = Some(id.clone());
604                    Some(shell)
605                } else if let Some(tombstone) = manager.peek_tombstone(id) {
606                    // Shell already exited. For a status check we can hand back the
607                    // final cached output exactly once. For anything else (send_text,
608                    // send_specials, send_ascii) tell the caller the shell is gone
609                    // and include the captured output so they can recover state.
610                    drop(manager);
611                    return finalize_tombstone(&bash_state.cwd, id, tombstone, action);
612                } else {
613                    // Error message matches WCGW Python
614                    let error = format!(
615                        "No shell found running with command id {}.\n{}",
616                        id,
617                        manager.get_running_info()
618                    );
619                    return Err(WinxError::CommandExecutionError(error));
620                }
621            } else {
622                None
623            }
624        }
625    };
626
627    // Process based on action type - matches WCGW Python _execute_bash dispatch
628    match action {
629        BashCommandAction::Command { command, is_background, allow_multi } => {
630            execute_command(bash_state, command, *is_background, *allow_multi, timeout_s).await
631        }
632        BashCommandAction::StatusCheck { scrollback_lines, verbose, .. } => {
633            execute_status_check(
634                bash_state,
635                bg_shell,
636                is_bg,
637                bg_id.as_deref(),
638                timeout_s,
639                *scrollback_lines,
640                *verbose,
641            )
642            .await
643        }
644        BashCommandAction::SendText { send_text, submit, .. } => {
645            execute_send_text(
646                bash_state,
647                send_text,
648                *submit,
649                bg_shell,
650                is_bg,
651                bg_id.as_deref(),
652                timeout_s,
653            )
654            .await
655        }
656        BashCommandAction::SendSpecials { send_specials, submit, .. } => {
657            execute_send_specials(
658                bash_state,
659                send_specials,
660                *submit,
661                bg_shell,
662                is_bg,
663                bg_id.as_deref(),
664                timeout_s,
665            )
666            .await
667        }
668        BashCommandAction::SendAscii { send_ascii, submit, .. } => {
669            execute_send_ascii(
670                bash_state,
671                send_ascii,
672                *submit,
673                bg_shell,
674                is_bg,
675                bg_id.as_deref(),
676                timeout_s,
677            )
678            .await
679        }
680        BashCommandAction::Screen { lines, diff, .. } => {
681            execute_screen(bash_state, bg_shell, is_bg, bg_id.as_deref(), *lines, *diff).await
682        }
683        BashCommandAction::WaitForTurn { recognizer, quiet_ms, timeout_seconds, lines, .. } => {
684            execute_wait_for_turn(
685                bash_state,
686                bg_shell,
687                is_bg,
688                bg_id.as_deref(),
689                recognizer.as_deref(),
690                *quiet_ms,
691                *timeout_seconds,
692                *lines,
693            )
694            .await
695        }
696    }
697}
698
699/// Strip a trailing `| tail ...` from a command (wcgw parity, `strip_tail_pipe`).
700///
701/// LLMs habitually pipe output through `tail`, but we already truncate output
702/// server-side — stripping the pipe avoids hiding the earlier output the model
703/// usually wants. Only a `tail` at the very end of the command is removed.
704///
705/// This matches wcgw by default. Set `WINX_KEEP_TAIL_PIPE=1` to preserve the
706/// pipe instead (winx's original behavior), e.g. when you deliberately want only
707/// the tail of a huge log rather than the server-side truncation.
708fn strip_tail_pipe(command: &str) -> String {
709    strip_tail_pipe_impl(command, keep_tail_pipe())
710}
711
712/// Pure core of [`strip_tail_pipe`], split out so both modes are unit-testable
713/// without touching process-wide env vars (tests run concurrently).
714fn strip_tail_pipe_impl(command: &str, keep: bool) -> String {
715    static RE: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
716    if keep {
717        return command.to_string();
718    }
719    // `.expect`, not `.ok()`: a compile-time-literal regex that fails to build is
720    // a dev bug. The old `OnceLock<Option<Regex>>` + `.ok()` would freeze `None`
721    // and silently stop stripping `| tail` for the whole process.
722    #[allow(clippy::expect_used)]
723    let re = RE.get_or_init(|| {
724        regex::Regex::new(r"\|\s*tail(?:\s+(?:-n\s*|-)?(\d+))?\s*$")
725            .expect("tail-pipe regex must compile")
726    });
727    match re.find(command) {
728        Some(matched) => command[..matched.start()].trim_end().to_string(),
729        None => command.to_string(),
730    }
731}
732
733/// Whether the user opted out of `| tail` stripping via `WINX_KEEP_TAIL_PIPE`.
734fn keep_tail_pipe() -> bool {
735    std::env::var("WINX_KEEP_TAIL_PIPE").is_ok_and(|value| {
736        let value = value.trim();
737        !value.is_empty() && value != "0" && !value.eq_ignore_ascii_case("false")
738    })
739}
740
741/// Execute a command - matches WCGW Python's Command handling in _`execute_bash`
742async fn execute_command(
743    bash_state: &mut BashState,
744    command: &str,
745    is_background: bool,
746    allow_multi: bool,
747    timeout_s: f64,
748) -> Result<String> {
749    // wcgw strips a trailing `| tail` before anything else (model_validator).
750    let stripped_command = strip_tail_pipe(command);
751    let command = stripped_command.as_str();
752    debug!("Processing Command action: {command:?} (allow_multi={allow_multi})");
753
754    // Check mode permissions - matches WCGW Python bash_command_mode check
755    if !bash_state.is_command_allowed(command) {
756        error!("Command '{}' not allowed in current mode", command);
757        return Err(WinxError::CommandNotAllowed(
758            "Error: BashCommand not allowed in current mode".to_string(),
759        ));
760    }
761
762    // Single-statement guard (wcgw parity). Callers can opt out via
763    // `allow_multi: true` when they knowingly want to chain commands
764    // without wrapping in `bash -lc '...'`.
765    let command = command.trim();
766    if !allow_multi {
767        // The `bash -n -c` fallback inside the parser spawns a shell; only allow
768        // that probe in trusted (wcgw) mode. In restricted modes tree-sitter is
769        // the sole arbiter so we never shell out to vet a command.
770        let allow_shell_probe = matches!(bash_state.mode, crate::types::Modes::Wcgw);
771        crate::utils::bash_parser::assert_single_statement(command, allow_shell_probe)?;
772    }
773
774    // If background execution requested, start new shell - matches WCGW Python is_background handling
775    if is_background {
776        return execute_in_background(bash_state, command, timeout_s).await;
777    }
778
779    // Check if a command is already running - matches WCGW Python state check
780    {
781        let bash_guard = bash_state.pty_shell.lock().await;
782
783        if let Some(ref bash) = *bash_guard {
784            if bash.command_running {
785                return Err(WinxError::CommandExecutionError(WAITING_INPUT_MESSAGE.to_string()));
786            }
787        }
788    }
789
790    // Initialize bash if needed
791    if bash_state.pty_shell.lock().await.is_none() {
792        bash_state
793            .init_pty_shell()
794            .await
795            .map_err(|e| WinxError::CommandExecutionError(format!("Failed to init bash: {e}")))?;
796    }
797
798    // Clear prompt before sending - matches WCGW Python clear_to_run.
799    // Drain any leftover output and, if the shell still looks busy, send
800    // Ctrl-C so the new command lands on a fresh prompt instead of being
801    // appended to whatever was hanging on stdin.
802    {
803        let needs_reset = {
804            // Only when a shell exists. clear_to_run_async drains/interrupts WITHOUT
805            // holding the lock across a blocking sleep (was bash.clear_to_run, which
806            // slept up to DEFAULT_TIMEOUT seconds inside the tokio mutex).
807            if bash_state.pty_shell.lock().await.is_some() {
808                if clear_to_run_async(&bash_state.pty_shell, DEFAULT_TIMEOUT).await {
809                    false
810                } else {
811                    warn!("clear_to_run: shell still busy after Ctrl-C, resetting it");
812                    true
813                }
814            } else {
815                false
816            }
817        };
818        // wcgw parity: a shell that won't return to a prompt even after Ctrl-C is
819        // recreated, so the new command lands on a fresh prompt instead of being
820        // appended to a hung shell. init_pty_shell rebuilds at the same cwd/mode.
821        if needs_reset {
822            if let Err(e) = bash_state.init_pty_shell().await {
823                warn!("Failed to reset shell after clear_to_run: {e}");
824            }
825        }
826    }
827
828    // Send command in chunks of 64 characters - matches WCGW Python exactly
829    let scratch_root = bash_state.workspace_root.clone();
830    {
831        let mut bash_guard = bash_state.pty_shell.lock().await;
832
833        let bash = bash_guard.as_mut().ok_or(WinxError::BashStateNotInitialized)?;
834
835        bash.output_buffer.clear();
836        bash.output_truncated = false;
837        // Offload an over-long output's dropped head to a scratch file under the
838        // current workspace so the agent can recover it via ReadFiles.
839        bash.reset_scratch();
840        bash.set_scratch_root(&scratch_root);
841        // Mirror send_command's full reset. This foreground path hand-rolls the
842        // field mutation (it chunks the send for WCGW parity) and used to drop
843        // these two: a stale exit code or dedup hash would then leak into the
844        // next status_check — wrong `exit code`, or a false "no new output".
845        bash.last_exit_code = None;
846        bash.last_returned_hash = None;
847        // Send in chunks - matches WCGW Python: for i in range(0, len(command), 64)
848        send_utf8_in_byte_chunks(bash, command, COMMAND_CHUNK_SIZE)?;
849
850        // Send linesep to execute - matches WCGW Python bash_state.send(bash_state.linesep, ...)
851        bash.send_special_key("Enter").map_err(|e| {
852            WinxError::CommandExecutionError(format!("Failed to send newline: {e}"))
853        })?;
854
855        bash.last_command = command.to_string();
856        bash.command_running = true;
857    }
858
859    // Wait for output with WCGW-style patience handling
860    let shell_arc = bash_state.pty_shell.clone();
861    wait_for_output(bash_state, &shell_arc, timeout_s, false, None, false).await
862}
863
864/// Wait for command output with WCGW-style patience handling - matches WCGW Python expect/wait logic.
865///
866/// Non-blocking drain of queued shell output under the lock; returns whether the
867/// command has completed. The lock is released before returning so the caller can
868/// `await` a poll interval without pinning the executor — unlike the old
869/// `read_output`, which slept (blocking) inside this lock.
870async fn poll_shell(shell_arc: &SharedPtyShell) -> bool {
871    let mut guard = shell_arc.lock().await;
872    match guard.as_mut() {
873        Some(bash) => bash.poll_output_nonblocking(),
874        None => true,
875    }
876}
877
878/// Snapshot the shell's accumulated output buffer in one lock acquisition.
879async fn snapshot_shell(shell_arc: &SharedPtyShell) -> String {
880    let mut guard = shell_arc.lock().await;
881    guard.as_mut().map_or_else(String::new, |bash| bash.output_snapshot())
882}
883
884/// Poll-drain the shell until its prompt returns or `budget_secs` elapses; returns
885/// whether the prompt was seen (i.e. the shell is idle). The lock is released
886/// between polls and the wait is awaited, so the executor is never blocked.
887async fn drain_until_prompt(shell_arc: &SharedPtyShell, budget_secs: f64) -> bool {
888    let start = Instant::now();
889    loop {
890        if poll_shell(shell_arc).await {
891            return true;
892        }
893        if start.elapsed().as_secs_f64() >= budget_secs {
894            return false;
895        }
896        sleep(Duration::from_millis(POLL_INTERVAL_MS)).await;
897    }
898}
899
900/// Async replacement for `PtyShell::clear_to_run`: drain leftover output, and if
901/// the shell still looks busy, send Ctrl-C and re-drain — returning whether the
902/// shell reached an idle prompt. The old sync method ran `read_output` (a blocking
903/// `thread::sleep` loop, up to `DEFAULT_TIMEOUT` seconds) WHILE the caller held the
904/// tokio mutex, pinning the worker on every foreground command. This holds the
905/// lock only for the instantaneous poll/interrupt, never across a wait.
906async fn clear_to_run_async(shell_arc: &SharedPtyShell, max_wait_secs: f64) -> bool {
907    // Phase 1: a quick drain — return the moment the prompt is already back.
908    if drain_until_prompt(shell_arc, max_wait_secs.min(0.5)).await {
909        return true;
910    }
911    // Still busy: interrupt (lock held only for the send), then re-drain.
912    {
913        let mut guard = shell_arc.lock().await;
914        if let Some(bash) = guard.as_mut() {
915            if let Err(e) = bash.send_interrupt() {
916                warn!("clear_to_run: failed to send Ctrl-C: {e}");
917            }
918        }
919    }
920    drain_until_prompt(shell_arc, max_wait_secs).await
921}
922
923/// `shell_arc` selects which shell to read from (main shell or a bg shell handle).
924async fn wait_for_output(
925    bash_state: &mut BashState,
926    shell_arc: &SharedPtyShell,
927    timeout_s: f64,
928    is_bg: bool,
929    bg_id: Option<&str>,
930    is_status_check: bool,
931) -> Result<String> {
932    let start = Instant::now();
933    let wait = timeout_s.min(TIMEOUT_WHILE_OUTPUT);
934    let mut last_pending_output = String::new();
935    let mut complete = false;
936
937    // Adaptive polling instead of a blind sleep. wcgw sleeps the full `wait`
938    // budget before reading even once, so a `pwd` that finishes in 10ms still
939    // costs ~5s. Instead we read in short slices and return the moment the
940    // prompt comes back (`read_output` already exits early on prompt + drain),
941    // dropping fast-command latency from seconds to ~100ms. Long-running
942    // commands still consume the whole budget, since we loop until `complete`
943    // or `wait` elapses — identical upper-bound behavior, far snappier floor.
944    // Drain non-blocking, release the lock, then `await` the poll interval. The
945    // old `read_output(slice)` slept up to ~0.5s of blocking `thread::sleep` WHILE
946    // holding this tokio mutex — pinning the worker thread (starving every other
947    // task on it) and the shell lock the whole time. poll + `await` frees both.
948    let mut output = String::new();
949    loop {
950        if start.elapsed().as_secs_f64() >= wait {
951            break;
952        }
953        complete = poll_shell(shell_arc).await;
954        if complete {
955            break;
956        }
957        sleep(Duration::from_millis(POLL_INTERVAL_MS)).await;
958    }
959    // Post-prompt grace drain (awaited, no lock held), then one buffer snapshot —
960    // the old read_output cloned the whole buffer on every slice (performance-2).
961    if complete {
962        sleep(Duration::from_millis(POST_PROMPT_DRAIN_MS)).await;
963        poll_shell(shell_arc).await;
964    }
965    output = snapshot_shell(shell_arc).await;
966
967    // If not complete and this is a status check, use WCGW-style patience waiting.
968    //
969    // Treat `timeout_s` (== caller's `wait_for_seconds`, capped at
970    // `TIMEOUT_WHILE_OUTPUT`) as the hard upper bound on the TOTAL wall-clock
971    // spent inside this call. wcgw computes `remaining = TIMEOUT_WHILE_OUTPUT
972    // - wait`, which makes a 2-second `wait_for_seconds` block for almost 20s
973    // on a TUI that keeps emitting spinner frames. We diverge from wcgw here
974    // because driving agents expect their wait budget to be respected.
975    if !complete && is_status_check {
976        let budget_secs = timeout_s.min(TIMEOUT_WHILE_OUTPUT);
977        let iter_wait_secs = 0.5_f64;
978        let mut patience = OUTPUT_WAIT_PATIENCE;
979
980        let incremental = wcgw_incremental_text(&output, &last_pending_output);
981        if incremental.is_empty() {
982            patience -= 1;
983        }
984
985        let mut last_incremental = incremental;
986
987        while start.elapsed().as_secs_f64() < budget_secs && patience > 0 {
988            let remaining = (budget_secs - start.elapsed().as_secs_f64()).max(0.0);
989            if remaining < 0.1 {
990                break;
991            }
992            sleep(Duration::from_secs_f64(iter_wait_secs.min(remaining))).await;
993
994            // The patience `sleep(iter_wait_secs)` above already elapsed, so the
995            // last half-second of output is queued — drain it non-blocking (was
996            // read_output(0.5) holding the lock across its own internal sleep).
997            let done = poll_shell(shell_arc).await;
998            let new_output = snapshot_shell(shell_arc).await;
999
1000            if done {
1001                complete = true;
1002                output = new_output;
1003                break;
1004            }
1005
1006            // Check if output changed - matches WCGW Python patience logic
1007            let new_incremental = wcgw_incremental_text(&new_output, &last_pending_output);
1008            if new_incremental == last_incremental {
1009                patience -= 1;
1010            } else {
1011                patience = OUTPUT_WAIT_PATIENCE; // Reset patience on new output
1012            }
1013            last_incremental = new_incremental;
1014
1015            output = new_output;
1016        }
1017
1018        if !complete {
1019            // Update pending output - matches WCGW Python bash_state.set_pending(text)
1020            last_pending_output = output.clone();
1021        }
1022    }
1023
1024    if complete {
1025        if let Some(cwd) = extract_prompt_cwd(&output) {
1026            bash_state.cwd = cwd;
1027        }
1028    }
1029
1030    // Process output through terminal emulation - matches WCGW Python _incremental_text
1031    let rendered = wcgw_incremental_text(&output, &last_pending_output);
1032
1033    // Conscious compression: collapse mechanical repetition (identical line runs,
1034    // blank-line blocks) before truncating, to save tokens without dropping any
1035    // unique context. Falls back to the raw text when nothing is safe to collapse.
1036    let rendered = {
1037        let before_lines = rendered.lines().count();
1038        match crate::utils::output_compress::compress_output(&rendered) {
1039            Some(compressed) => {
1040                debug!(
1041                    from_lines = before_lines,
1042                    to_lines = compressed.lines().count(),
1043                    "winx collapsed mechanical repetition in shell output"
1044                );
1045                compressed
1046            }
1047            None => rendered,
1048        }
1049    };
1050
1051    // Truncate if needed - matches WCGW Python token truncation
1052    let rendered = truncate_to_token_budget(&rendered, MAX_OUTPUT_TOKENS).into_owned();
1053
1054    // Calculate running duration for status
1055    let running_for =
1056        if complete { None } else { Some(format!("{} seconds", start.elapsed().as_secs())) };
1057
1058    // Surface the just-finished command's exit code (parsed from the prompt
1059    // marker) so the agent sees failure without grepping stderr.
1060    // Exit code (parsed from the prompt) plus a pointer to any offloaded output
1061    // scratch file, read in one lock acquisition.
1062    let (exit_code, scratch_pointer) = read_completion_extras(shell_arc, complete).await;
1063
1064    // Add status - matches WCGW Python get_status
1065    let status = get_status(bash_state, is_bg, bg_id, !complete, running_for.as_deref(), exit_code);
1066    Ok(format!("{rendered}{status}{scratch_pointer}"))
1067}
1068
1069/// Pull the just-finished command's exit code and, if its output overflowed and
1070/// the dropped head was offloaded, a pointer message to the scratch file - in a
1071/// single lock acquisition so callers don't lock the shell twice.
1072async fn read_completion_extras(
1073    shell_arc: &SharedPtyShell,
1074    complete: bool,
1075) -> (Option<i32>, String) {
1076    let guard = shell_arc.lock().await;
1077    let Some(shell) = guard.as_ref() else {
1078        return (None, String::new());
1079    };
1080    let exit_code = if complete { shell.last_exit_code } else { None };
1081    let pointer = match (shell.output_truncated, shell.scratch_path()) {
1082        (true, Some(path)) => format!(
1083            "\n\n---\n[Output was truncated to fit context. The earlier (dropped) output was \
1084             saved to:\n{}\nRead it with ReadFiles or grep it via BashCommand.]\n---",
1085            path.display()
1086        ),
1087        _ => String::new(),
1088    };
1089    (exit_code, pointer)
1090}
1091
1092/// Render the final cached output of an exited background shell.
1093///
1094/// `status_check` is allowed to "consume" the tombstone and return the trailing
1095/// output exactly once. Send-style actions (`send_text`, `send_specials`,
1096/// `send_ascii`) cannot interact with a dead shell, so we return an explicit
1097/// error that still includes the captured output so the agent can recover state.
1098fn finalize_tombstone(
1099    cwd: &Path,
1100    id: &str,
1101    tombstone: ExitedShellInfo,
1102    action: &BashCommandAction,
1103) -> Result<String> {
1104    let ExitedShellInfo { last_command, final_output, .. } = tombstone;
1105    match action {
1106        // A dead shell's turn is over: Screen/WaitForTurn hand back the final
1107        // captured output as the snapshot, exactly like a status check.
1108        BashCommandAction::StatusCheck { .. }
1109        | BashCommandAction::Screen { .. }
1110        | BashCommandAction::WaitForTurn { .. } => {
1111            let rendered = wcgw_incremental_text(&final_output, "");
1112            let rendered = truncate_to_token_budget(&rendered, MAX_OUTPUT_TOKENS).into_owned();
1113            // Build a compact status block matching `get_status` for a finished bg shell.
1114            let mut status = "\n\n---\n\n".to_string();
1115            let _ = writeln!(status, "bg_command_id = {id}");
1116            status.push_str("status = process exited\n");
1117            let _ = writeln!(status, "cwd = {}", cwd.display());
1118            Ok(format!("{rendered}{}", status.trim_end()))
1119        }
1120        BashCommandAction::SendText { .. }
1121        | BashCommandAction::SendSpecials { .. }
1122        | BashCommandAction::SendAscii { .. } => Err(WinxError::CommandExecutionError(format!(
1123            "Background shell {id} already exited (last command: {last_command}).\nFinal captured output:\n{final_output}"
1124        ))),
1125        BashCommandAction::Command { .. } => {
1126            // We only enter `finalize_tombstone` from the bg routing path, which
1127            // never matches Command. Treat this as a programmer error.
1128            unreachable!("finalize_tombstone called for non-bg action")
1129        }
1130    }
1131}
1132
1133/// Execute a status check - matches WCGW Python's `StatusCheck` handling.
1134///
1135/// New behavior (v0.2.308):
1136/// - Deduplicates against the last response by fingerprint; when nothing
1137///   changed and `verbose=false`, returns a compact "no new output" payload
1138///   instead of resending the same screen.
1139/// - Optional `scrollback_lines` pulls bounded history from the `PtyShell`
1140///   ringbuffer so agents can reorient after a long pause.
1141async fn execute_status_check(
1142    bash_state: &mut BashState,
1143    bg_shell: Option<SharedPtyShell>,
1144    is_bg: bool,
1145    bg_id: Option<&str>,
1146    timeout_s: f64,
1147    scrollback_lines: Option<usize>,
1148    verbose: bool,
1149) -> Result<String> {
1150    debug!("Processing StatusCheck action (verbose={verbose}, scrollback={scrollback_lines:?})");
1151
1152    // Pick the shell we're going to inspect: bg shell when bg_command_id was provided,
1153    // otherwise fall back to the main interactive shell.
1154    let shell_arc = bg_shell.unwrap_or_else(|| bash_state.pty_shell.clone());
1155
1156    // Check if there's a running command - matches WCGW Python state check
1157    let is_running = {
1158        let guard = shell_arc.lock().await;
1159        if let Some(ref bash) = *guard {
1160            bash.command_running
1161        } else {
1162            false
1163        }
1164    };
1165
1166    // If no command running and not background, return error - matches WCGW Python
1167    if !is_running && !is_bg {
1168        let mut manager = lock_bg_manager();
1169        let error = format!(
1170            "No command is currently running, so there's nothing to check. The previous \
1171             command already finished and its output was returned when it completed. Start a \
1172             new command, or pass a bg_command_id if you launched one in the background.\n{}",
1173            manager.get_running_info()
1174        );
1175        return Err(WinxError::CommandExecutionError(error));
1176    }
1177
1178    // Read output with patience handling - this IS a status check
1179    let response = wait_for_output(bash_state, &shell_arc, timeout_s, is_bg, bg_id, true).await?;
1180
1181    // Inter-call dedup: hash only the response *body* (the chunk before the
1182    // `\n\n---\n` status footer). The footer contains a live "running for"
1183    // counter that would otherwise defeat the comparison.
1184    let body = response.split("\n\n---\n").next().unwrap_or(&response);
1185    if !verbose && scrollback_lines.is_none() {
1186        let mut guard = shell_arc.lock().await;
1187        if let Some(bash) = guard.as_mut() {
1188            let fingerprint = PtyShell::fingerprint(body);
1189            if Some(fingerprint) == bash.last_returned_hash {
1190                let status = get_status(bash_state, is_bg, bg_id, is_running, None, None);
1191                return Ok(format!("no new output since last check{status}"));
1192            }
1193            bash.last_returned_hash = Some(fingerprint);
1194        }
1195    } else if !verbose {
1196        // Still record the hash so subsequent non-scrollback calls can dedup.
1197        let mut guard = shell_arc.lock().await;
1198        if let Some(bash) = guard.as_mut() {
1199            bash.last_returned_hash = Some(PtyShell::fingerprint(body));
1200        }
1201    }
1202
1203    // Optional scrollback prefix — only ever pulled when the caller asks for it.
1204    if let Some(lines) = scrollback_lines {
1205        if lines > 0 {
1206            let scrollback = {
1207                let guard = shell_arc.lock().await;
1208                guard.as_ref().map(|s| s.collect_scrollback(lines)).unwrap_or_default()
1209            };
1210            if !scrollback.is_empty() {
1211                let count = scrollback.lines().count();
1212                return Ok(format!(
1213                    "--- scrollback ({count} lines) ---\n{scrollback}\n--- latest ---\n{response}"
1214                ));
1215            }
1216        }
1217    }
1218
1219    Ok(response)
1220}
1221
1222/// Execute `Screen` — a stable, point-in-time snapshot of a shell's live
1223/// terminal screen (consolidated grid, ANSI stripped). No waiting, no dedup;
1224/// the foundation for reading an interactive TUI's current frame.
1225async fn execute_screen(
1226    bash_state: &BashState,
1227    bg_shell: Option<SharedPtyShell>,
1228    is_bg: bool,
1229    bg_id: Option<&str>,
1230    lines: Option<usize>,
1231    diff: bool,
1232) -> Result<String> {
1233    let shell_arc = bg_shell.unwrap_or_else(|| bash_state.pty_shell.clone());
1234    let max_lines = lines.unwrap_or(0);
1235
1236    if diff {
1237        let (update, is_running, in_alt, cursor) = {
1238            let guard = shell_arc.lock().await;
1239            match guard.as_ref() {
1240                Some(bash) => (
1241                    bash.live_snapshot_diff(max_lines, SCREEN_DIFF_THRESHOLD),
1242                    bash.command_running,
1243                    bash.live_in_alt_screen(),
1244                    bash.live_cursor_position(),
1245                ),
1246                None => (ScreenUpdate::Full(Vec::new()), false, false, (0, 0)),
1247            }
1248        };
1249        let (crow, ccol) = cursor;
1250        let alt = if in_alt { " [alt-screen]" } else { "" };
1251        let status = get_status(bash_state, is_bg, bg_id, is_running, None, None);
1252        let body = match update {
1253            ScreenUpdate::Unchanged => "(no change since last screen)".to_string(),
1254            ScreenUpdate::Diff(changed) => {
1255                let mut out = String::from("(changed lines only)\n");
1256                for (row, content) in changed {
1257                    let _ = writeln!(out, "{row:>4}: {content}");
1258                }
1259                out
1260            }
1261            ScreenUpdate::Full(snap) => {
1262                let joined = snap.join("\n");
1263                if joined.trim().is_empty() {
1264                    "(screen is empty)".to_string()
1265                } else {
1266                    truncate_to_token_budget(&joined, MAX_OUTPUT_TOKENS).into_owned()
1267                }
1268            }
1269        };
1270        return Ok(format!(
1271            "--- live screen{alt} [cursor row={crow} col={ccol}] (diff) ---\n{body}{status}"
1272        ));
1273    }
1274
1275    let (snapshot, is_running, in_alt, cursor) = {
1276        let guard = shell_arc.lock().await;
1277        match guard.as_ref() {
1278            Some(bash) => (
1279                bash.live_snapshot(max_lines),
1280                bash.command_running,
1281                bash.live_in_alt_screen(),
1282                bash.live_cursor_position(),
1283            ),
1284            None => (Vec::new(), false, false, (0, 0)),
1285        }
1286    };
1287
1288    let joined = snapshot.join("\n");
1289    let body = if joined.trim().is_empty() {
1290        "(screen is empty)".to_string()
1291    } else {
1292        truncate_to_token_budget(&joined, MAX_OUTPUT_TOKENS).into_owned()
1293    };
1294    let alt = if in_alt { " [alt-screen]" } else { "" };
1295    let (crow, ccol) = cursor;
1296    let status = get_status(bash_state, is_bg, bg_id, is_running, None, None);
1297    Ok(format!("--- live screen{alt} [cursor row={crow} col={ccol}] ---\n{body}{status}"))
1298}
1299
1300/// Execute `WaitForTurn` — block until an interactive TUI finishes its turn.
1301///
1302/// Polls the live screen, combining a per-app recognizer (claude/codex/auto)
1303/// with a generic quiescence window: the turn is "ready" when the recognizer
1304/// reports awaiting-input/approval (after a short settle) or, for an unknown
1305/// TUI, when the screen simply stops changing for `quiet`. Returns the stable
1306/// snapshot plus the detected state.
1307#[allow(clippy::too_many_arguments)]
1308async fn execute_wait_for_turn(
1309    bash_state: &BashState,
1310    bg_shell: Option<SharedPtyShell>,
1311    is_bg: bool,
1312    bg_id: Option<&str>,
1313    recognizer_hint: Option<&str>,
1314    quiet_ms: Option<u64>,
1315    timeout_seconds: Option<f32>,
1316    lines: Option<usize>,
1317) -> Result<String> {
1318    use crate::state::turn::{recognizer_for, TurnState};
1319
1320    let shell_arc = bg_shell.unwrap_or_else(|| bash_state.pty_shell.clone());
1321    let recognizer = recognizer_for(recognizer_hint.unwrap_or("auto"));
1322    let quiet = Duration::from_millis(quiet_ms.unwrap_or(600).clamp(50, 10_000));
1323    let settle = quiet.min(Duration::from_millis(300));
1324    let hard_cap =
1325        Duration::from_secs_f64(f64::from(timeout_seconds.unwrap_or(30.0)).clamp(0.5, 600.0));
1326    let max_lines = lines.unwrap_or(0);
1327    let poll = Duration::from_millis(120);
1328    // Grace period so a freshly-prompted app has time to react before we'd
1329    // otherwise mistake the *pre-input* idle screen for a finished turn.
1330    let warmup = Duration::from_millis(2500);
1331
1332    let start = Instant::now();
1333    let mut last_hash: Option<u64> = None;
1334    let mut initial_hash: Option<u64> = None;
1335    let mut stable_since = Instant::now();
1336    let mut seen_busy = false;
1337
1338    loop {
1339        let (snapshot, in_alt, alive, running) = {
1340            let mut guard = shell_arc.lock().await;
1341            match guard.as_mut() {
1342                Some(bash) => (
1343                    bash.live_snapshot(max_lines),
1344                    bash.live_in_alt_screen(),
1345                    bash.is_alive(),
1346                    bash.command_running,
1347                ),
1348                None => (Vec::new(), false, false, false),
1349            }
1350        };
1351
1352        let hash = PtyShell::fingerprint(&snapshot.join("\n"));
1353        if initial_hash.is_none() {
1354            initial_hash = Some(hash);
1355        }
1356        if Some(hash) != last_hash {
1357            last_hash = Some(hash);
1358            stable_since = Instant::now();
1359        }
1360
1361        let state = recognizer.detect(&snapshot);
1362        if state == TurnState::Busy {
1363            seen_busy = true;
1364        }
1365        let stable_for = stable_since.elapsed();
1366        // Don't call it "done" until something actually happened since we began
1367        // waiting: the app went Busy, the screen changed from the first frame we
1368        // saw, or the warmup elapsed (instant reply / nothing to do).
1369        let activity = seen_busy || Some(hash) != initial_hash || start.elapsed() >= warmup;
1370        let ready = match state {
1371            TurnState::Busy => false,
1372            // A short settle is enough once we saw it go Busy; otherwise wait the
1373            // full quiet window so a slow first token isn't read as "done".
1374            TurnState::AwaitingInput | TurnState::AwaitingApproval => {
1375                activity && stable_for >= if seen_busy { settle } else { quiet }
1376            }
1377            TurnState::Unknown => activity && stable_for >= quiet,
1378        };
1379
1380        let timed_out = start.elapsed() >= hard_cap;
1381        if ready || !alive || timed_out {
1382            let reason = if !alive {
1383                "exited"
1384            } else if ready {
1385                "ready"
1386            } else {
1387                "timeout"
1388            };
1389            let joined = snapshot.join("\n");
1390            let body = if joined.trim().is_empty() {
1391                "(screen is empty)".to_string()
1392            } else {
1393                truncate_to_token_budget(&joined, MAX_OUTPUT_TOKENS).into_owned()
1394            };
1395            let alt = if in_alt { " [alt-screen]" } else { "" };
1396            let header = format!(
1397                "--- turn: {} ({}, recognizer={}, waited {:.1}s){} ---",
1398                state.as_str(),
1399                reason,
1400                recognizer.name(),
1401                start.elapsed().as_secs_f64(),
1402                alt
1403            );
1404            let status = get_status(bash_state, is_bg, bg_id, running, None, None);
1405            return Ok(format!("{header}\n{body}{status}"));
1406        }
1407
1408        tokio::time::sleep(poll).await;
1409    }
1410}
1411
1412/// Execute `send_text` - matches WCGW Python's `SendText` handling
1413async fn execute_send_text(
1414    bash_state: &mut BashState,
1415    text: &str,
1416    submit: bool,
1417    bg_shell: Option<SharedPtyShell>,
1418    is_bg: bool,
1419    bg_id: Option<&str>,
1420    timeout_s: f64,
1421) -> Result<String> {
1422    debug!("Processing SendText action: {text:?} (submit={submit})");
1423
1424    // Validate - matches WCGW Python
1425    if text.is_empty() {
1426        return Err(WinxError::CommandExecutionError(
1427            "Failure: send_text cannot be empty".to_string(),
1428        ));
1429    }
1430
1431    // Get the target shell
1432    let shell_arc = bg_shell.unwrap_or_else(|| bash_state.pty_shell.clone());
1433
1434    // Send text in chunks of 128 characters - matches WCGW Python exactly
1435    {
1436        let mut guard = shell_arc.lock().await;
1437
1438        let bash = guard.as_mut().ok_or(WinxError::BashStateNotInitialized)?;
1439
1440        // Send in chunks - matches WCGW Python: for i in range(0, len(command_data.send_text), 128)
1441        send_utf8_in_byte_chunks(bash, text, TEXT_CHUNK_SIZE)?;
1442    }
1443
1444    // Only submit when explicitly asked. The Enter goes as a separate, delayed
1445    // write so Ink TUIs (Claude Code) don't swallow a CR glued to the text — a
1446    // bare CR there is otherwise treated as a soft newline and never submits.
1447    if submit {
1448        submit_enter(&shell_arc).await?;
1449    }
1450
1451    // Wait for output
1452    wait_for_output(bash_state, &shell_arc, timeout_s, is_bg, bg_id, false).await
1453}
1454
1455/// Execute `send_specials` - matches WCGW Python's `SendSpecials` handling exactly
1456async fn execute_send_specials(
1457    bash_state: &mut BashState,
1458    keys: &[SpecialKey],
1459    submit: bool,
1460    bg_shell: Option<SharedPtyShell>,
1461    is_bg: bool,
1462    bg_id: Option<&str>,
1463    timeout_s: f64,
1464) -> Result<String> {
1465    debug!("Processing SendSpecials action: {keys:?} (submit={submit})");
1466
1467    // Validate - matches WCGW Python
1468    if keys.is_empty() {
1469        return Err(WinxError::CommandExecutionError(
1470            "Failure: send_specials cannot be empty".to_string(),
1471        ));
1472    }
1473
1474    let shell_arc = bg_shell.unwrap_or_else(|| bash_state.pty_shell.clone());
1475    let mut is_interrupt = false;
1476
1477    {
1478        let mut guard = shell_arc.lock().await;
1479
1480        let bash = guard.as_mut().ok_or(WinxError::BashStateNotInitialized)?;
1481
1482        // Send each special key - matches WCGW Python exactly
1483        for key in keys {
1484            match key {
1485                SpecialKey::KeyUp => {
1486                    // matches WCGW Python: bash_state.send("\033[A", ...)
1487                    bash.send_special_key("KeyUp").map_err(|e| {
1488                        WinxError::CommandExecutionError(format!("Failed to send KeyUp: {e}"))
1489                    })?;
1490                }
1491                SpecialKey::KeyDown => {
1492                    // matches WCGW Python: bash_state.send("\033[B", ...)
1493                    bash.send_special_key("KeyDown").map_err(|e| {
1494                        WinxError::CommandExecutionError(format!("Failed to send KeyDown: {e}"))
1495                    })?;
1496                }
1497                SpecialKey::KeyLeft => {
1498                    // matches WCGW Python: bash_state.send("\033[D", ...)
1499                    bash.send_special_key("KeyLeft").map_err(|e| {
1500                        WinxError::CommandExecutionError(format!("Failed to send KeyLeft: {e}"))
1501                    })?;
1502                }
1503                SpecialKey::KeyRight => {
1504                    // matches WCGW Python: bash_state.send("\033[C", ...)
1505                    bash.send_special_key("KeyRight").map_err(|e| {
1506                        WinxError::CommandExecutionError(format!("Failed to send KeyRight: {e}"))
1507                    })?;
1508                }
1509                SpecialKey::Enter => {
1510                    // matches WCGW Python: bash_state.send("\x0d", ...) - carriage return
1511                    bash.send_special_key("Enter").map_err(|e| {
1512                        WinxError::CommandExecutionError(format!("Failed to send Enter: {e}"))
1513                    })?;
1514                }
1515                SpecialKey::CtrlC => {
1516                    // matches WCGW Python: bash_state.sendintr()
1517                    bash.send_interrupt().map_err(|e| {
1518                        WinxError::CommandExecutionError(format!("Failed to send interrupt: {e}"))
1519                    })?;
1520                    is_interrupt = true;
1521                }
1522                SpecialKey::CtrlD => {
1523                    // matches WCGW Python: bash_state.sendintr() - same as Ctrl+C in WCGW
1524                    bash.send_eof().map_err(|e| {
1525                        WinxError::CommandExecutionError(format!("Failed to send Ctrl+D: {e}"))
1526                    })?;
1527                    is_interrupt = true;
1528                }
1529                SpecialKey::CtrlZ => {
1530                    // Ctrl+Z = SIGTSTP (suspend) - ASCII 0x1a
1531                    bash.send_suspend().map_err(|e| {
1532                        WinxError::CommandExecutionError(format!("Failed to send Ctrl+Z: {e}"))
1533                    })?;
1534                }
1535            }
1536        }
1537    }
1538
1539    // Submit as a separate, slightly-delayed write (see `submit_enter`) so an
1540    // Ink TUI doesn't drop the CR.
1541    if submit {
1542        submit_enter(&shell_arc).await?;
1543    }
1544
1545    // NOTE: wcgw treats a bare Enter as a status check and applies its
1546    // patience loop. We deliberately diverge: for a driving agent (e.g.,
1547    // pushing Enter to submit text in a TUI) the patience loop swallows the
1548    // immediate response. Callers that want patience semantics should use the
1549    // explicit `status_check` action instead.
1550
1551    // Wait for output
1552    let mut output =
1553        wait_for_output(bash_state, &shell_arc, timeout_s, is_bg, bg_id, false).await?;
1554
1555    // Add interrupt failure message if still running - matches WCGW Python exactly
1556    if is_interrupt && output.contains("status = still running") {
1557        output.push_str("\n---\n----\nFailure interrupting.\nYou may want to try Ctrl-c again or program specific exit interactive commands.\n");
1558    }
1559
1560    Ok(output)
1561}
1562
1563/// Execute `send_ascii` - matches WCGW Python's `SendAscii` handling
1564async fn execute_send_ascii(
1565    bash_state: &mut BashState,
1566    ascii_codes: &[u8],
1567    submit: bool,
1568    bg_shell: Option<SharedPtyShell>,
1569    is_bg: bool,
1570    bg_id: Option<&str>,
1571    timeout_s: f64,
1572) -> Result<String> {
1573    debug!("Processing SendAscii action: {ascii_codes:?} (submit={submit})");
1574
1575    // Validate - matches WCGW Python
1576    if ascii_codes.is_empty() {
1577        return Err(WinxError::CommandExecutionError(
1578            "Failure: send_ascii cannot be empty".to_string(),
1579        ));
1580    }
1581
1582    let shell_arc = bg_shell.unwrap_or_else(|| bash_state.pty_shell.clone());
1583    let mut is_interrupt = false;
1584
1585    {
1586        let mut guard = shell_arc.lock().await;
1587
1588        let bash = guard.as_mut().ok_or(WinxError::BashStateNotInitialized)?;
1589
1590        // Send each ASCII code - matches WCGW Python
1591        for &code in ascii_codes {
1592            // matches WCGW Python: bash_state.send(chr(ascii_char), ...)
1593            bash.send_bytes(&[code]).map_err(|e| {
1594                WinxError::CommandExecutionError(format!("Failed to write ASCII code: {e}"))
1595            })?;
1596
1597            // Check for interrupt - matches WCGW Python: if ascii_char == 3: is_interrupt = True
1598            if code == 3 {
1599                is_interrupt = true;
1600            }
1601        }
1602    }
1603
1604    // Submit as a separate, slightly-delayed write (see `submit_enter`) so an
1605    // Ink TUI doesn't drop the CR.
1606    if submit {
1607        submit_enter(&shell_arc).await?;
1608    }
1609
1610    // Same divergence from wcgw as in `execute_send_specials`: send_ascii [10]
1611    // or [13] is treated as a direct write, not a status check. Callers that
1612    // need patience-aware reads should use `status_check`.
1613
1614    // Wait for output
1615    let mut output =
1616        wait_for_output(bash_state, &shell_arc, timeout_s, is_bg, bg_id, false).await?;
1617
1618    // Add interrupt failure message if still running - matches WCGW Python
1619    if is_interrupt && output.contains("status = still running") {
1620        output.push_str("\n---\n----\nFailure interrupting.\nYou may want to try Ctrl-c again or program specific exit interactive commands.\n");
1621    }
1622
1623    Ok(output)
1624}
1625
1626/// Execute command in background - matches WCGW Python's `is_background` handling
1627async fn execute_in_background(
1628    bash_state: &mut BashState,
1629    command: &str,
1630    timeout_s: f64,
1631) -> Result<String> {
1632    debug!("Executing command in background: {}", command);
1633
1634    // Start a new background shell - matches WCGW Python bash_state.start_new_bg_shell
1635    let restricted_mode =
1636        matches!(bash_state.bash_command_mode.bash_mode, crate::types::BashMode::RestrictedMode);
1637
1638    // Build the shell OFF the tokio worker AND outside the manager lock:
1639    // PtyShell::new forks+execs and blocks ~300ms on prompt init. The old
1640    // start_new_shell did all of that under the std::Mutex on the executor thread.
1641    let bg_id = {
1642        let cwd = bash_state.cwd.clone();
1643        let shell = tokio::task::spawn_blocking(move || PtyShell::new(&cwd, restricted_mode))
1644            .await
1645            .map_err(|e| {
1646                WinxError::CommandExecutionError(format!("bg shell init task failed: {e}"))
1647            })?
1648            .map_err(|e| {
1649                WinxError::CommandExecutionError(format!("Failed to start background shell: {e}"))
1650            })?;
1651        lock_bg_manager().register_shell(shell)
1652    };
1653
1654    // Get the shell
1655    let shell_arc = {
1656        let manager = lock_bg_manager();
1657        manager.get_shell(&bg_id).ok_or_else(|| {
1658            WinxError::CommandExecutionError("Failed to get background shell".to_string())
1659        })?
1660    };
1661
1662    // Send command via the same PTY path used by foreground execute_command.
1663    let scratch_root = bash_state.workspace_root.clone();
1664    {
1665        let mut guard = shell_arc.lock().await;
1666        let bash = guard.as_mut().ok_or(WinxError::BashStateNotInitialized)?;
1667        // Offload an over-long bg output's dropped head too (send_command resets
1668        // the per-command scratch state; this points it at the workspace).
1669        bash.set_scratch_root(&scratch_root);
1670        bash.send_command(command).map_err(|e| {
1671            WinxError::CommandExecutionError(format!("Failed to send bg command: {e}"))
1672        })?;
1673    }
1674    debug!("bg[{}]: send_command returned, replying with bg_command_id", bg_id);
1675
1676    let _ = timeout_s;
1677    let _ = shell_arc;
1678    Ok(get_status(bash_state, true, Some(&bg_id), true, None, None))
1679}
1680
1681#[cfg(test)]
1682mod tests {
1683    use super::strip_tail_pipe_impl;
1684
1685    #[test]
1686    fn strips_trailing_tail_by_default() {
1687        assert_eq!(strip_tail_pipe_impl("seq 1 5 | tail -2", false), "seq 1 5");
1688        assert_eq!(strip_tail_pipe_impl("cat log | tail -n 20", false), "cat log");
1689        assert_eq!(strip_tail_pipe_impl("cat log | tail", false), "cat log");
1690        assert_eq!(strip_tail_pipe_impl("ls -la|tail -5", false), "ls -la");
1691    }
1692
1693    #[test]
1694    fn keeps_command_without_trailing_tail() {
1695        // tail not at the end, or piped further, must be left alone.
1696        assert_eq!(strip_tail_pipe_impl("tail -f log | grep err", false), "tail -f log | grep err");
1697        assert_eq!(strip_tail_pipe_impl("echo hi", false), "echo hi");
1698        assert_eq!(
1699            strip_tail_pipe_impl("cat a | tail -5 | wc -l", false),
1700            "cat a | tail -5 | wc -l"
1701        );
1702    }
1703
1704    #[test]
1705    fn keep_mode_preserves_tail_pipe() {
1706        // WINX_KEEP_TAIL_PIPE behavior: command passes through untouched.
1707        assert_eq!(strip_tail_pipe_impl("seq 1 5 | tail -2", true), "seq 1 5 | tail -2");
1708        assert_eq!(strip_tail_pipe_impl("cat log | tail -n 20", true), "cat log | tail -n 20");
1709    }
1710}