Skip to main content

winx_code_agent/state/
pty.rs

1//! Real PTY implementation using portable-pty
2//!
3//! This module provides a true pseudo-terminal interface for interactive
4//! shell sessions, enabling proper handling of:
5//! - ANSI escape sequences and colors
6//! - Interactive programs (sudo, vim, less, etc.)
7//! - Terminal resize events
8//! - Job control signals (Ctrl+C, Ctrl+Z, etc.)
9
10use crate::utils::executable::{shell_kind_of, ShellKind};
11use anyhow::{anyhow, Context, Result};
12use portable_pty::{native_pty_system, Child, CommandBuilder, MasterPty, PtySize};
13use std::collections::hash_map::DefaultHasher;
14use std::hash::{Hash, Hasher};
15use std::io::{Read, Write};
16use std::path::{Path, PathBuf};
17use std::process::Command;
18use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering};
19use std::sync::mpsc::{self, TryRecvError};
20use std::sync::{Arc, Mutex as StdMutex};
21use std::thread;
22use std::time::{Duration, Instant};
23use tokio::sync::Mutex;
24use tracing::{debug, info, warn};
25
26use crate::state::line_ring::LineRing;
27use crate::state::live_terminal::{LiveTerminal, ScreenUpdate};
28
29/// Default terminal dimensions (columns x rows)
30pub const DEFAULT_COLS: u16 = 200;
31pub const DEFAULT_ROWS: u16 = 50;
32
33/// Maximum output buffer size to prevent memory issues
34const MAX_OUTPUT_SIZE: usize = 1_000_000;
35
36/// Cap on bytes streamed to one command's output-offload scratch file, so a
37/// command emitting gigabytes cannot fill the disk. The head beyond this is
38/// dropped (the agent still gets the first 50 MB plus the live tail).
39const SCRATCH_MAX_BYTES: u64 = 50 * 1024 * 1024;
40
41/// Sleep injected between PTY reads once the current command's output is pure
42/// discard (scratch budget exhausted — only the live tail is still retained).
43/// With 4 KiB reads this caps consumption at roughly 2 MB/s, so a runaway
44/// producer (`head -c 5T /dev/zero | tr '\0' x` was the production incident)
45/// back-pressures against the kernel PTY buffer instead of pinning a core in
46/// the terminal parsers at full stream speed. A real TUI redraw burst
47/// (~40 KiB/frame) still renders at ~50 fps under this cap, so interactive
48/// piloting is unaffected.
49const DISCARD_READ_THROTTLE: Duration = Duration::from_millis(2);
50
51/// How many fully-formed lines to keep in the per-shell ringbuffer. Callers can
52/// ask for at most this many lines of historical context via
53/// `StatusCheck.scrollback_lines`.
54pub const RING_BUFFER_LINES: usize = 2_000;
55
56/// Cap on the unterminated tail held in `line_ring_partial`. Bounds memory when
57/// a program emits megabytes without ever printing a newline (a `\r`-redrawn
58/// progress bar, a binary blob). Generous enough to hold any real terminal line.
59const MAX_PARTIAL_LINE_BYTES: usize = 64 * 1024;
60
61/// WCGW-style prompt pattern for command completion detection
62const WCGW_PROMPT_PATTERN: &str = "◉";
63const WCGW_PROMPT_END: &str = "──➤";
64/// Upper bound on waiting for a freshly spawned shell's first prompt. Linux bash
65/// answers in milliseconds; Git for Windows bash under `ConPTY` can take seconds
66/// on a cold start.
67const PROMPT_BOOTSTRAP_TIMEOUT: Duration = Duration::from_secs(5);
68
69fn attachable_command(restricted_mode: bool) -> (CommandBuilder, Option<String>, ShellKind) {
70    let requested = crate::config::env_text("WINX_ATTACH_TERMINAL")
71        .or_else(|| crate::config::env_text("WINX_USE_SCREEN"))
72        .unwrap_or_default();
73    if requested == "tmux"
74        || requested == "screen"
75        || crate::config::parse_bool(&requested) == Some(true)
76    {
77        let session = format!("winx-{}-{}", std::process::id(), timestamp_millis());
78        if requested == "tmux" && command_available("tmux") {
79            let mut cmd = CommandBuilder::new("tmux");
80            cmd.args(["new-session", "-A", "-s", &session, "bash"]);
81            if restricted_mode {
82                cmd.arg("-r");
83            }
84            return (cmd, Some(format!("tmux attach -t {session}")), ShellKind::Bash);
85        }
86        if command_available("screen") {
87            // Parity with wcgw: ensure a sane ~/.screenrc and reap sessions whose
88            // creating winx process has died before spawning a fresh one.
89            ensure_screenrc();
90            cleanup_orphaned_screens();
91            let mut cmd = CommandBuilder::new("screen");
92            cmd.args(["-q", "-S", &session, "bash"]);
93            if restricted_mode {
94                cmd.arg("-r");
95            }
96            return (cmd, Some(format!("screen -x {session}")), ShellKind::Bash);
97        }
98    }
99
100    let shell = preferred_shell(restricted_mode);
101    // `WINX_SHELL=/bin/zsh` must get the zsh bootstrap too, not only `zsh`.
102    let kind = shell_kind_of(&shell);
103    let mut cmd = CommandBuilder::new(&shell);
104    match kind {
105        // zsh's restricted mode isn't the `-r` flag, so restricted always uses bash -r.
106        ShellKind::Bash if restricted_mode => {
107            cmd.arg("-r");
108        }
109        // The banner would otherwise land in the first command's output; the
110        // profile still runs so the user's PATH and aliases apply.
111        ShellKind::PowerShell => {
112            cmd.arg("-NoLogo");
113        }
114        ShellKind::Bash | ShellKind::Zsh => {}
115    }
116    // Operator-supplied extra shell arguments (`WINX_SHELL_ARGS="-i --login"`):
117    // whitespace-separated, applied to the direct shell path only.
118    if let Some(extra) = crate::config::env_text("WINX_SHELL_ARGS") {
119        for arg in extra.split_whitespace() {
120            cmd.arg(arg);
121        }
122    }
123    (cmd, None, kind)
124}
125
126/// The shell family a new PTY would get right now, from the same selection
127/// the spawner uses. Command policy (single-statement checks, static write
128/// analysis) consults it before a shell exists.
129pub fn configured_shell_kind(restricted_mode: bool) -> ShellKind {
130    shell_kind_of(&preferred_shell(restricted_mode))
131}
132
133/// Shell to spawn directly. Defaults to bash; honors `WINX_SHELL=zsh` when zsh is
134/// on PATH and we're not in restricted mode (zsh's restricted mode differs from
135/// `bash -r`, so restricted falls back to bash). On Windows the Git for Windows
136/// `bash.exe` is resolved to an absolute path so the `ConPTY` child never lands
137/// on the WSL launcher in `System32`.
138/// On Windows the shell must be an absolute Git for Windows `bash.exe`; the
139/// `System32` WSL launcher is never used. If no usable bash is found, fail with
140/// an actionable message instead of an opaque spawn error later.
141#[cfg(windows)]
142fn ensure_windows_shell_available(restricted_mode: bool) -> Result<()> {
143    // An absolute `WINX_SHELL` (honored only outside restricted mode) wins.
144    if !restricted_mode {
145        if let Ok(requested) = std::env::var("WINX_SHELL") {
146            let path = Path::new(&requested);
147            if path.is_absolute() && path.is_file() {
148                return Ok(());
149            }
150        }
151    }
152    if crate::utils::executable::bash_executable().is_some() {
153        return Ok(());
154    }
155    if crate::utils::executable::powershell_executable().is_some() {
156        if restricted_mode {
157            return Err(anyhow!(
158                "restricted mode needs bash -r; install Git for Windows or set WINX_SHELL to an \
159                 absolute bash.exe path (PowerShell has no equivalent restricted mode)"
160            ));
161        }
162        return Ok(());
163    }
164    Err(anyhow!(
165        "no usable shell found: install Git for Windows (the System32 WSL launcher is not \
166         used) or PowerShell 7, or set WINX_SHELL to an absolute bash.exe or pwsh.exe path"
167    ))
168}
169
170fn preferred_shell(restricted_mode: bool) -> String {
171    if !restricted_mode {
172        if let Ok(requested) = std::env::var("WINX_SHELL") {
173            if requested == "zsh" && command_available("zsh") {
174                return "zsh".to_string();
175            }
176            // `pwsh`/`powershell` select PowerShell wherever it is installed;
177            // restricted mode never does, because `bash -r` has no equivalent.
178            if matches!(requested.as_str(), "pwsh" | "powershell") {
179                if let Some(found) = crate::utils::executable::powershell_executable() {
180                    return found.to_string_lossy().into_owned();
181                }
182            }
183            // An absolute path selects that exact shell binary (a specific
184            // bash.exe on Windows, a custom build elsewhere).
185            if Path::new(&requested).is_absolute() && Path::new(&requested).is_file() {
186                return requested;
187            }
188        }
189    }
190    if cfg!(windows) {
191        if let Some(bash) = crate::utils::executable::bash_executable() {
192            return bash.to_string_lossy().into_owned();
193        }
194        // No Git for Windows: PowerShell keeps the native runtime usable
195        // without WSL, outside restricted mode.
196        if !restricted_mode {
197            if let Some(found) = crate::utils::executable::powershell_executable() {
198                return found.to_string_lossy().into_owned();
199            }
200        }
201    }
202    "bash".to_string()
203}
204
205/// One-line PowerShell bootstrap with the same completion contract as the
206/// bash prompt: `◉ <cwd>──➤<nonce>:<code> ` after every command.
207///
208/// `PSReadLine` is unloaded because it redraws the line with cursor movement
209/// that breaks marker detection; `PlainText` rendering keeps ANSI out of
210/// command output on PowerShell 7.2+. The exit code mirrors a POSIX shell:
211/// a native process code when one was set, `1` for a failed cmdlet
212/// (`$?` false), else `0`; `$LASTEXITCODE` is cleared so a later cmdlet
213/// does not inherit a stale native failure. Windows PowerShell 5.1 keeps
214/// `$?` true after a failing native command, which is why the code is read
215/// before `$?` is consulted.
216fn powershell_bootstrap(nonce: &str) -> String {
217    format!(
218        "Remove-Module PSReadLine -ErrorAction SilentlyContinue; \
219         if (Get-Variable PSStyle -ErrorAction SilentlyContinue) {{ $PSStyle.OutputRendering = 'PlainText' }}; \
220         $env:PAGER = 'cat'; $env:GIT_PAGER = 'cat'; $global:LASTEXITCODE = 0; \
221         function global:prompt {{ $ok = $?; $ec = $global:LASTEXITCODE; \
222         $code = if ($ec -is [int] -and $ec -ne 0) {{ $ec }} elseif ($ok) {{ 0 }} else {{ 1 }}; \
223         $global:LASTEXITCODE = 0; \
224         \"\u{25c9} $($ExecutionContext.SessionState.Path.CurrentLocation.ProviderPath)\u{2500}\u{2500}\u{27a4}{nonce}:$code \" }}"
225    )
226}
227
228fn command_available(command: &str) -> bool {
229    crate::utils::executable::is_available(command)
230}
231
232/// Create `~/.screenrc` with a large scrollback if the user has none, matching
233/// wcgw's `check_if_screen_command_available`. Never overwrites an existing file.
234fn ensure_screenrc() {
235    let Some(home) = home::home_dir() else {
236        return;
237    };
238    let screenrc = home.join(".screenrc");
239    if screenrc.exists() {
240        return;
241    }
242    let _ = std::fs::write(
243        &screenrc,
244        "defscrollback 10000\ntermcapinfo xterm* ti@:te@\nstartup_message off\n",
245    );
246}
247
248/// Reap detached `winx-*` screen sessions whose creating process is gone.
249///
250/// The session name embeds the creator PID (`winx-<pid>-<ts>`), so an orphan is
251/// simply a session whose `<pid>` no longer exists — the wcgw equivalent of
252/// detecting `parent_pid == 1`. Best-effort: any failure is silently ignored.
253fn cleanup_orphaned_screens() {
254    let Ok(output) = Command::new("screen").arg("-ls").output() else {
255        return;
256    };
257    // `screen -ls` exits non-zero when sessions exist, so we parse stdout regardless.
258    let listing = String::from_utf8_lossy(&output.stdout);
259    for line in listing.lines() {
260        let Some(session) = line.split_whitespace().next() else {
261            continue;
262        };
263        // session token looks like "<screen_pid>.winx-<creator_pid>-<ts>"
264        let Some((_, name)) = session.split_once('.') else {
265            continue;
266        };
267        if let Some(creator_pid) = winx_creator_pid(name) {
268            if !process_exists(creator_pid) {
269                let _ = Command::new("screen").args(["-S", session, "-X", "quit"]).output();
270            }
271        }
272    }
273}
274
275/// Extract the creator PID from a `winx-<pid>-<ts>` screen session name.
276fn winx_creator_pid(name: &str) -> Option<u32> {
277    name.strip_prefix("winx-")?.split('-').next()?.parse::<u32>().ok()
278}
279
280/// Whether a process with `pid` is currently alive. `kill(pid, 0)` is portable
281/// across supported Unix platforms and sends no signal.
282#[cfg(unix)]
283fn process_exists(pid: u32) -> bool {
284    crate::os::unix::process_exists(pid)
285}
286
287#[cfg(not(unix))]
288fn process_exists(pid: u32) -> bool {
289    crate::os::process_exists(pid)
290}
291
292/// Git for Windows bash reports its cwd in MSYS form (`/c/Users/x`, or
293/// `/cygdrive/c/...` under Cygwin). On Windows, convert it back to the native
294/// `C:\Users\x` spelling so relative file targets and `cd` tracking resolve
295/// against a directory that exists for the rest of Winx.
296pub(crate) fn native_cwd_from_prompt(cwd: &str) -> PathBuf {
297    if cfg!(windows) {
298        if let Some(native) = msys_to_native(cwd) {
299            return native;
300        }
301    }
302    PathBuf::from(cwd)
303}
304
305fn msys_to_native(cwd: &str) -> Option<PathBuf> {
306    let rest = cwd.strip_prefix("/cygdrive").unwrap_or(cwd);
307    let mut parts = rest.strip_prefix('/')?.splitn(2, '/');
308    let drive = parts.next()?;
309    if drive.len() != 1 || !drive.chars().all(|character| character.is_ascii_alphabetic()) {
310        return None;
311    }
312    let tail = parts.next().unwrap_or("");
313    let mut native = format!("{}:\\", drive.to_ascii_uppercase());
314    native.push_str(&tail.replace('/', "\\"));
315    Some(PathBuf::from(native))
316}
317
318fn timestamp_millis() -> u128 {
319    std::time::SystemTime::now()
320        .duration_since(std::time::UNIX_EPOCH)
321        .map_or(0, |duration| duration.as_millis())
322}
323
324/// Background thread that pumps the PTY master into the output channel and the
325/// live emulator. Owns the blocking `read` loop so the async side never blocks.
326fn spawn_pty_reader(
327    mut reader: Box<dyn Read + Send>,
328    output_tx: mpsc::SyncSender<String>,
329    live: Arc<StdMutex<LiveTerminal>>,
330    discard_throttle: Arc<AtomicBool>,
331) {
332    thread::spawn(move || {
333        let mut buf = [0u8; 4096];
334        // Bytes of an incomplete trailing UTF-8 char held back for the next
335        // read. Without this, a multibyte glyph split across a 4096-byte read
336        // boundary would decode to two U+FFFDs — corrupting the output buffer
337        // and the prompt/CWD detection that runs over it.
338        let mut carry: Vec<u8> = Vec::new();
339        loop {
340            match reader.read(&mut buf) {
341                Ok(0) => {
342                    debug!("PTY reader reached EOF");
343                    // EOF - PTY closed. Flush any held bytes lossily.
344                    if !carry.is_empty() {
345                        let _ = output_tx.send(String::from_utf8_lossy(&carry).into_owned());
346                    }
347                    break;
348                }
349                Ok(n) => {
350                    debug!(bytes = n, "PTY reader chunk");
351                    // Tap the raw bytes into the live emulator first (brief
352                    // lock; feed is O(chunk len)). Feeding bytes — not the
353                    // lossy String — keeps the persistent VTE parser exact
354                    // across chunk boundaries. Recover from a poisoned lock
355                    // instead of dropping the feed silently.
356                    {
357                        let mut emu =
358                            live.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
359                        emu.feed(&buf[..n]);
360                    }
361                    // Decode the longest valid prefix; carry an incomplete
362                    // trailing char into the next read.
363                    carry.extend_from_slice(&buf[..n]);
364                    let (chunk, rest) = decode_keep_incomplete(&carry);
365                    carry = rest;
366                    if !chunk.is_empty() && output_tx.send(chunk).is_err() {
367                        // Receiver dropped, exit thread
368                        break;
369                    }
370                    // Once the command's output is pure discard, stop
371                    // consuming at stream speed: the pause fills the kernel
372                    // PTY buffer and blocks the producer instead of burning
373                    // a core parsing bytes that are thrown away.
374                    if discard_throttle.load(AtomicOrdering::Relaxed) {
375                        thread::sleep(DISCARD_READ_THROTTLE);
376                    }
377                }
378                Err(e) => {
379                    debug!("PTY reader thread error: {}", e);
380                    break;
381                }
382            }
383        }
384        debug!("PTY reader thread exiting");
385    });
386}
387
388/// Real PTY-based interactive shell
389///
390/// Uses portable-pty for true pseudo-terminal functionality,
391/// enabling proper handling of interactive programs like sudo, vim, etc.
392pub struct PtyShell {
393    /// The PTY master handle for resize operations
394    master: Box<dyn MasterPty + Send>,
395    /// Child process running the shell
396    child: Box<dyn Child + Send + Sync>,
397    /// Writer for PTY input (taken from master)
398    writer: Box<dyn Write + Send>,
399    /// Channel receiver for output from reader thread
400    output_rx: mpsc::Receiver<String>,
401    /// Current terminal size
402    size: PtySize,
403    /// Last command executed
404    pub last_command: String,
405    /// Accumulated output buffer
406    pub output_buffer: String,
407    /// Whether a command is currently running
408    pub command_running: bool,
409    /// Last cwd observed in this shell's nonce-bearing prompt.
410    current_cwd: PathBuf,
411    /// Monotonic start time of the current or most recently completed command.
412    /// Status polling uses this instead of restarting the clock per tool call.
413    command_started_at: Option<Instant>,
414    /// Monotonic command generation used by daemon journals to distinguish two
415    /// consecutive commands whose terminal bytes happen to be identical.
416    command_generation: u64,
417    /// Random identity of this PTY instance. Unlike the numeric generation it
418    /// changes when a shell is reset and generations start again at zero.
419    incarnation: u64,
420    /// Exit code of the last completed foreground command, parsed from the prompt
421    /// marker (`──➤<nonce>:<code>`). `None` until a command finishes, and reset
422    /// to `None` while one is running.
423    pub last_exit_code: Option<i32>,
424    /// Maximum output size before truncation
425    max_output_size: usize,
426    /// Flag for output truncation
427    pub output_truncated: bool,
428    /// Bounded scrollback ring of raw PTY lines (newest at the back) plus the
429    /// in-flight partial line, with drop accounting so a truncated scrollback is
430    /// reported to the caller instead of silently shrinking. See `LineRing`.
431    ring: LineRing,
432    /// Hash of the last rendered output we shipped to the caller. Used by the
433    /// delta path in `status_check` to elide repeats when the screen is idle.
434    pub last_returned_hash: Option<u64>,
435    /// Cumulative PTY snapshot already delivered to the caller. Incremental
436    /// status polling diffs against this value, then advances it after rendering.
437    delivered_output: String,
438    /// True from a foreground command's start until a response has reported
439    /// its exit. The prompt can be drained by another reader (the daemon
440    /// journal) between two status polls; the next poll then finds the shell
441    /// idle and must still deliver the final output and exit code instead of
442    /// rejecting the call as if nothing had run.
443    pending_completion_report: bool,
444    /// Optional command a human can run to attach to the same terminal session.
445    pub attach_hint: Option<String>,
446    /// The exact suffix that ends this shell's prompt: `──➤<nonce>`. The nonce is
447    /// a per-shell random value embedded in `PROMPT_COMMAND`, so command output
448    /// can't impersonate the prompt (printing `◉ x──➤` no longer ends a command
449    /// early). Anchoring completion on this instead of the bare glyphs removes
450    /// the false-positive that truncated output when a program echoed them.
451    prompt_end_marker: String,
452    /// Live terminal emulator (fixed-viewport, `vt100`-backed) fed continuously
453    /// by the reader thread. Unlike the scrollback ring (raw lines), it keeps a
454    /// consolidated screen grid — cursor moves, redraws, alternate-screen
455    /// applied — so a TUI yields a stable, non-stacked snapshot. The fixed
456    /// viewport is what lets inline-rendering TUIs (the `agy`/Antigravity CLI,
457    /// which redraws with cursor-up + erase-line in the main screen) consolidate
458    /// instead of ghosting. See `live_snapshot`.
459    live: Arc<StdMutex<LiveTerminal>>,
460    /// Workspace root under which output-offload scratch files are written.
461    /// `None` until a caller sets it (the workspace is only known after
462    /// Initialize, and `execute_command` sets it per command). See
463    /// `crate::utils::scratch_file`.
464    scratch_workspace_root: Option<PathBuf>,
465    /// Scratch file holding the CURRENT command's dropped output head, created
466    /// lazily on the first truncation and reset per command.
467    scratch_path: Option<PathBuf>,
468    /// Bytes already streamed to `scratch_path`, used to enforce `SCRATCH_MAX_BYTES`.
469    scratch_bytes: u64,
470    /// Shared with the reader thread: when set, the current command's output
471    /// is pure discard (scratch budget exhausted), so the reader inserts
472    /// [`DISCARD_READ_THROTTLE`] between reads and lets the kernel PTY buffer
473    /// back-pressure the producer. Cleared on every new command.
474    discard_throttle: Arc<AtomicBool>,
475    /// Windows job object holding the shell and everything it spawns, so a
476    /// dropped shell takes its background children with it (the Unix path
477    /// signals the process group instead).
478    #[cfg(windows)]
479    job: Option<crate::os::windows::ProcessTreeJob>,
480}
481
482impl std::fmt::Debug for PtyShell {
483    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
484        f.debug_struct("PtyShell")
485            .field("size", &format!("{}x{}", self.size.cols, self.size.rows))
486            .field("last_command", &self.last_command)
487            .field("command_running", &self.command_running)
488            .field("current_cwd", &self.current_cwd)
489            .field("output_truncated", &self.output_truncated)
490            .field("output_buffer_len", &self.output_buffer.len())
491            .field("attach_hint", &self.attach_hint)
492            .finish_non_exhaustive()
493    }
494}
495
496/// Resolve the process group to signal for a PTY child, but ONLY when it is
497/// safe: the pid must be a real child (`> 1`) that leads its own group
498/// (`getpgid(pid) == pid`). portable-pty `setsid`s the shell, so a live PTY
499/// child is always its own group leader; if that ever stopped holding,
500/// `kill(-pgid, ...)` would hit some unrelated group, so we refuse instead of
501/// guessing.
502///
503/// The `pid > 1` check is load-bearing: `kill(-1, ...)` means "every process I
504/// may signal" and `kill(0, ...)` means "my own group" - either would be
505/// catastrophic from a teardown path.
506#[cfg(unix)]
507fn killable_group(pid: u32) -> Option<i32> {
508    crate::os::unix::owned_process_group(pid)
509}
510
511/// Send `signal` to the whole process group `pgid` (group-kill via negative
512/// pid). `pgid` must be one vetted by [`killable_group`].
513#[cfg(unix)]
514fn signal_group(pgid: i32, signal: i32) {
515    let _ = crate::os::unix::signal_group(pgid, signal);
516}
517
518impl Drop for PtyShell {
519    /// Kill and reap the shell child **and its whole process group** so neither
520    /// the shell nor anything it spawned leaks.
521    ///
522    /// `std::process::Child::drop` neither kills nor waits, and even
523    /// `Child::kill` signals only the shell itself: a background job it started
524    /// (`npm run dev &`, a `nohup`'d server) would be reparented to init and live
525    /// on. Because portable-pty runs the shell as a session/group leader, we can
526    /// signal the whole group with a negative pid - SIGTERM first so well-behaved
527    /// children can clean up, then `Child::kill` (SIGKILL on the leader, which
528    /// closes the PTY slave so the reader thread's `read()` returns EOF and the
529    /// thread exits), then SIGKILL the group to sweep anything still alive, then
530    /// reap. The pgid is captured while the leader is alive and reused: it stays
531    /// valid until we `wait()`, even after the leader dies. All best-effort.
532    fn drop(&mut self) {
533        // Only group-kill the direct bash/zsh path. Under screen/tmux (`attach_hint`
534        // is `Some`) the `Child` is a multiplexer *client*; the real shell runs in
535        // a detached daemon in another process group, so a group-kill here would
536        // miss the shell entirely and could disturb unrelated sessions of the same
537        // multiplexer. Let the multiplexer own its lifecycle in that case.
538        #[cfg(unix)]
539        let pgid = if self.attach_hint.is_some() {
540            None
541        } else {
542            self.child.process_id().and_then(killable_group)
543        };
544
545        #[cfg(unix)]
546        if let Some(pgid) = pgid {
547            signal_group(pgid, libc::SIGTERM);
548        }
549
550        // Windows: the job object takes the whole tree down at once.
551        #[cfg(windows)]
552        if let Some(job) = self.job.as_ref() {
553            job.terminate();
554        }
555
556        // SIGKILL the leader and close the PTY slave (unblocks the reader thread).
557        let _ = self.child.kill();
558
559        #[cfg(unix)]
560        if let Some(pgid) = pgid {
561            signal_group(pgid, libc::SIGKILL);
562        }
563
564        let _ = self.child.wait();
565    }
566}
567
568impl PtyShell {
569    /// Create a new PTY shell session
570    ///
571    /// # Arguments
572    /// * `initial_dir` - Starting directory for the shell
573    /// * `restricted_mode` - Whether to use bash restricted mode (-r)
574    ///
575    /// # Returns
576    /// A new `PtyShell` instance with an active bash session
577    pub fn new(initial_dir: &Path, restricted_mode: bool) -> Result<Self> {
578        Self::new_with_agent_paths(initial_dir, restricted_mode, None, None)
579    }
580
581    /// Create a PTY with Winx's stable workspace and managed helper paths in
582    /// the child environment. Direct callers keep using [`Self::new`].
583    pub(crate) fn new_with_agent_paths(
584        initial_dir: &Path,
585        restricted_mode: bool,
586        workspace_root: Option<&Path>,
587        temporary_artifact_dir: Option<&Path>,
588    ) -> Result<Self> {
589        info!(
590            "Creating new PTY shell (restricted: {}) in {}",
591            restricted_mode,
592            initial_dir.display()
593        );
594
595        // On Windows, fail fast with an actionable message if no Git for Windows
596        // bash is available, rather than letting `CommandBuilder::new("bash")`
597        // fail later with an opaque OS error.
598        #[cfg(windows)]
599        ensure_windows_shell_available(restricted_mode)?;
600
601        // Initialize the native PTY system
602        let pty_system = native_pty_system();
603
604        // Configure terminal size
605        let size =
606            PtySize { rows: DEFAULT_ROWS, cols: DEFAULT_COLS, pixel_width: 0, pixel_height: 0 };
607
608        // Open the PTY pair (master + slave)
609        let pair = pty_system.openpty(size).context("Failed to open PTY pair")?;
610
611        // Build the command
612        let (mut cmd, attach_hint, shell_kind) = attachable_command(restricted_mode);
613        if shell_kind.is_powershell() && restricted_mode {
614            return Err(anyhow!(
615                "restricted mode needs bash -r; PowerShell has no equivalent restricted mode"
616            ));
617        }
618
619        // Set up environment for proper terminal behavior
620        cmd.env("TERM", "xterm-256color");
621        cmd.env("COLORTERM", "truecolor");
622        cmd.env("PAGER", "cat");
623        cmd.env("GIT_PAGER", "cat");
624        // Agent commands (and the prompt bootstrap line) must not end up in the
625        // user's ~/.bash_history: bash skips saving history when HISTFILE is
626        // empty. Set before exec so it also holds under `bash -r`, which forbids
627        // changing HISTFILE afterwards.
628        cmd.env("HISTFILE", "");
629        cmd.env("COLUMNS", DEFAULT_COLS.to_string());
630        cmd.env("ROWS", DEFAULT_ROWS.to_string());
631        if let Some(workspace_root) = workspace_root {
632            cmd.env("WINX_WORKSPACE_ROOT", workspace_root);
633        }
634        if let Some(temporary_artifact_dir) = temporary_artifact_dir {
635            cmd.env("WINX_TEMP_DIR", temporary_artifact_dir);
636        }
637        // Per-shell random nonce embedded in the prompt so command output can't
638        // forge the completion marker. 64 bits of entropy in hex.
639        let nonce = format!("{:016x}", rand::random::<u64>());
640        // WCGW-style prompt for command completion detection
641        // Note: removed \r\e[2K which was erasing the prompt before it could be detected
642        // `__winx_ec=$?` captures the user command's exit status as the very
643        // first thing PROMPT_COMMAND does, then we print it after the marker.
644        cmd.env(
645            "PROMPT_COMMAND",
646            format!(r#"__winx_ec=$?; printf "◉ %s──➤{nonce}:%s " "$PWD" "$__winx_ec""#),
647        );
648        cmd.cwd(initial_dir);
649
650        // Spawn bash in the PTY slave
651        let child = pair.slave.spawn_command(cmd).context("Failed to spawn bash in PTY")?;
652        #[cfg(windows)]
653        let job = match crate::os::windows::ProcessTreeJob::new()
654            .and_then(|job| child.process_id().map_or(Ok(()), |pid| job.assign(pid)).map(|()| job))
655        {
656            Ok(job) => Some(job),
657            Err(error) => {
658                warn!(%error, "PTY child is not in a job object; background children may outlive the shell");
659                None
660            }
661        };
662
663        // Get reader and writer from master
664        let reader = pair.master.try_clone_reader().context("Failed to clone PTY reader")?;
665        let writer = pair.master.take_writer().context("Failed to take PTY writer")?;
666
667        // Bounded channel: if the consumer stalls, the reader thread blocks on
668        // send (natural backpressure via the PTY OS buffer) instead of growing
669        // memory without bound on a runaway producer like `yes`.
670        let (output_tx, output_rx) = mpsc::sync_channel::<String>(1024);
671
672        // Live terminal emulator, shared with the reader thread so the screen
673        // grid stays current without any consumer needing to poll.
674        let live = Arc::new(StdMutex::new(LiveTerminal::new(DEFAULT_ROWS, DEFAULT_COLS)));
675        let live_reader = Arc::clone(&live);
676        let discard_throttle = Arc::new(AtomicBool::new(false));
677        let throttle_reader = Arc::clone(&discard_throttle);
678
679        spawn_pty_reader(reader, output_tx, live_reader, throttle_reader);
680
681        // Create the shell instance
682        let mut shell = Self {
683            master: pair.master,
684            child,
685            writer,
686            output_rx,
687            size,
688            last_command: String::new(),
689            output_buffer: String::new(),
690            command_running: false,
691            current_cwd: initial_dir.to_path_buf(),
692            command_started_at: None,
693            command_generation: 0,
694            incarnation: rand::random::<u64>().max(1),
695            last_exit_code: None,
696            max_output_size: MAX_OUTPUT_SIZE,
697            output_truncated: false,
698            ring: LineRing::new(RING_BUFFER_LINES, MAX_PARTIAL_LINE_BYTES),
699            last_returned_hash: None,
700            delivered_output: String::new(),
701            pending_completion_report: false,
702            attach_hint,
703            prompt_end_marker: format!("{WCGW_PROMPT_END}{nonce}"),
704            live,
705            scratch_workspace_root: None,
706            scratch_path: None,
707            scratch_bytes: 0,
708            discard_throttle,
709            #[cfg(windows)]
710            job,
711        };
712
713        // Initialize the shell with WCGW-style prompt
714        shell.initialize_prompt(shell_kind, &nonce)?;
715
716        debug!("PTY shell created successfully");
717        Ok(shell)
718    }
719
720    /// Initialize the shell prompt for WCGW compatibility
721    fn initialize_prompt(&mut self, shell_kind: ShellKind, nonce: &str) -> Result<()> {
722        // Set up the dynamic prompt - matches WCGW Python PROMPT_STATEMENT.
723        // zsh ignores PROMPT_COMMAND, so it gets a precmd hook with a blanked
724        // default prompt instead.
725        // Blank the shell's own PS1/PROMPT so the line ends exactly at our `──➤`
726        // marker. Otherwise a user's ~/.bashrc/~/.zshrc PS1 (e.g. `[user@host]$`)
727        // is appended after the marker, and prompt detection — which anchors on a
728        // trailing `──➤` — only fires when the chunk happens to fragment right
729        // before the PS1, making command-completion detection flaky.
730        let prompt_statement = match shell_kind {
731            // Clear precmd_functions too: frameworks (oh-my-zsh/p10k) register the
732            // prompt via that array, so redefining `precmd` alone leaves their
733            // prompt in place and our `──➤` marker never ends the line.
734            ShellKind::Zsh => format!(
735                r#"export GIT_PAGER=cat PAGER=cat; precmd_functions=(); preexec_functions=(); PROMPT=''; RPROMPT=''; precmd() {{ local __winx_ec=$?; printf "◉ %s──➤{nonce}:%s " "$PWD" "$__winx_ec" }}"#
736            ),
737            ShellKind::Bash => format!(
738                r#"export GIT_PAGER=cat PAGER=cat PROMPT_COMMAND='__winx_ec=$?; printf "◉ %s──➤{nonce}:%s " "$PWD" "$__winx_ec"'; PS1=''"#
739            ),
740            ShellKind::PowerShell => powershell_bootstrap(nonce),
741        };
742
743        self.write_command(&prompt_statement)?;
744
745        // Wait for the first marker-bearing prompt instead of a fixed pause:
746        // everything before it (the shell's startup banner, the echoed
747        // bootstrap line) must never leak into the first command's output, and
748        // Git for Windows bash reaches its first prompt far later than Linux
749        // bash. Once the marker is seen, a short drain swallows the trailing
750        // bytes of that same prompt.
751        let deadline = Instant::now() + PROMPT_BOOTSTRAP_TIMEOUT;
752        let mut bootstrap = String::new();
753        let mut settled = false;
754        while Instant::now() < deadline {
755            match self.output_rx.recv_timeout(Duration::from_millis(50)) {
756                Ok(chunk) => {
757                    self.answer_terminal_queries(&chunk);
758                    bootstrap.push_str(&chunk);
759                    if Self::check_prompt_complete(&bootstrap, &self.prompt_end_marker) {
760                        settled = true;
761                        break;
762                    }
763                }
764                Err(mpsc::RecvTimeoutError::Timeout) => {}
765                Err(mpsc::RecvTimeoutError::Disconnected) => break,
766            }
767        }
768        if settled {
769            std::thread::sleep(Duration::from_millis(30));
770        } else {
771            warn!(
772                timeout_ms = PROMPT_BOOTSTRAP_TIMEOUT.as_millis(),
773                "PTY shell did not print its first prompt in time; continuing anyway"
774            );
775        }
776        bootstrap.push_str(&self.drain_output());
777        debug!(
778            bytes = bootstrap.len(),
779            settled,
780            child_pid = ?self.child.process_id(),
781            "PTY prompt bootstrap drained"
782        );
783
784        Ok(())
785    }
786
787    /// Answer terminal queries the console host blocks on.
788    ///
789    /// Windows `ConPTY` is created with `INHERIT_CURSOR` (portable-pty's default)
790    /// and then asks the "terminal" for the cursor position with `ESC[6n`
791    /// before rendering a single byte of the child's output. Winx is that
792    /// terminal, so it must reply with a cursor position report or every shell
793    /// stays silent forever. The reply is harmless on Unix, where no PTY layer
794    /// issues the query.
795    fn answer_terminal_queries(&mut self, chunk: &str) {
796        const CURSOR_POSITION_REQUEST: &str = "\x1b[6n";
797        if !chunk.contains(CURSOR_POSITION_REQUEST) {
798            return;
799        }
800        debug!("PTY answered a cursor position request");
801        if let Err(error) = self.writer.write_all(b"\x1b[1;1R").and_then(|()| self.writer.flush()) {
802            debug!("PTY cursor position report failed: {error}");
803        }
804    }
805
806    /// Write a command to the PTY, submitting it with a carriage return.
807    fn write_command(&mut self, command: &str) -> Result<()> {
808        // Submit with `\r`, matching the foreground path (`send_special_key("Enter")`
809        // also sends `\r`) and a real terminal's Enter key. The two paths used to
810        // disagree — background sent `\n` here, foreground sent `\r` — which is a
811        // real difference for readline-based TUIs. bash's canonical line discipline
812        // maps CR to NL (ICRNL), so plain commands behave identically.
813        let cmd_with_newline = format!("{command}\r");
814        self.writer.write_all(cmd_with_newline.as_bytes()).context("Failed to write to PTY")?;
815        self.writer.flush().context("Failed to flush PTY")?;
816        Ok(())
817    }
818
819    /// Drain any pending output from the PTY channel
820    fn drain_output(&mut self) -> String {
821        let mut output = String::new();
822        let deadline = Instant::now() + Duration::from_millis(200);
823
824        // Drain all available output from the channel
825        while Instant::now() < deadline {
826            match self.output_rx.try_recv() {
827                Ok(chunk) => {
828                    self.answer_terminal_queries(&chunk);
829                    output.push_str(&chunk);
830
831                    // Prevent runaway reads
832                    if output.len() > self.max_output_size {
833                        self.output_truncated = true;
834                        break;
835                    }
836                }
837                Err(TryRecvError::Empty) => {
838                    // No more data, wait briefly for more
839                    thread::sleep(Duration::from_millis(10));
840                }
841                Err(TryRecvError::Disconnected) => {
842                    // Reader thread died
843                    break;
844                }
845            }
846        }
847
848        output
849    }
850
851    /// Send a command to the shell and start reading output
852    pub fn send_command(&mut self, command: &str) -> Result<()> {
853        debug!(bytes = command.len(), "PTY sending command");
854
855        // Clear previous state
856        self.output_buffer.clear();
857        self.output_truncated = false;
858        self.reset_scratch();
859        self.last_command = command.to_string();
860        self.command_running = true;
861        self.mark_command_started();
862        self.last_exit_code = None;
863        // A new command means the next status_check should return whatever
864        // shows up — drop the dedup hash so we don't elide the first response.
865        self.last_returned_hash = None;
866        self.delivered_output.clear();
867        // Drop retained OSC title/progress so the previous foreground
868        // program's last title can't masquerade as this command's turn state.
869        self.live.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clear_osc();
870
871        // Write the command
872        self.write_command(command)?;
873
874        Ok(())
875    }
876
877    /// Start the monotonic runtime clock for a newly submitted command.
878    pub fn mark_command_started(&mut self) {
879        self.command_generation = self.command_generation.saturating_add(1);
880        self.command_started_at = Some(Instant::now());
881        self.pending_completion_report = true;
882    }
883
884    /// Whether the most recent foreground command has finished without any
885    /// response having reported its exit yet.
886    pub fn completion_report_pending(&self) -> bool {
887        !self.command_running && self.pending_completion_report
888    }
889
890    /// Record that a response reported the current command as finished.
891    pub fn mark_completion_reported(&mut self) {
892        self.pending_completion_report = false;
893    }
894
895    pub fn command_generation(&self) -> u64 {
896        self.command_generation
897    }
898
899    pub fn incarnation(&self) -> u64 {
900        self.incarnation
901    }
902
903    /// Elapsed runtime since the current command was submitted.
904    pub fn command_elapsed(&self) -> Option<Duration> {
905        self.command_started_at.map(|started_at| started_at.elapsed())
906    }
907
908    /// Current working directory last reported by this shell's prompt.
909    pub fn current_cwd(&self) -> &Path {
910        &self.current_cwd
911    }
912
913    /// Snapshot used as the left-hand side of incremental output rendering.
914    pub fn delivered_output(&self) -> String {
915        self.delivered_output.clone()
916    }
917
918    /// Mark the cumulative output snapshot as delivered after rendering it.
919    pub fn mark_output_delivered(&mut self, output: &str) {
920        self.delivered_output.clear();
921        self.delivered_output.push_str(output);
922    }
923
924    /// Return up to `lines` recent lines from the scrollback ring, oldest
925    /// first. When older lines were evicted or a long unterminated line was
926    /// clipped, a `[winx: …]` notice is prepended so the caller knows the
927    /// scrollback is incomplete rather than silently receiving less than asked.
928    pub fn collect_scrollback(&self, lines: usize) -> String {
929        // The ring holds raw PTY lines. Replay them through the terminal
930        // emulator so cursor movements (readline echo, in-place redraws) are
931        // *applied* — not merely stripped — yielding what the screen actually
932        // showed. A plain strip can't undo a `\x1b[D`, so it would leave
933        // `>>> p>>> pr>>> pri...` echo noise behind; the emulator collapses it.
934        let rendered =
935            crate::state::terminal::render_terminal_output(&self.ring.raw(lines)).join("\n");
936        match self.ring.scrollback_notice(lines) {
937            Some(notice) => format!("{notice}\n{rendered}"),
938            None => rendered,
939        }
940    }
941
942    /// Hash arbitrary rendered output into a u64 dedup key.
943    pub fn fingerprint(text: &str) -> u64 {
944        let mut hasher = DefaultHasher::new();
945        text.hash(&mut hasher);
946        hasher.finish()
947    }
948
949    /// Read output from the PTY with timeout
950    ///
951    /// Returns (output, `is_complete`) tuple where `is_complete` indicates
952    /// whether the command has finished (prompt detected)
953    pub fn read_output(&mut self, timeout_secs: f32) -> Result<(String, bool)> {
954        let timeout = Duration::from_secs_f32(timeout_secs.clamp(0.1, 60.0));
955        let start = Instant::now();
956        let mut complete = false;
957        let mut no_data_count = 0;
958        let mut prompt_detected_at: Option<Instant> = None;
959
960        while start.elapsed() < timeout {
961            match self.output_rx.try_recv() {
962                Ok(chunk) => {
963                    self.answer_terminal_queries(&chunk);
964                    self.output_buffer.push_str(&chunk);
965                    self.ring.push_chunk(&chunk);
966                    no_data_count = 0;
967
968                    // Check for WCGW prompt indicating command completion
969                    if prompt_detected_at.is_none()
970                        && (Self::check_prompt_complete(&chunk, &self.prompt_end_marker)
971                            || Self::check_prompt_complete(
972                                &self.output_buffer,
973                                &self.prompt_end_marker,
974                            ))
975                    {
976                        prompt_detected_at = Some(Instant::now());
977                        debug!("Prompt detected, draining remaining output...");
978                    }
979
980                    // Truncate if too large (offloads the dropped head to scratch).
981                    self.truncate_output_buffer_with_offload();
982                }
983                Err(TryRecvError::Empty) => {
984                    // No data available, wait briefly
985                    thread::sleep(Duration::from_millis(10));
986                    no_data_count += 1;
987
988                    // If prompt was detected, check if we've drained long enough
989                    if let Some(detected_time) = prompt_detected_at {
990                        // Wait 100ms after prompt detection to capture any trailing output
991                        if detected_time.elapsed() > Duration::from_millis(100) {
992                            complete = true;
993                            debug!("Command completed - prompt detected and drained");
994                            break;
995                        }
996                    } else if no_data_count > 10
997                        && Self::check_prompt_complete(&self.output_buffer, &self.prompt_end_marker)
998                    {
999                        // Prompt detected during empty reads
1000                        prompt_detected_at = Some(Instant::now());
1001                        debug!("Prompt detected after wait, draining...");
1002                    }
1003                }
1004                Err(TryRecvError::Disconnected) => {
1005                    // Reader thread died - PTY closed
1006                    warn!("PTY reader disconnected");
1007                    complete = true;
1008                    break;
1009                }
1010            }
1011        }
1012
1013        if complete || prompt_detected_at.is_some() {
1014            self.command_running = false;
1015            self.last_exit_code =
1016                Self::parse_prompt_exit_code(&self.output_buffer, &self.prompt_end_marker);
1017            self.update_current_cwd_from_prompt();
1018            complete = true;
1019        }
1020
1021        Ok((self.output_buffer.clone(), complete))
1022    }
1023
1024    /// Non-blocking drain of whatever the reader thread has already queued.
1025    ///
1026    /// Unlike [`read_output`](Self::read_output), this never sleeps: it consumes
1027    /// every chunk currently available, updates prompt/completion state, and
1028    /// returns immediately. `prune_finished_shells` uses it so the global
1029    /// background-shell lock is never held across a blocking 100ms `read_output`.
1030    /// Returns `true` if the command has completed (prompt seen or PTY closed).
1031    pub fn poll_output_nonblocking(&mut self) -> bool {
1032        let mut prompt_seen = false;
1033        loop {
1034            match self.output_rx.try_recv() {
1035                Ok(chunk) => {
1036                    self.answer_terminal_queries(&chunk);
1037                    let chunk_has_prompt =
1038                        Self::check_prompt_complete(&chunk, &self.prompt_end_marker);
1039                    self.output_buffer.push_str(&chunk);
1040                    self.ring.push_chunk(&chunk);
1041                    if chunk_has_prompt
1042                        || Self::check_prompt_complete(&self.output_buffer, &self.prompt_end_marker)
1043                    {
1044                        prompt_seen = true;
1045                    }
1046                    self.truncate_output_buffer_with_offload();
1047                }
1048                Err(TryRecvError::Empty) => break,
1049                Err(TryRecvError::Disconnected) => {
1050                    self.command_running = false;
1051                    return true;
1052                }
1053            }
1054        }
1055        if prompt_seen {
1056            self.command_running = false;
1057            self.last_exit_code =
1058                Self::parse_prompt_exit_code(&self.output_buffer, &self.prompt_end_marker);
1059            self.update_current_cwd_from_prompt();
1060        }
1061        // Completion is state, not an edge. Another consumer (notably the
1062        // background reaper) may have drained the prompt first; a later poll
1063        // must still report the already-idle shell as complete even when this
1064        // particular drain saw no new prompt bytes.
1065        !self.command_running
1066    }
1067
1068    fn update_current_cwd_from_prompt(&mut self) {
1069        let Some(last) =
1070            self.output_buffer.lines().rev().find(|line| line.contains(&self.prompt_end_marker))
1071        else {
1072            return;
1073        };
1074        let clean = crate::state::terminal::strip_ansi_codes(last);
1075        let Some((before_marker, _)) = clean.rsplit_once(&self.prompt_end_marker) else {
1076            return;
1077        };
1078        let Some((_, cwd)) = before_marker.rsplit_once("◉ ") else {
1079            return;
1080        };
1081        let cwd = cwd.trim();
1082        if !cwd.is_empty() {
1083            self.current_cwd = native_cwd_from_prompt(cwd);
1084        }
1085    }
1086
1087    /// Snapshot of the accumulated output buffer — the same text `read_output`
1088    /// returns. Lets callers poll non-blocking (`poll_output_nonblocking`) and
1089    /// grab the buffer once at the end instead of cloning it on every slice.
1090    pub fn output_snapshot(&self) -> String {
1091        self.output_buffer.clone()
1092    }
1093
1094    /// Check if the output ends with this shell's prompt.
1095    ///
1096    /// `prompt_end` is the per-shell `──➤<nonce>` suffix. Anchoring on the LAST
1097    /// non-empty line (not a global `contains`) plus the random nonce means
1098    /// command output that happens to print the prompt glyphs mid-stream — or
1099    /// even a forged `◉ x──➤ ` at end of line — can't be mistaken for the prompt
1100    /// and truncate output or end the command early.
1101    fn check_prompt_complete(text: &str, prompt_end: &str) -> bool {
1102        Self::parse_prompt_exit_code(text, prompt_end).is_some()
1103    }
1104
1105    /// If the last non-empty line is this shell's completion prompt
1106    /// (`◉ <pwd>──➤<nonce>:<code>`), return the exit code that follows the
1107    /// marker. Returns `None` when the prompt isn't present — which is exactly
1108    /// "the command is still running". The per-shell nonce plus the structured
1109    /// `:<digits>` suffix keep command output from forging completion.
1110    fn parse_prompt_exit_code(text: &str, prompt_end: &str) -> Option<i32> {
1111        let last = text.lines().rev().find(|line| !line.trim().is_empty())?;
1112        if !last.contains(WCGW_PROMPT_PATTERN) {
1113            return None;
1114        }
1115        // Everything after the last "──➤<nonce>" must be ":<digits>" followed by
1116        // the prompt's own terminator — this confirms the prompt ends the line
1117        // AND yields the code. The raw tail keeps its escape sequences: a
1118        // trailing erase/cursor sequence (":0 \x1b[K", or ConPTY's ":0\x1b[C")
1119        // counts as the terminator, so it is stripped only for parsing.
1120        let raw_tail = last.rsplit_once(prompt_end)?.1;
1121        let clean_tail = crate::state::terminal::strip_ansi_codes(raw_tail);
1122        let code_text = clean_tail.strip_prefix(':')?;
1123        let digits = code_text
1124            .char_indices()
1125            .take_while(|(index, c)| c.is_ascii_digit() || (*index == 0 && *c == '-'))
1126            .count();
1127        let (code, rest) = code_text.split_at(digits);
1128        if !rest.chars().all(char::is_whitespace) {
1129            return None;
1130        }
1131        // A read boundary can fall between the digits of "127": without the
1132        // terminator the record is still in flight, and accepting "1" now would
1133        // report the wrong exit code before the rest arrives.
1134        let terminated = !rest.is_empty() || raw_tail.len() > clean_tail.len();
1135        if !terminated {
1136            return None;
1137        }
1138        code.parse::<i32>().ok()
1139    }
1140
1141    /// Point output-offload scratch files at `root` (the workspace). Idempotent;
1142    /// callers set it per command so it always tracks the current workspace.
1143    pub fn set_scratch_root(&mut self, root: &Path) {
1144        self.scratch_workspace_root = Some(root.to_path_buf());
1145    }
1146
1147    /// The scratch file holding the current command's dropped output head, if any
1148    /// was offloaded this command.
1149    pub fn scratch_path(&self) -> Option<&Path> {
1150        self.scratch_path.as_deref()
1151    }
1152
1153    /// Forget the current command's scratch file so the next command starts a
1154    /// fresh one. Does not delete the file (pruned later by age).
1155    pub fn reset_scratch(&mut self) {
1156        self.scratch_path = None;
1157        self.scratch_bytes = 0;
1158        self.discard_throttle.store(false, AtomicOrdering::Relaxed);
1159    }
1160
1161    /// Append a just-dropped output `head` to the per-command scratch file so the
1162    /// agent can recover it via `ReadFiles`. Best-effort: needs a known workspace
1163    /// root, stops at `SCRATCH_MAX_BYTES`, and swallows IO errors.
1164    fn offload_dropped_head(&mut self, head: &str) {
1165        let Some(root) = self.scratch_workspace_root.clone() else {
1166            return;
1167        };
1168        // Clamp to the remaining byte budget so the file honors SCRATCH_MAX_BYTES
1169        // exactly (a single head can be up to keep_size, ~500 KB). Snap to a char
1170        // boundary so we never slice mid-UTF-8.
1171        let remaining = SCRATCH_MAX_BYTES.saturating_sub(self.scratch_bytes);
1172        if remaining == 0 {
1173            // From here on the head is discarded outright — reading faster
1174            // only burns CPU. Engage reader back-pressure until the next
1175            // command resets the scratch state.
1176            self.discard_throttle.store(true, AtomicOrdering::Relaxed);
1177            return;
1178        }
1179        let head = match usize::try_from(remaining) {
1180            Ok(rem) if rem < head.len() => &head[..crate::utils::floor_char_boundary(head, rem)],
1181            _ => head,
1182        };
1183        if self.scratch_path.is_none() {
1184            self.scratch_path = crate::utils::scratch_file::new_scratch_path(&root);
1185        }
1186        let Some(path) = self.scratch_path.clone() else {
1187            return;
1188        };
1189        match crate::utils::scratch_file::append_scratch(&path, head.as_bytes()) {
1190            Ok(0) if self.scratch_bytes == 0 => self.scratch_path = None,
1191            Ok(written) => {
1192                self.scratch_bytes = self.scratch_bytes.saturating_add(written as u64);
1193                if self.scratch_bytes >= SCRATCH_MAX_BYTES {
1194                    self.discard_throttle.store(true, AtomicOrdering::Relaxed);
1195                }
1196            }
1197            Err(e) => debug!("scratch: append to {} failed: {e}", path.display()),
1198        }
1199    }
1200
1201    /// Once `output_buffer` exceeds the cap, offload the head about to be dropped
1202    /// to the scratch file, then keep only the tail with a truncation marker.
1203    /// Shared by the blocking and non-blocking drain paths so the offload and the
1204    /// char-boundary handling live in one place.
1205    fn truncate_output_buffer_with_offload(&mut self) {
1206        if self.output_buffer.len() <= self.max_output_size {
1207            return;
1208        }
1209        self.output_truncated = true;
1210        let keep_size = self.max_output_size / 2;
1211        // Snap to a char boundary: a raw byte offset can land mid-UTF-8
1212        // (CJK/emoji/box-drawing/the prompt glyphs) and slicing there would panic.
1213        let cut = crate::utils::floor_char_boundary(
1214            &self.output_buffer,
1215            self.output_buffer.len() - keep_size,
1216        );
1217        let head = self.output_buffer[..cut].to_owned();
1218        self.offload_dropped_head(&head);
1219        // Replace the dropped head in place instead of `format!`-ing a brand-new
1220        // String: `replace_range` shifts the kept tail down once and reuses the
1221        // buffer's allocation. `cut` is already a char boundary (above), and 0 is
1222        // always one, so the range is valid.
1223        self.output_buffer.replace_range(..cut, "\n(...output truncated...)\n");
1224    }
1225
1226    /// Send Ctrl+C (interrupt) to the PTY
1227    pub fn send_interrupt(&mut self) -> Result<()> {
1228        debug!("PTY sending Ctrl+C");
1229        self.writer
1230            .write_all(&[0x03]) // ASCII ETX (Ctrl+C)
1231            .context("Failed to send Ctrl+C")?;
1232        self.writer.flush()?;
1233        Ok(())
1234    }
1235
1236    /// Send Ctrl+D (EOF) to the PTY
1237    pub fn send_eof(&mut self) -> Result<()> {
1238        debug!("PTY sending Ctrl+D");
1239        self.writer
1240            .write_all(&[0x04]) // ASCII EOT (Ctrl+D)
1241            .context("Failed to send Ctrl+D")?;
1242        self.writer.flush()?;
1243        Ok(())
1244    }
1245
1246    /// Send Ctrl+Z (suspend) to the PTY
1247    pub fn send_suspend(&mut self) -> Result<()> {
1248        debug!("PTY sending Ctrl+Z");
1249        self.writer
1250            .write_all(&[0x1A]) // ASCII SUB (Ctrl+Z)
1251            .context("Failed to send Ctrl+Z")?;
1252        self.writer.flush()?;
1253        Ok(())
1254    }
1255
1256    /// Send text directly to the PTY (for interactive input)
1257    pub fn send_text(&mut self, text: &str) -> Result<()> {
1258        debug!(bytes = text.len(), "PTY sending text");
1259        self.send_bytes(text.as_bytes()).context("Failed to send text")?;
1260        Ok(())
1261    }
1262
1263    /// Send raw bytes directly to the PTY.
1264    pub fn send_bytes(&mut self, bytes: &[u8]) -> Result<()> {
1265        self.writer.write_all(bytes).context("Failed to send bytes")?;
1266        self.writer.flush()?;
1267        Ok(())
1268    }
1269
1270    /// Send a special key sequence
1271    pub fn send_special_key(&mut self, key: &str) -> Result<()> {
1272        let bytes: &[u8] = match key {
1273            "Enter" => b"\r",
1274            "Tab" => b"\t",
1275            "Backspace" => b"\x7F",
1276            "Escape" => b"\x1B",
1277            "Up" | "KeyUp" => b"\x1B[A",
1278            "Down" | "KeyDown" => b"\x1B[B",
1279            "Right" | "KeyRight" => b"\x1B[C",
1280            "Left" | "KeyLeft" => b"\x1B[D",
1281            "Home" => b"\x1B[H",
1282            "End" => b"\x1B[F",
1283            "PageUp" => b"\x1B[5~",
1284            "PageDown" => b"\x1B[6~",
1285            "Delete" => b"\x1B[3~",
1286            "Insert" => b"\x1B[2~",
1287            "CtrlC" | "Ctrl-C" => b"\x03",
1288            "CtrlD" | "Ctrl-D" => b"\x04",
1289            "CtrlZ" | "Ctrl-Z" => b"\x1A",
1290            "CtrlL" | "Ctrl-L" => b"\x0C",
1291            _ => return Err(anyhow!("Unknown special key: {key}")),
1292        };
1293
1294        debug!("PTY sending special key: {} ({:?})", key, bytes);
1295        self.send_bytes(bytes)?;
1296        Ok(())
1297    }
1298
1299    /// Snapshot the live terminal screen — a stable, consolidated view of what a
1300    /// human would currently see, with cursor moves/redraws applied and ANSI
1301    /// stripped. `max_lines` of 0 returns the full screen buffer. This is the
1302    /// foundation for piloting interactive TUIs (the `claude` CLI, vim, ...).
1303    pub fn live_snapshot(&self, max_lines: usize) -> Vec<String> {
1304        // Recover from a poisoned lock instead of returning a blank screen
1305        // forever — a single panic while holding `live` would otherwise wedge
1306        // every future snapshot (and `wait_for_turn`/`screen` with it).
1307        self.live.lock().unwrap_or_else(std::sync::PoisonError::into_inner).snapshot(max_lines)
1308    }
1309
1310    /// Whether the live terminal is currently on the alternate screen buffer
1311    /// (a full-screen app like vim/htop/less is running).
1312    pub fn live_in_alt_screen(&self) -> bool {
1313        self.live.lock().unwrap_or_else(std::sync::PoisonError::into_inner).in_alt_screen()
1314    }
1315
1316    /// The latest OSC 0/2 window title emitted by the foreground program (`""`
1317    /// when none) — an out-of-band turn signal for the manifest recognizers
1318    /// (claude/codex render a spinner glyph in the title while generating).
1319    pub fn live_osc_title(&self) -> String {
1320        self.live.lock().unwrap_or_else(std::sync::PoisonError::into_inner).osc_title().to_string()
1321    }
1322
1323    /// The latest OSC 9 payload after `9;` (`""` when none) — ConEmu-style
1324    /// progress reads `4;<state>;<percent>`.
1325    pub fn live_osc_progress(&self) -> String {
1326        self.live
1327            .lock()
1328            .unwrap_or_else(std::sync::PoisonError::into_inner)
1329            .osc_progress()
1330            .to_string()
1331    }
1332
1333    /// Cursor position `(row, col)` on the live screen (0-based), so a piloting
1334    /// agent knows where focus is in a menu/form. `(0, 0)` if the lock is poisoned.
1335    pub fn live_cursor_position(&self) -> (u16, u16) {
1336        self.live.lock().unwrap_or_else(std::sync::PoisonError::into_inner).cursor_position()
1337    }
1338
1339    /// Diff the live screen against what the client last saw, returning only the
1340    /// changed lines when the change is small (huge token savings over many
1341    /// polls). Updates the baseline as a side effect. See [`ScreenUpdate`].
1342    pub fn live_snapshot_diff(&self, max_lines: usize, threshold: usize) -> ScreenUpdate {
1343        self.live
1344            .lock()
1345            .unwrap_or_else(std::sync::PoisonError::into_inner)
1346            .snapshot_diff(max_lines, threshold)
1347    }
1348
1349    /// Resize the terminal
1350    pub fn resize(&mut self, cols: u16, rows: u16) -> Result<()> {
1351        debug!("PTY resizing to {}x{}", cols, rows);
1352
1353        let new_size = PtySize { rows, cols, pixel_width: 0, pixel_height: 0 };
1354
1355        self.master.resize(new_size).context("Failed to resize PTY")?;
1356
1357        // Keep the live emulator's viewport in lockstep with the PTY size.
1358        self.live.lock().unwrap_or_else(std::sync::PoisonError::into_inner).resize(rows, cols);
1359
1360        self.size = new_size;
1361        Ok(())
1362    }
1363
1364    /// Get current terminal size
1365    pub fn get_size(&self) -> (u16, u16) {
1366        (self.size.cols, self.size.rows)
1367    }
1368
1369    /// OS process id of the shell that owns this PTY.
1370    pub fn process_id(&self) -> Option<u32> {
1371        self.child.process_id()
1372    }
1373
1374    /// Check if the shell is still alive
1375    pub fn is_alive(&mut self) -> bool {
1376        self.child.try_wait().is_ok_and(|status| status.is_none())
1377    }
1378}
1379
1380/// Thread-safe wrapper for `PtyShell`
1381pub type SharedPtyShell = Arc<Mutex<Option<PtyShell>>>;
1382
1383/// Create a new shared PTY shell
1384pub fn create_shared_pty(initial_dir: &Path, restricted_mode: bool) -> Result<SharedPtyShell> {
1385    let shell = PtyShell::new(initial_dir, restricted_mode)?;
1386    Ok(Arc::new(Mutex::new(Some(shell))))
1387}
1388
1389/// Split a byte slice into the longest valid-UTF-8 prefix (decoded) and the
1390/// trailing bytes of an incomplete final char (to carry into the next read).
1391/// Genuinely invalid sequences become a single U+FFFD and are consumed, so the
1392/// carry only ever holds a recoverable incomplete tail and never grows unbounded.
1393///
1394/// Iterative on purpose: a recursive version blows the reader thread's stack on
1395/// a burst of invalid bytes (e.g. `cat`-ing a binary), which aborts under
1396/// `panic = "abort"`. This stays O(1) in stack depth regardless of input.
1397fn decode_keep_incomplete(bytes: &[u8]) -> (String, Vec<u8>) {
1398    let mut decoded = String::new();
1399    let mut rest = bytes;
1400    loop {
1401        match std::str::from_utf8(rest) {
1402            Ok(text) => {
1403                decoded.push_str(text);
1404                return (decoded, Vec::new());
1405            }
1406            Err(error) => {
1407                let valid = error.valid_up_to();
1408                // `rest[..valid]` is valid UTF-8 by construction (no allocation
1409                // for the borrowed case).
1410                decoded.push_str(&String::from_utf8_lossy(&rest[..valid]));
1411                match error.error_len() {
1412                    // Incomplete final char: keep the tail for the next read.
1413                    None => return (decoded, rest[valid..].to_vec()),
1414                    // Genuinely invalid run: emit one replacement and skip past it.
1415                    Some(bad) => {
1416                        decoded.push('\u{FFFD}');
1417                        rest = &rest[valid + bad..];
1418                    }
1419                }
1420            }
1421        }
1422    }
1423}
1424
1425#[cfg(test)]
1426mod tests {
1427    use super::*;
1428    #[cfg(unix)] // only the shell-spawning tests need a workspace
1429    use tempfile::TempDir;
1430
1431    #[test]
1432    fn decode_passes_clean_utf8_through() {
1433        let (text, carry) = decode_keep_incomplete("hello ✓ café".as_bytes());
1434        assert_eq!(text, "hello ✓ café");
1435        assert!(carry.is_empty(), "expected empty carry");
1436    }
1437
1438    #[test]
1439    fn decode_carries_incomplete_trailing_char_across_reads() {
1440        // "é" is 0xC3 0xA9; a read boundary splits it. The first half must NOT
1441        // turn into U+FFFD — it's held and completed on the next read.
1442        let (text1, carry1) = decode_keep_incomplete(&[b'a', 0xC3]);
1443        assert_eq!(text1, "a");
1444        assert_eq!(carry1, vec![0xC3]);
1445
1446        let mut next = carry1;
1447        next.push(0xA9); // continuation byte arrives in the next read
1448        let (text2, carry2) = decode_keep_incomplete(&next);
1449        assert_eq!(text2, "é");
1450        assert!(carry2.is_empty(), "expected empty carry2");
1451    }
1452
1453    #[test]
1454    fn decode_replaces_genuinely_invalid_bytes() {
1455        // 0xFF is never valid UTF-8 and is not an incomplete prefix.
1456        let (text, carry) = decode_keep_incomplete(&[b'x', 0xFF, b'y']);
1457        assert_eq!(text, "x\u{FFFD}y");
1458        assert!(carry.is_empty(), "expected empty carry");
1459    }
1460
1461    #[test]
1462    fn decode_handles_large_invalid_burst_without_overflow() {
1463        // Regression: the first (recursive) version blew the stack — one frame
1464        // per invalid byte — and aborted under panic="abort" on a binary dump.
1465        // The iterative version must handle far more than the 4KB reader buffer.
1466        let big = vec![0xFFu8; 200_000];
1467        let (text, carry) = decode_keep_incomplete(&big);
1468        assert!(carry.is_empty(), "expected empty carry");
1469        assert_eq!(text.chars().filter(|&c| c == '\u{FFFD}').count(), 200_000);
1470    }
1471
1472    #[test]
1473    fn screen_session_name_parser_is_strict() {
1474        assert_eq!(super::winx_creator_pid("winx-123-456"), Some(123));
1475        assert_eq!(super::winx_creator_pid("winx-nope-456"), None);
1476        assert_eq!(super::winx_creator_pid("other-123-456"), None);
1477    }
1478
1479    #[cfg(unix)]
1480    #[test]
1481    fn process_probe_recognizes_current_process_and_rejects_reserved_pids() {
1482        assert!(super::process_exists(std::process::id()));
1483        assert!(!super::process_exists(0));
1484        assert!(!super::process_exists(1));
1485    }
1486
1487    #[test]
1488    fn msys_paths_convert_to_native_drives() {
1489        use super::msys_to_native;
1490        assert_eq!(msys_to_native("/c/Users/x/ws"), Some(PathBuf::from("C:\\Users\\x\\ws")));
1491        assert_eq!(msys_to_native("/cygdrive/d/work"), Some(PathBuf::from("D:\\work")));
1492        assert_eq!(msys_to_native("/c"), Some(PathBuf::from("C:\\")));
1493        assert_eq!(msys_to_native("/home/x"), None);
1494        assert_eq!(msys_to_native("relative"), None);
1495    }
1496
1497    #[test]
1498    fn prompt_detection_is_suffix_anchored() {
1499        // Per-shell nonce + exit code after the arrow: `──➤<nonce>:<code>`.
1500        let end = "──➤deadbeefcafe0001";
1501        // real prompt on the last line -> complete
1502        assert!(PtyShell::check_prompt_complete("out\nmore\n◉ /home/x──➤deadbeefcafe0001:0 ", end));
1503        // prompt with trailing ANSI erase -> still complete
1504        assert!(PtyShell::check_prompt_complete("◉ /home/x──➤deadbeefcafe0001:0 \u{1b}[K", end));
1505        // the bug: ◉ and ──➤ appear MID-output, last line is normal -> NOT complete
1506        assert!(!PtyShell::check_prompt_complete(
1507            "menu: ◉ start ──➤deadbeefcafe0001 stop\nstill running",
1508            end
1509        ));
1510        // command echoed after the prompt (not the waiting prompt) -> not complete
1511        assert!(!PtyShell::check_prompt_complete("◉ /home/x──➤deadbeefcafe0001:0 ls -la", end));
1512        // no prompt at all
1513        assert!(!PtyShell::check_prompt_complete("just some output\n", end));
1514        // the nonce's payoff: output that forges the bare glyphs but NOT the
1515        // nonce (or omits the exit code) must not be mistaken for the prompt.
1516        assert!(!PtyShell::check_prompt_complete("◉ /fake──➤ ", end));
1517        assert!(!PtyShell::check_prompt_complete("◉ /fake──➤wrongnonce:0 ", end));
1518        assert!(!PtyShell::check_prompt_complete("◉ /home/x──➤deadbeefcafe0001 ", end));
1519    }
1520
1521    #[test]
1522    fn powershell_bootstrap_defines_a_marker_prompt_without_psreadline() {
1523        let bootstrap = super::powershell_bootstrap("cafe1234");
1524        assert!(bootstrap.contains("Remove-Module PSReadLine"), "{bootstrap}");
1525        assert!(bootstrap.contains("function global:prompt"), "{bootstrap}");
1526        assert!(bootstrap.contains("──➤cafe1234:$code "), "{bootstrap}");
1527        assert!(bootstrap.contains("$global:LASTEXITCODE = 0"), "{bootstrap}");
1528        assert!(!bootstrap.contains('\n'), "bootstrap must be a single input line");
1529    }
1530
1531    #[test]
1532    fn parses_exit_code_from_prompt_marker() {
1533        let end = "──➤cafe1234";
1534        assert_eq!(PtyShell::parse_prompt_exit_code("ok\n◉ /x──➤cafe1234:0 ", end), Some(0));
1535        assert_eq!(PtyShell::parse_prompt_exit_code("oops\n◉ /x──➤cafe1234:1 ", end), Some(1));
1536        assert_eq!(PtyShell::parse_prompt_exit_code("◉ /x──➤cafe1234:42 ", end), Some(42));
1537        // A record split by a read boundary inside the digits is still in flight.
1538        assert_eq!(PtyShell::parse_prompt_exit_code("◉ /x──➤cafe1234:1", end), None);
1539        assert_eq!(PtyShell::parse_prompt_exit_code("◉ /x──➤cafe1234:127", end), None);
1540        assert_eq!(PtyShell::parse_prompt_exit_code("◉ /x──➤cafe1234:127 ", end), Some(127));
1541        // ConPTY may replace the trailing space with a cursor move.
1542        assert_eq!(PtyShell::parse_prompt_exit_code("◉ /x──➤cafe1234:127\u{1b}[C", end), Some(127));
1543        assert_eq!(PtyShell::parse_prompt_exit_code("◉ /x──➤cafe1234:0\u{1b}[K", end), Some(0));
1544        assert_eq!(PtyShell::parse_prompt_exit_code("◉ /x──➤cafe1234:-1 ", end), Some(-1));
1545        assert_eq!(PtyShell::parse_prompt_exit_code("◉ /x──➤cafe1234:12a ", end), None);
1546        // still running (no completion prompt yet) -> None
1547        assert_eq!(PtyShell::parse_prompt_exit_code("building...", end), None);
1548        // forged with the wrong nonce -> None
1549        assert_eq!(PtyShell::parse_prompt_exit_code("◉ /x──➤wrong:0 ", end), None);
1550    }
1551
1552    use proptest::prelude::*;
1553
1554    proptest! {
1555        // Exit-code parsing runs on untrusted program output — arbitrary text
1556        // (and a forgeable marker) must never panic, only ever return None or a
1557        // parsed i32.
1558        #[test]
1559        fn parse_prompt_exit_code_never_panics(
1560            text in prop::collection::vec(any::<char>(), 0..256),
1561            nonce in "[0-9a-f]{0,16}",
1562        ) {
1563            let s: String = text.into_iter().collect();
1564            let end = format!("{WCGW_PROMPT_END}{nonce}");
1565            // Must not panic; any Option<i32> is acceptable.
1566            let _ = PtyShell::parse_prompt_exit_code(&s, &end);
1567        }
1568
1569        // A well-formed marker round-trips the embedded code for any i32.
1570        #[test]
1571        fn parse_prompt_exit_code_round_trips(code in any::<i32>(), nonce in "[0-9a-f]{1,16}") {
1572            let end = format!("{WCGW_PROMPT_END}{nonce}");
1573            let line = format!("output line\n{WCGW_PROMPT_PATTERN} /home/x{end}:{code} ");
1574            prop_assert_eq!(PtyShell::parse_prompt_exit_code(&line, &end), Some(code));
1575        }
1576    }
1577
1578    #[cfg(unix)] // spawns a real shell
1579    #[test]
1580    fn test_pty_shell_creation() -> Result<()> {
1581        let temp_dir = TempDir::new()?;
1582        let result = PtyShell::new(temp_dir.path(), false);
1583        assert!(result.is_ok(), "Failed to create PTY shell: {:?}", result.err());
1584        Ok(())
1585    }
1586
1587    #[cfg(unix)] // spawns a real shell
1588    #[test]
1589    fn discard_throttle_engages_at_scratch_cap_and_resets_per_command() -> Result<()> {
1590        let temp_dir = TempDir::new()?;
1591        let mut shell = PtyShell::new(temp_dir.path(), false)?;
1592        assert!(!shell.discard_throttle.load(AtomicOrdering::Relaxed));
1593
1594        // Saturated scratch budget: the next dropped head is pure discard and
1595        // must engage reader back-pressure.
1596        shell.scratch_workspace_root = Some(temp_dir.path().to_path_buf());
1597        shell.scratch_bytes = SCRATCH_MAX_BYTES;
1598        shell.offload_dropped_head("dropped beyond the budget");
1599        assert!(shell.discard_throttle.load(AtomicOrdering::Relaxed));
1600
1601        // A new command resets scratch state and releases the throttle.
1602        shell.send_command("echo done")?;
1603        assert!(!shell.discard_throttle.load(AtomicOrdering::Relaxed));
1604        Ok(())
1605    }
1606
1607    #[cfg(unix)] // spawns a real shell
1608    #[test]
1609    fn discard_throttle_engages_when_a_write_reaches_the_cap() -> Result<()> {
1610        let temp_dir = TempDir::new()?;
1611        let mut shell = PtyShell::new(temp_dir.path(), false)?;
1612        shell.scratch_workspace_root = Some(temp_dir.path().to_path_buf());
1613        // One byte of budget left: this write saturates the cap exactly.
1614        shell.scratch_bytes = SCRATCH_MAX_BYTES - 1;
1615        shell.offload_dropped_head("xx");
1616        assert!(shell.discard_throttle.load(AtomicOrdering::Relaxed));
1617        Ok(())
1618    }
1619
1620    #[cfg(unix)] // spawns a real shell
1621    #[test]
1622    fn test_pty_shell_echo() -> Result<()> {
1623        let temp_dir = TempDir::new()?;
1624        let mut shell = PtyShell::new(temp_dir.path(), false)?;
1625
1626        shell.send_command("echo 'hello pty'")?;
1627        let (output, complete) = shell.read_output(2.0)?;
1628
1629        assert!(output.contains("hello pty"), "Output should contain 'hello pty': {output}");
1630        // The bootstrap (prompt export line, shell banner) must have been
1631        // consumed before the first command, and the first command must
1632        // already report its exit code.
1633        assert!(complete, "first command must complete: {output}");
1634        assert!(!output.contains("PROMPT_COMMAND"), "bootstrap leaked into output: {output}");
1635        assert_eq!(shell.last_exit_code, Some(0), "{output}");
1636        Ok(())
1637    }
1638
1639    #[cfg(unix)] // spawns a real shell
1640    #[test]
1641    fn agent_paths_are_exported_to_the_pty() -> Result<()> {
1642        let workspace = TempDir::new()?;
1643        let temporary_artifact_dir = workspace.path().join(".winx/tmp/session-test");
1644        let mut shell = PtyShell::new_with_agent_paths(
1645            workspace.path(),
1646            false,
1647            Some(workspace.path()),
1648            Some(&temporary_artifact_dir),
1649        )?;
1650
1651        shell.send_command("printf '%s\\n%s\\n' \"$WINX_WORKSPACE_ROOT\" \"$WINX_TEMP_DIR\"")?;
1652        let (output, _complete) = shell.read_output(2.0)?;
1653
1654        assert!(output.contains(&workspace.path().to_string_lossy().to_string()), "{output}");
1655        assert!(output.contains(&temporary_artifact_dir.to_string_lossy().to_string()), "{output}");
1656        Ok(())
1657    }
1658
1659    #[cfg(unix)] // spawns a real shell
1660    #[test]
1661    fn completed_nonblocking_poll_is_level_triggered() -> Result<()> {
1662        let temp_dir = TempDir::new()?;
1663        let mut shell = PtyShell::new(temp_dir.path(), false)?;
1664
1665        shell.send_command("true")?;
1666        let deadline = Instant::now() + Duration::from_secs(2);
1667        while Instant::now() < deadline && !shell.poll_output_nonblocking() {
1668            std::thread::sleep(Duration::from_millis(10));
1669        }
1670
1671        assert!(!shell.command_running, "shell did not complete before the deadline");
1672        assert!(
1673            shell.poll_output_nonblocking(),
1674            "a later consumer must still observe the completed state"
1675        );
1676        Ok(())
1677    }
1678
1679    #[cfg(unix)] // spawns a real shell
1680    #[test]
1681    fn test_pty_shell_pwd() -> Result<()> {
1682        let temp_dir = TempDir::new()?;
1683        let mut shell = PtyShell::new(temp_dir.path(), false)?;
1684
1685        // Simply verify shell responds to pwd command
1686        // Use single quotes like echo test for consistency
1687        shell.send_command("pwd && echo 'pwd_done'")?;
1688        let (output, _complete) = shell.read_output(2.0)?;
1689
1690        // Verify the echo marker appears (proves command executed)
1691        assert!(output.contains("pwd_done"), "Output should contain 'pwd_done': {output}");
1692        Ok(())
1693    }
1694
1695    #[cfg(unix)] // spawns a real shell
1696    #[test]
1697    fn test_pty_resize() -> Result<()> {
1698        let temp_dir = TempDir::new()?;
1699        let mut shell = PtyShell::new(temp_dir.path(), false)?;
1700
1701        let result = shell.resize(120, 40);
1702        assert!(result.is_ok());
1703
1704        let (cols, rows) = shell.get_size();
1705        assert_eq!(cols, 120);
1706        assert_eq!(rows, 40);
1707        Ok(())
1708    }
1709
1710    /// `kill(pid, 0)` probes existence without sending a signal: 0 = the pid
1711    /// exists, -1 (ESRCH) = it's gone. A freshly-killed orphan lingers briefly
1712    /// as a zombie under init until reaped, so callers poll.
1713    #[cfg(unix)]
1714    fn pid_alive(pid: i32) -> bool {
1715        u32::try_from(pid).is_ok_and(crate::os::unix::process_exists)
1716    }
1717
1718    #[cfg(unix)]
1719    #[test]
1720    fn dropping_shell_kills_orphaned_background_child() -> Result<()> {
1721        // A background job the shell starts must not outlive the shell. Spawn a
1722        // long `sleep` in the background, record its pid, drop the shell, and
1723        // confirm the sleep is gone - proving the group-kill reached past the
1724        // shell to a child `Child::kill` alone would have orphaned.
1725        let dir = TempDir::new()?;
1726        let pidfile = dir.path().join("child.pid");
1727        let mut shell = PtyShell::new(dir.path(), false)?;
1728
1729        shell
1730            .send_command(&format!("sleep 300 & echo $! > {} ; echo spawned", pidfile.display()))?;
1731
1732        // The PTY echoes the input line, so `out` containing "spawned" only proves
1733        // the line was sent - not that bash ran it. Under CI load bash can lag, so
1734        // poll the pidfile (it only appears once `echo $! > pidfile` executes) while
1735        // draining the PTY, instead of trusting the echo and racing the redirect.
1736        let mut child_pid = None;
1737        for _ in 0..150 {
1738            let _ = shell.read_output(0.1);
1739            if let Some(pid) =
1740                std::fs::read_to_string(&pidfile).ok().and_then(|c| c.trim().parse::<i32>().ok())
1741            {
1742                child_pid = Some(pid);
1743                break;
1744            }
1745            thread::sleep(Duration::from_millis(20));
1746        }
1747        let child_pid =
1748            child_pid.ok_or_else(|| anyhow!("background child pid never materialized"))?;
1749        assert!(pid_alive(child_pid), "background child should be running before drop");
1750
1751        drop(shell);
1752
1753        // The group-kill plus init reaping the orphan are async w.r.t. us; poll.
1754        let mut gone = false;
1755        for _ in 0..150 {
1756            if !pid_alive(child_pid) {
1757                gone = true;
1758                break;
1759            }
1760            thread::sleep(Duration::from_millis(20));
1761        }
1762        assert!(gone, "background child {child_pid} survived shell teardown (orphan leak)");
1763        Ok(())
1764    }
1765}