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        if shell_kind.is_powershell() {
744            // PSReadLine initializes asynchronously after the first prompt
745            // (it queries the cursor position first). Input written before
746            // that lands in its line editor with the Enter keys dropped, so
747            // the bootstrap and the first command fuse into one unsubmitted
748            // line. Wait for the default `PS ...>` prompt before typing.
749            self.wait_for_initial_powershell_prompt();
750        }
751        self.write_command(&prompt_statement)?;
752
753        // Wait for the first marker-bearing prompt instead of a fixed pause:
754        // everything before it (the shell's startup banner, the echoed
755        // bootstrap line) must never leak into the first command's output, and
756        // Git for Windows bash reaches its first prompt far later than Linux
757        // bash. Once the marker is seen, a short drain swallows the trailing
758        // bytes of that same prompt.
759        let deadline = Instant::now() + PROMPT_BOOTSTRAP_TIMEOUT;
760        let mut bootstrap = String::new();
761        let mut settled = false;
762        while Instant::now() < deadline {
763            match self.output_rx.recv_timeout(Duration::from_millis(50)) {
764                Ok(chunk) => {
765                    self.answer_terminal_queries(&chunk);
766                    bootstrap.push_str(&chunk);
767                    if Self::check_prompt_complete(&bootstrap, &self.prompt_end_marker) {
768                        settled = true;
769                        break;
770                    }
771                }
772                Err(mpsc::RecvTimeoutError::Timeout) => {}
773                Err(mpsc::RecvTimeoutError::Disconnected) => break,
774            }
775        }
776        if settled {
777            std::thread::sleep(Duration::from_millis(30));
778        } else {
779            warn!(
780                timeout_ms = PROMPT_BOOTSTRAP_TIMEOUT.as_millis(),
781                "PTY shell did not print its first prompt in time; continuing anyway"
782            );
783        }
784        bootstrap.push_str(&self.drain_output());
785        debug!(
786            bytes = bootstrap.len(),
787            settled,
788            child_pid = ?self.child.process_id(),
789            "PTY prompt bootstrap drained"
790        );
791
792        Ok(())
793    }
794
795    /// Block until PowerShell has drawn its initial prompt (or the bootstrap
796    /// timeout elapses), answering cursor-position queries on the way.
797    fn wait_for_initial_powershell_prompt(&mut self) {
798        let deadline = Instant::now() + PROMPT_BOOTSTRAP_TIMEOUT;
799        let mut seen = String::new();
800        while Instant::now() < deadline {
801            match self.output_rx.recv_timeout(Duration::from_millis(50)) {
802                Ok(chunk) => {
803                    self.answer_terminal_queries(&chunk);
804                    seen.push_str(&chunk);
805                    let clean = crate::state::terminal::strip_ansi_codes(&seen);
806                    if clean.contains("> ") || clean.contains(">\u{a0}") {
807                        // Give PSReadLine a moment to finish arming its input loop.
808                        std::thread::sleep(Duration::from_millis(100));
809                        return;
810                    }
811                }
812                Err(mpsc::RecvTimeoutError::Timeout) => {}
813                Err(mpsc::RecvTimeoutError::Disconnected) => return,
814            }
815        }
816        warn!(
817            timeout_ms = PROMPT_BOOTSTRAP_TIMEOUT.as_millis(),
818            "PowerShell did not draw its initial prompt in time; sending the bootstrap anyway"
819        );
820    }
821
822    /// Answer terminal queries the console host blocks on.
823    ///
824    /// Windows `ConPTY` is created with `INHERIT_CURSOR` (portable-pty's default)
825    /// and then asks the "terminal" for the cursor position with `ESC[6n`
826    /// before rendering a single byte of the child's output. Winx is that
827    /// terminal, so it must reply with a cursor position report or every shell
828    /// stays silent forever. The reply is harmless on Unix, where no PTY layer
829    /// issues the query.
830    fn answer_terminal_queries(&mut self, chunk: &str) {
831        const CURSOR_POSITION_REQUEST: &str = "\x1b[6n";
832        if !chunk.contains(CURSOR_POSITION_REQUEST) {
833            return;
834        }
835        debug!("PTY answered a cursor position request");
836        if let Err(error) = self.writer.write_all(b"\x1b[1;1R").and_then(|()| self.writer.flush()) {
837            debug!("PTY cursor position report failed: {error}");
838        }
839    }
840
841    /// Write a command to the PTY, submitting it with a carriage return.
842    fn write_command(&mut self, command: &str) -> Result<()> {
843        // Submit with `\r`, matching the foreground path (`send_special_key("Enter")`
844        // also sends `\r`) and a real terminal's Enter key. The two paths used to
845        // disagree — background sent `\n` here, foreground sent `\r` — which is a
846        // real difference for readline-based TUIs. bash's canonical line discipline
847        // maps CR to NL (ICRNL), so plain commands behave identically.
848        let cmd_with_newline = format!("{command}\r");
849        self.writer.write_all(cmd_with_newline.as_bytes()).context("Failed to write to PTY")?;
850        self.writer.flush().context("Failed to flush PTY")?;
851        Ok(())
852    }
853
854    /// Drain any pending output from the PTY channel
855    fn drain_output(&mut self) -> String {
856        let mut output = String::new();
857        let deadline = Instant::now() + Duration::from_millis(200);
858
859        // Drain all available output from the channel
860        while Instant::now() < deadline {
861            match self.output_rx.try_recv() {
862                Ok(chunk) => {
863                    self.answer_terminal_queries(&chunk);
864                    output.push_str(&chunk);
865
866                    // Prevent runaway reads
867                    if output.len() > self.max_output_size {
868                        self.output_truncated = true;
869                        break;
870                    }
871                }
872                Err(TryRecvError::Empty) => {
873                    // No more data, wait briefly for more
874                    thread::sleep(Duration::from_millis(10));
875                }
876                Err(TryRecvError::Disconnected) => {
877                    // Reader thread died
878                    break;
879                }
880            }
881        }
882
883        output
884    }
885
886    /// Send a command to the shell and start reading output
887    pub fn send_command(&mut self, command: &str) -> Result<()> {
888        debug!(bytes = command.len(), "PTY sending command");
889
890        // Clear previous state
891        self.output_buffer.clear();
892        self.output_truncated = false;
893        self.reset_scratch();
894        self.last_command = command.to_string();
895        self.command_running = true;
896        self.mark_command_started();
897        self.last_exit_code = None;
898        // A new command means the next status_check should return whatever
899        // shows up — drop the dedup hash so we don't elide the first response.
900        self.last_returned_hash = None;
901        self.delivered_output.clear();
902        // Drop retained OSC title/progress so the previous foreground
903        // program's last title can't masquerade as this command's turn state.
904        self.live.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clear_osc();
905
906        // Write the command
907        self.write_command(command)?;
908
909        Ok(())
910    }
911
912    /// Start the monotonic runtime clock for a newly submitted command.
913    pub fn mark_command_started(&mut self) {
914        self.command_generation = self.command_generation.saturating_add(1);
915        self.command_started_at = Some(Instant::now());
916        self.pending_completion_report = true;
917    }
918
919    /// Whether the most recent foreground command has finished without any
920    /// response having reported its exit yet.
921    pub fn completion_report_pending(&self) -> bool {
922        !self.command_running && self.pending_completion_report
923    }
924
925    /// Record that a response reported the current command as finished.
926    pub fn mark_completion_reported(&mut self) {
927        self.pending_completion_report = false;
928    }
929
930    pub fn command_generation(&self) -> u64 {
931        self.command_generation
932    }
933
934    pub fn incarnation(&self) -> u64 {
935        self.incarnation
936    }
937
938    /// Elapsed runtime since the current command was submitted.
939    pub fn command_elapsed(&self) -> Option<Duration> {
940        self.command_started_at.map(|started_at| started_at.elapsed())
941    }
942
943    /// Current working directory last reported by this shell's prompt.
944    pub fn current_cwd(&self) -> &Path {
945        &self.current_cwd
946    }
947
948    /// Snapshot used as the left-hand side of incremental output rendering.
949    pub fn delivered_output(&self) -> String {
950        self.delivered_output.clone()
951    }
952
953    /// Mark the cumulative output snapshot as delivered after rendering it.
954    pub fn mark_output_delivered(&mut self, output: &str) {
955        self.delivered_output.clear();
956        self.delivered_output.push_str(output);
957    }
958
959    /// Return up to `lines` recent lines from the scrollback ring, oldest
960    /// first. When older lines were evicted or a long unterminated line was
961    /// clipped, a `[winx: …]` notice is prepended so the caller knows the
962    /// scrollback is incomplete rather than silently receiving less than asked.
963    pub fn collect_scrollback(&self, lines: usize) -> String {
964        // The ring holds raw PTY lines. Replay them through the terminal
965        // emulator so cursor movements (readline echo, in-place redraws) are
966        // *applied* — not merely stripped — yielding what the screen actually
967        // showed. A plain strip can't undo a `\x1b[D`, so it would leave
968        // `>>> p>>> pr>>> pri...` echo noise behind; the emulator collapses it.
969        let rendered =
970            crate::state::terminal::render_terminal_output(&self.ring.raw(lines)).join("\n");
971        match self.ring.scrollback_notice(lines) {
972            Some(notice) => format!("{notice}\n{rendered}"),
973            None => rendered,
974        }
975    }
976
977    /// Hash arbitrary rendered output into a u64 dedup key.
978    pub fn fingerprint(text: &str) -> u64 {
979        let mut hasher = DefaultHasher::new();
980        text.hash(&mut hasher);
981        hasher.finish()
982    }
983
984    /// Read output from the PTY with timeout
985    ///
986    /// Returns (output, `is_complete`) tuple where `is_complete` indicates
987    /// whether the command has finished (prompt detected)
988    pub fn read_output(&mut self, timeout_secs: f32) -> Result<(String, bool)> {
989        let timeout = Duration::from_secs_f32(timeout_secs.clamp(0.1, 60.0));
990        let start = Instant::now();
991        let mut complete = false;
992        let mut no_data_count = 0;
993        let mut prompt_detected_at: Option<Instant> = None;
994
995        while start.elapsed() < timeout {
996            match self.output_rx.try_recv() {
997                Ok(chunk) => {
998                    self.answer_terminal_queries(&chunk);
999                    self.output_buffer.push_str(&chunk);
1000                    self.ring.push_chunk(&chunk);
1001                    no_data_count = 0;
1002
1003                    // Check for WCGW prompt indicating command completion
1004                    if prompt_detected_at.is_none()
1005                        && (Self::check_prompt_complete(&chunk, &self.prompt_end_marker)
1006                            || Self::check_prompt_complete(
1007                                &self.output_buffer,
1008                                &self.prompt_end_marker,
1009                            ))
1010                    {
1011                        prompt_detected_at = Some(Instant::now());
1012                        debug!("Prompt detected, draining remaining output...");
1013                    }
1014
1015                    // Truncate if too large (offloads the dropped head to scratch).
1016                    self.truncate_output_buffer_with_offload();
1017                }
1018                Err(TryRecvError::Empty) => {
1019                    // No data available, wait briefly
1020                    thread::sleep(Duration::from_millis(10));
1021                    no_data_count += 1;
1022
1023                    // If prompt was detected, check if we've drained long enough
1024                    if let Some(detected_time) = prompt_detected_at {
1025                        // Wait 100ms after prompt detection to capture any trailing output
1026                        if detected_time.elapsed() > Duration::from_millis(100) {
1027                            complete = true;
1028                            debug!("Command completed - prompt detected and drained");
1029                            break;
1030                        }
1031                    } else if no_data_count > 10
1032                        && Self::check_prompt_complete(&self.output_buffer, &self.prompt_end_marker)
1033                    {
1034                        // Prompt detected during empty reads
1035                        prompt_detected_at = Some(Instant::now());
1036                        debug!("Prompt detected after wait, draining...");
1037                    }
1038                }
1039                Err(TryRecvError::Disconnected) => {
1040                    // Reader thread died - PTY closed
1041                    warn!("PTY reader disconnected");
1042                    complete = true;
1043                    break;
1044                }
1045            }
1046        }
1047
1048        if complete || prompt_detected_at.is_some() {
1049            self.command_running = false;
1050            self.last_exit_code =
1051                Self::parse_prompt_exit_code(&self.output_buffer, &self.prompt_end_marker);
1052            self.update_current_cwd_from_prompt();
1053            complete = true;
1054        }
1055
1056        Ok((self.output_buffer.clone(), complete))
1057    }
1058
1059    /// Non-blocking drain of whatever the reader thread has already queued.
1060    ///
1061    /// Unlike [`read_output`](Self::read_output), this never sleeps: it consumes
1062    /// every chunk currently available, updates prompt/completion state, and
1063    /// returns immediately. `prune_finished_shells` uses it so the global
1064    /// background-shell lock is never held across a blocking 100ms `read_output`.
1065    /// Returns `true` if the command has completed (prompt seen or PTY closed).
1066    pub fn poll_output_nonblocking(&mut self) -> bool {
1067        let mut prompt_seen = false;
1068        loop {
1069            match self.output_rx.try_recv() {
1070                Ok(chunk) => {
1071                    self.answer_terminal_queries(&chunk);
1072                    let chunk_has_prompt =
1073                        Self::check_prompt_complete(&chunk, &self.prompt_end_marker);
1074                    self.output_buffer.push_str(&chunk);
1075                    self.ring.push_chunk(&chunk);
1076                    if chunk_has_prompt
1077                        || Self::check_prompt_complete(&self.output_buffer, &self.prompt_end_marker)
1078                    {
1079                        prompt_seen = true;
1080                    }
1081                    self.truncate_output_buffer_with_offload();
1082                }
1083                Err(TryRecvError::Empty) => break,
1084                Err(TryRecvError::Disconnected) => {
1085                    self.command_running = false;
1086                    return true;
1087                }
1088            }
1089        }
1090        if prompt_seen {
1091            self.command_running = false;
1092            self.last_exit_code =
1093                Self::parse_prompt_exit_code(&self.output_buffer, &self.prompt_end_marker);
1094            self.update_current_cwd_from_prompt();
1095        }
1096        // Completion is state, not an edge. Another consumer (notably the
1097        // background reaper) may have drained the prompt first; a later poll
1098        // must still report the already-idle shell as complete even when this
1099        // particular drain saw no new prompt bytes.
1100        !self.command_running
1101    }
1102
1103    fn update_current_cwd_from_prompt(&mut self) {
1104        let Some(last) =
1105            self.output_buffer.lines().rev().find(|line| line.contains(&self.prompt_end_marker))
1106        else {
1107            return;
1108        };
1109        let clean = crate::state::terminal::strip_ansi_codes(last);
1110        let Some((before_marker, _)) = clean.rsplit_once(&self.prompt_end_marker) else {
1111            return;
1112        };
1113        let Some((_, cwd)) = before_marker.rsplit_once("◉ ") else {
1114            return;
1115        };
1116        let cwd = cwd.trim();
1117        if !cwd.is_empty() {
1118            self.current_cwd = native_cwd_from_prompt(cwd);
1119        }
1120    }
1121
1122    /// Snapshot of the accumulated output buffer — the same text `read_output`
1123    /// returns. Lets callers poll non-blocking (`poll_output_nonblocking`) and
1124    /// grab the buffer once at the end instead of cloning it on every slice.
1125    pub fn output_snapshot(&self) -> String {
1126        self.output_buffer.clone()
1127    }
1128
1129    /// Check if the output ends with this shell's prompt.
1130    ///
1131    /// `prompt_end` is the per-shell `──➤<nonce>` suffix. Anchoring on the LAST
1132    /// non-empty line (not a global `contains`) plus the random nonce means
1133    /// command output that happens to print the prompt glyphs mid-stream — or
1134    /// even a forged `◉ x──➤ ` at end of line — can't be mistaken for the prompt
1135    /// and truncate output or end the command early.
1136    fn check_prompt_complete(text: &str, prompt_end: &str) -> bool {
1137        Self::parse_prompt_exit_code(text, prompt_end).is_some()
1138    }
1139
1140    /// If the last non-empty line is this shell's completion prompt
1141    /// (`◉ <pwd>──➤<nonce>:<code>`), return the exit code that follows the
1142    /// marker. Returns `None` when the prompt isn't present — which is exactly
1143    /// "the command is still running". The per-shell nonce plus the structured
1144    /// `:<digits>` suffix keep command output from forging completion.
1145    fn parse_prompt_exit_code(text: &str, prompt_end: &str) -> Option<i32> {
1146        let last = text.lines().rev().find(|line| !line.trim().is_empty())?;
1147        if !last.contains(WCGW_PROMPT_PATTERN) {
1148            return None;
1149        }
1150        // Everything after the last "──➤<nonce>" must be ":<digits>" followed by
1151        // the prompt's own terminator — this confirms the prompt ends the line
1152        // AND yields the code. The raw tail keeps its escape sequences: a
1153        // trailing erase/cursor sequence (":0 \x1b[K", or ConPTY's ":0\x1b[C")
1154        // counts as the terminator, so it is stripped only for parsing.
1155        let raw_tail = last.rsplit_once(prompt_end)?.1;
1156        let clean_tail = crate::state::terminal::strip_ansi_codes(raw_tail);
1157        let code_text = clean_tail.strip_prefix(':')?;
1158        let digits = code_text
1159            .char_indices()
1160            .take_while(|(index, c)| c.is_ascii_digit() || (*index == 0 && *c == '-'))
1161            .count();
1162        let (code, rest) = code_text.split_at(digits);
1163        if !rest.chars().all(char::is_whitespace) {
1164            return None;
1165        }
1166        // A read boundary can fall between the digits of "127": without the
1167        // terminator the record is still in flight, and accepting "1" now would
1168        // report the wrong exit code before the rest arrives.
1169        let terminated = !rest.is_empty() || raw_tail.len() > clean_tail.len();
1170        if !terminated {
1171            return None;
1172        }
1173        code.parse::<i32>().ok()
1174    }
1175
1176    /// Point output-offload scratch files at `root` (the workspace). Idempotent;
1177    /// callers set it per command so it always tracks the current workspace.
1178    pub fn set_scratch_root(&mut self, root: &Path) {
1179        self.scratch_workspace_root = Some(root.to_path_buf());
1180    }
1181
1182    /// The scratch file holding the current command's dropped output head, if any
1183    /// was offloaded this command.
1184    pub fn scratch_path(&self) -> Option<&Path> {
1185        self.scratch_path.as_deref()
1186    }
1187
1188    /// Forget the current command's scratch file so the next command starts a
1189    /// fresh one. Does not delete the file (pruned later by age).
1190    pub fn reset_scratch(&mut self) {
1191        self.scratch_path = None;
1192        self.scratch_bytes = 0;
1193        self.discard_throttle.store(false, AtomicOrdering::Relaxed);
1194    }
1195
1196    /// Append a just-dropped output `head` to the per-command scratch file so the
1197    /// agent can recover it via `ReadFiles`. Best-effort: needs a known workspace
1198    /// root, stops at `SCRATCH_MAX_BYTES`, and swallows IO errors.
1199    fn offload_dropped_head(&mut self, head: &str) {
1200        let Some(root) = self.scratch_workspace_root.clone() else {
1201            return;
1202        };
1203        // Clamp to the remaining byte budget so the file honors SCRATCH_MAX_BYTES
1204        // exactly (a single head can be up to keep_size, ~500 KB). Snap to a char
1205        // boundary so we never slice mid-UTF-8.
1206        let remaining = SCRATCH_MAX_BYTES.saturating_sub(self.scratch_bytes);
1207        if remaining == 0 {
1208            // From here on the head is discarded outright — reading faster
1209            // only burns CPU. Engage reader back-pressure until the next
1210            // command resets the scratch state.
1211            self.discard_throttle.store(true, AtomicOrdering::Relaxed);
1212            return;
1213        }
1214        let head = match usize::try_from(remaining) {
1215            Ok(rem) if rem < head.len() => &head[..crate::utils::floor_char_boundary(head, rem)],
1216            _ => head,
1217        };
1218        if self.scratch_path.is_none() {
1219            self.scratch_path = crate::utils::scratch_file::new_scratch_path(&root);
1220        }
1221        let Some(path) = self.scratch_path.clone() else {
1222            return;
1223        };
1224        match crate::utils::scratch_file::append_scratch(&path, head.as_bytes()) {
1225            Ok(0) if self.scratch_bytes == 0 => self.scratch_path = None,
1226            Ok(written) => {
1227                self.scratch_bytes = self.scratch_bytes.saturating_add(written as u64);
1228                if self.scratch_bytes >= SCRATCH_MAX_BYTES {
1229                    self.discard_throttle.store(true, AtomicOrdering::Relaxed);
1230                }
1231            }
1232            Err(e) => debug!("scratch: append to {} failed: {e}", path.display()),
1233        }
1234    }
1235
1236    /// Once `output_buffer` exceeds the cap, offload the head about to be dropped
1237    /// to the scratch file, then keep only the tail with a truncation marker.
1238    /// Shared by the blocking and non-blocking drain paths so the offload and the
1239    /// char-boundary handling live in one place.
1240    fn truncate_output_buffer_with_offload(&mut self) {
1241        if self.output_buffer.len() <= self.max_output_size {
1242            return;
1243        }
1244        self.output_truncated = true;
1245        let keep_size = self.max_output_size / 2;
1246        // Snap to a char boundary: a raw byte offset can land mid-UTF-8
1247        // (CJK/emoji/box-drawing/the prompt glyphs) and slicing there would panic.
1248        let cut = crate::utils::floor_char_boundary(
1249            &self.output_buffer,
1250            self.output_buffer.len() - keep_size,
1251        );
1252        let head = self.output_buffer[..cut].to_owned();
1253        self.offload_dropped_head(&head);
1254        // Replace the dropped head in place instead of `format!`-ing a brand-new
1255        // String: `replace_range` shifts the kept tail down once and reuses the
1256        // buffer's allocation. `cut` is already a char boundary (above), and 0 is
1257        // always one, so the range is valid.
1258        self.output_buffer.replace_range(..cut, "\n(...output truncated...)\n");
1259    }
1260
1261    /// Send Ctrl+C (interrupt) to the PTY
1262    pub fn send_interrupt(&mut self) -> Result<()> {
1263        debug!("PTY sending Ctrl+C");
1264        self.writer
1265            .write_all(&[0x03]) // ASCII ETX (Ctrl+C)
1266            .context("Failed to send Ctrl+C")?;
1267        self.writer.flush()?;
1268        Ok(())
1269    }
1270
1271    /// Send Ctrl+D (EOF) to the PTY
1272    pub fn send_eof(&mut self) -> Result<()> {
1273        debug!("PTY sending Ctrl+D");
1274        self.writer
1275            .write_all(&[0x04]) // ASCII EOT (Ctrl+D)
1276            .context("Failed to send Ctrl+D")?;
1277        self.writer.flush()?;
1278        Ok(())
1279    }
1280
1281    /// Send Ctrl+Z (suspend) to the PTY
1282    pub fn send_suspend(&mut self) -> Result<()> {
1283        debug!("PTY sending Ctrl+Z");
1284        self.writer
1285            .write_all(&[0x1A]) // ASCII SUB (Ctrl+Z)
1286            .context("Failed to send Ctrl+Z")?;
1287        self.writer.flush()?;
1288        Ok(())
1289    }
1290
1291    /// Send text directly to the PTY (for interactive input)
1292    pub fn send_text(&mut self, text: &str) -> Result<()> {
1293        debug!(bytes = text.len(), "PTY sending text");
1294        self.send_bytes(text.as_bytes()).context("Failed to send text")?;
1295        Ok(())
1296    }
1297
1298    /// Send raw bytes directly to the PTY.
1299    pub fn send_bytes(&mut self, bytes: &[u8]) -> Result<()> {
1300        self.writer.write_all(bytes).context("Failed to send bytes")?;
1301        self.writer.flush()?;
1302        Ok(())
1303    }
1304
1305    /// Send a special key sequence
1306    pub fn send_special_key(&mut self, key: &str) -> Result<()> {
1307        let bytes: &[u8] = match key {
1308            "Enter" => b"\r",
1309            "Tab" => b"\t",
1310            "Backspace" => b"\x7F",
1311            "Escape" => b"\x1B",
1312            "Up" | "KeyUp" => b"\x1B[A",
1313            "Down" | "KeyDown" => b"\x1B[B",
1314            "Right" | "KeyRight" => b"\x1B[C",
1315            "Left" | "KeyLeft" => b"\x1B[D",
1316            "Home" => b"\x1B[H",
1317            "End" => b"\x1B[F",
1318            "PageUp" => b"\x1B[5~",
1319            "PageDown" => b"\x1B[6~",
1320            "Delete" => b"\x1B[3~",
1321            "Insert" => b"\x1B[2~",
1322            "CtrlC" | "Ctrl-C" => b"\x03",
1323            "CtrlD" | "Ctrl-D" => b"\x04",
1324            "CtrlZ" | "Ctrl-Z" => b"\x1A",
1325            "CtrlL" | "Ctrl-L" => b"\x0C",
1326            _ => return Err(anyhow!("Unknown special key: {key}")),
1327        };
1328
1329        debug!("PTY sending special key: {} ({:?})", key, bytes);
1330        self.send_bytes(bytes)?;
1331        Ok(())
1332    }
1333
1334    /// Snapshot the live terminal screen — a stable, consolidated view of what a
1335    /// human would currently see, with cursor moves/redraws applied and ANSI
1336    /// stripped. `max_lines` of 0 returns the full screen buffer. This is the
1337    /// foundation for piloting interactive TUIs (the `claude` CLI, vim, ...).
1338    pub fn live_snapshot(&self, max_lines: usize) -> Vec<String> {
1339        // Recover from a poisoned lock instead of returning a blank screen
1340        // forever — a single panic while holding `live` would otherwise wedge
1341        // every future snapshot (and `wait_for_turn`/`screen` with it).
1342        self.live.lock().unwrap_or_else(std::sync::PoisonError::into_inner).snapshot(max_lines)
1343    }
1344
1345    /// Whether the live terminal is currently on the alternate screen buffer
1346    /// (a full-screen app like vim/htop/less is running).
1347    pub fn live_in_alt_screen(&self) -> bool {
1348        self.live.lock().unwrap_or_else(std::sync::PoisonError::into_inner).in_alt_screen()
1349    }
1350
1351    /// The latest OSC 0/2 window title emitted by the foreground program (`""`
1352    /// when none) — an out-of-band turn signal for the manifest recognizers
1353    /// (claude/codex render a spinner glyph in the title while generating).
1354    pub fn live_osc_title(&self) -> String {
1355        self.live.lock().unwrap_or_else(std::sync::PoisonError::into_inner).osc_title().to_string()
1356    }
1357
1358    /// The latest OSC 9 payload after `9;` (`""` when none) — ConEmu-style
1359    /// progress reads `4;<state>;<percent>`.
1360    pub fn live_osc_progress(&self) -> String {
1361        self.live
1362            .lock()
1363            .unwrap_or_else(std::sync::PoisonError::into_inner)
1364            .osc_progress()
1365            .to_string()
1366    }
1367
1368    /// Cursor position `(row, col)` on the live screen (0-based), so a piloting
1369    /// agent knows where focus is in a menu/form. `(0, 0)` if the lock is poisoned.
1370    pub fn live_cursor_position(&self) -> (u16, u16) {
1371        self.live.lock().unwrap_or_else(std::sync::PoisonError::into_inner).cursor_position()
1372    }
1373
1374    /// Diff the live screen against what the client last saw, returning only the
1375    /// changed lines when the change is small (huge token savings over many
1376    /// polls). Updates the baseline as a side effect. See [`ScreenUpdate`].
1377    pub fn live_snapshot_diff(&self, max_lines: usize, threshold: usize) -> ScreenUpdate {
1378        self.live
1379            .lock()
1380            .unwrap_or_else(std::sync::PoisonError::into_inner)
1381            .snapshot_diff(max_lines, threshold)
1382    }
1383
1384    /// Resize the terminal
1385    pub fn resize(&mut self, cols: u16, rows: u16) -> Result<()> {
1386        debug!("PTY resizing to {}x{}", cols, rows);
1387
1388        let new_size = PtySize { rows, cols, pixel_width: 0, pixel_height: 0 };
1389
1390        self.master.resize(new_size).context("Failed to resize PTY")?;
1391
1392        // Keep the live emulator's viewport in lockstep with the PTY size.
1393        self.live.lock().unwrap_or_else(std::sync::PoisonError::into_inner).resize(rows, cols);
1394
1395        self.size = new_size;
1396        Ok(())
1397    }
1398
1399    /// Get current terminal size
1400    pub fn get_size(&self) -> (u16, u16) {
1401        (self.size.cols, self.size.rows)
1402    }
1403
1404    /// OS process id of the shell that owns this PTY.
1405    pub fn process_id(&self) -> Option<u32> {
1406        self.child.process_id()
1407    }
1408
1409    /// Check if the shell is still alive
1410    pub fn is_alive(&mut self) -> bool {
1411        self.child.try_wait().is_ok_and(|status| status.is_none())
1412    }
1413}
1414
1415/// Thread-safe wrapper for `PtyShell`
1416pub type SharedPtyShell = Arc<Mutex<Option<PtyShell>>>;
1417
1418/// Create a new shared PTY shell
1419pub fn create_shared_pty(initial_dir: &Path, restricted_mode: bool) -> Result<SharedPtyShell> {
1420    let shell = PtyShell::new(initial_dir, restricted_mode)?;
1421    Ok(Arc::new(Mutex::new(Some(shell))))
1422}
1423
1424/// Split a byte slice into the longest valid-UTF-8 prefix (decoded) and the
1425/// trailing bytes of an incomplete final char (to carry into the next read).
1426/// Genuinely invalid sequences become a single U+FFFD and are consumed, so the
1427/// carry only ever holds a recoverable incomplete tail and never grows unbounded.
1428///
1429/// Iterative on purpose: a recursive version blows the reader thread's stack on
1430/// a burst of invalid bytes (e.g. `cat`-ing a binary), which aborts under
1431/// `panic = "abort"`. This stays O(1) in stack depth regardless of input.
1432fn decode_keep_incomplete(bytes: &[u8]) -> (String, Vec<u8>) {
1433    let mut decoded = String::new();
1434    let mut rest = bytes;
1435    loop {
1436        match std::str::from_utf8(rest) {
1437            Ok(text) => {
1438                decoded.push_str(text);
1439                return (decoded, Vec::new());
1440            }
1441            Err(error) => {
1442                let valid = error.valid_up_to();
1443                // `rest[..valid]` is valid UTF-8 by construction (no allocation
1444                // for the borrowed case).
1445                decoded.push_str(&String::from_utf8_lossy(&rest[..valid]));
1446                match error.error_len() {
1447                    // Incomplete final char: keep the tail for the next read.
1448                    None => return (decoded, rest[valid..].to_vec()),
1449                    // Genuinely invalid run: emit one replacement and skip past it.
1450                    Some(bad) => {
1451                        decoded.push('\u{FFFD}');
1452                        rest = &rest[valid + bad..];
1453                    }
1454                }
1455            }
1456        }
1457    }
1458}
1459
1460#[cfg(test)]
1461mod tests {
1462    use super::*;
1463    #[cfg(unix)] // only the shell-spawning tests need a workspace
1464    use tempfile::TempDir;
1465
1466    #[test]
1467    fn decode_passes_clean_utf8_through() {
1468        let (text, carry) = decode_keep_incomplete("hello ✓ café".as_bytes());
1469        assert_eq!(text, "hello ✓ café");
1470        assert!(carry.is_empty(), "expected empty carry");
1471    }
1472
1473    #[test]
1474    fn decode_carries_incomplete_trailing_char_across_reads() {
1475        // "é" is 0xC3 0xA9; a read boundary splits it. The first half must NOT
1476        // turn into U+FFFD — it's held and completed on the next read.
1477        let (text1, carry1) = decode_keep_incomplete(&[b'a', 0xC3]);
1478        assert_eq!(text1, "a");
1479        assert_eq!(carry1, vec![0xC3]);
1480
1481        let mut next = carry1;
1482        next.push(0xA9); // continuation byte arrives in the next read
1483        let (text2, carry2) = decode_keep_incomplete(&next);
1484        assert_eq!(text2, "é");
1485        assert!(carry2.is_empty(), "expected empty carry2");
1486    }
1487
1488    #[test]
1489    fn decode_replaces_genuinely_invalid_bytes() {
1490        // 0xFF is never valid UTF-8 and is not an incomplete prefix.
1491        let (text, carry) = decode_keep_incomplete(&[b'x', 0xFF, b'y']);
1492        assert_eq!(text, "x\u{FFFD}y");
1493        assert!(carry.is_empty(), "expected empty carry");
1494    }
1495
1496    #[test]
1497    fn decode_handles_large_invalid_burst_without_overflow() {
1498        // Regression: the first (recursive) version blew the stack — one frame
1499        // per invalid byte — and aborted under panic="abort" on a binary dump.
1500        // The iterative version must handle far more than the 4KB reader buffer.
1501        let big = vec![0xFFu8; 200_000];
1502        let (text, carry) = decode_keep_incomplete(&big);
1503        assert!(carry.is_empty(), "expected empty carry");
1504        assert_eq!(text.chars().filter(|&c| c == '\u{FFFD}').count(), 200_000);
1505    }
1506
1507    #[test]
1508    fn screen_session_name_parser_is_strict() {
1509        assert_eq!(super::winx_creator_pid("winx-123-456"), Some(123));
1510        assert_eq!(super::winx_creator_pid("winx-nope-456"), None);
1511        assert_eq!(super::winx_creator_pid("other-123-456"), None);
1512    }
1513
1514    #[cfg(unix)]
1515    #[test]
1516    fn process_probe_recognizes_current_process_and_rejects_reserved_pids() {
1517        assert!(super::process_exists(std::process::id()));
1518        assert!(!super::process_exists(0));
1519        assert!(!super::process_exists(1));
1520    }
1521
1522    #[test]
1523    fn msys_paths_convert_to_native_drives() {
1524        use super::msys_to_native;
1525        assert_eq!(msys_to_native("/c/Users/x/ws"), Some(PathBuf::from("C:\\Users\\x\\ws")));
1526        assert_eq!(msys_to_native("/cygdrive/d/work"), Some(PathBuf::from("D:\\work")));
1527        assert_eq!(msys_to_native("/c"), Some(PathBuf::from("C:\\")));
1528        assert_eq!(msys_to_native("/home/x"), None);
1529        assert_eq!(msys_to_native("relative"), None);
1530    }
1531
1532    #[test]
1533    fn prompt_detection_is_suffix_anchored() {
1534        // Per-shell nonce + exit code after the arrow: `──➤<nonce>:<code>`.
1535        let end = "──➤deadbeefcafe0001";
1536        // real prompt on the last line -> complete
1537        assert!(PtyShell::check_prompt_complete("out\nmore\n◉ /home/x──➤deadbeefcafe0001:0 ", end));
1538        // prompt with trailing ANSI erase -> still complete
1539        assert!(PtyShell::check_prompt_complete("◉ /home/x──➤deadbeefcafe0001:0 \u{1b}[K", end));
1540        // the bug: ◉ and ──➤ appear MID-output, last line is normal -> NOT complete
1541        assert!(!PtyShell::check_prompt_complete(
1542            "menu: ◉ start ──➤deadbeefcafe0001 stop\nstill running",
1543            end
1544        ));
1545        // command echoed after the prompt (not the waiting prompt) -> not complete
1546        assert!(!PtyShell::check_prompt_complete("◉ /home/x──➤deadbeefcafe0001:0 ls -la", end));
1547        // no prompt at all
1548        assert!(!PtyShell::check_prompt_complete("just some output\n", end));
1549        // the nonce's payoff: output that forges the bare glyphs but NOT the
1550        // nonce (or omits the exit code) must not be mistaken for the prompt.
1551        assert!(!PtyShell::check_prompt_complete("◉ /fake──➤ ", end));
1552        assert!(!PtyShell::check_prompt_complete("◉ /fake──➤wrongnonce:0 ", end));
1553        assert!(!PtyShell::check_prompt_complete("◉ /home/x──➤deadbeefcafe0001 ", end));
1554    }
1555
1556    #[test]
1557    fn powershell_bootstrap_defines_a_marker_prompt_without_psreadline() {
1558        let bootstrap = super::powershell_bootstrap("cafe1234");
1559        assert!(bootstrap.contains("Remove-Module PSReadLine"), "{bootstrap}");
1560        assert!(bootstrap.contains("function global:prompt"), "{bootstrap}");
1561        assert!(bootstrap.contains("──➤cafe1234:$code "), "{bootstrap}");
1562        assert!(bootstrap.contains("$global:LASTEXITCODE = 0"), "{bootstrap}");
1563        assert!(!bootstrap.contains('\n'), "bootstrap must be a single input line");
1564    }
1565
1566    #[test]
1567    fn parses_exit_code_from_prompt_marker() {
1568        let end = "──➤cafe1234";
1569        assert_eq!(PtyShell::parse_prompt_exit_code("ok\n◉ /x──➤cafe1234:0 ", end), Some(0));
1570        assert_eq!(PtyShell::parse_prompt_exit_code("oops\n◉ /x──➤cafe1234:1 ", end), Some(1));
1571        assert_eq!(PtyShell::parse_prompt_exit_code("◉ /x──➤cafe1234:42 ", end), Some(42));
1572        // A record split by a read boundary inside the digits is still in flight.
1573        assert_eq!(PtyShell::parse_prompt_exit_code("◉ /x──➤cafe1234:1", end), None);
1574        assert_eq!(PtyShell::parse_prompt_exit_code("◉ /x──➤cafe1234:127", end), None);
1575        assert_eq!(PtyShell::parse_prompt_exit_code("◉ /x──➤cafe1234:127 ", end), Some(127));
1576        // ConPTY may replace the trailing space with a cursor move.
1577        assert_eq!(PtyShell::parse_prompt_exit_code("◉ /x──➤cafe1234:127\u{1b}[C", end), Some(127));
1578        assert_eq!(PtyShell::parse_prompt_exit_code("◉ /x──➤cafe1234:0\u{1b}[K", end), Some(0));
1579        assert_eq!(PtyShell::parse_prompt_exit_code("◉ /x──➤cafe1234:-1 ", end), Some(-1));
1580        assert_eq!(PtyShell::parse_prompt_exit_code("◉ /x──➤cafe1234:12a ", end), None);
1581        // still running (no completion prompt yet) -> None
1582        assert_eq!(PtyShell::parse_prompt_exit_code("building...", end), None);
1583        // forged with the wrong nonce -> None
1584        assert_eq!(PtyShell::parse_prompt_exit_code("◉ /x──➤wrong:0 ", end), None);
1585    }
1586
1587    use proptest::prelude::*;
1588
1589    proptest! {
1590        // Exit-code parsing runs on untrusted program output — arbitrary text
1591        // (and a forgeable marker) must never panic, only ever return None or a
1592        // parsed i32.
1593        #[test]
1594        fn parse_prompt_exit_code_never_panics(
1595            text in prop::collection::vec(any::<char>(), 0..256),
1596            nonce in "[0-9a-f]{0,16}",
1597        ) {
1598            let s: String = text.into_iter().collect();
1599            let end = format!("{WCGW_PROMPT_END}{nonce}");
1600            // Must not panic; any Option<i32> is acceptable.
1601            let _ = PtyShell::parse_prompt_exit_code(&s, &end);
1602        }
1603
1604        // A well-formed marker round-trips the embedded code for any i32.
1605        #[test]
1606        fn parse_prompt_exit_code_round_trips(code in any::<i32>(), nonce in "[0-9a-f]{1,16}") {
1607            let end = format!("{WCGW_PROMPT_END}{nonce}");
1608            let line = format!("output line\n{WCGW_PROMPT_PATTERN} /home/x{end}:{code} ");
1609            prop_assert_eq!(PtyShell::parse_prompt_exit_code(&line, &end), Some(code));
1610        }
1611    }
1612
1613    #[cfg(unix)] // spawns a real shell
1614    #[test]
1615    fn test_pty_shell_creation() -> Result<()> {
1616        let temp_dir = TempDir::new()?;
1617        let result = PtyShell::new(temp_dir.path(), false);
1618        assert!(result.is_ok(), "Failed to create PTY shell: {:?}", result.err());
1619        Ok(())
1620    }
1621
1622    #[cfg(unix)] // spawns a real shell
1623    #[test]
1624    fn discard_throttle_engages_at_scratch_cap_and_resets_per_command() -> Result<()> {
1625        let temp_dir = TempDir::new()?;
1626        let mut shell = PtyShell::new(temp_dir.path(), false)?;
1627        assert!(!shell.discard_throttle.load(AtomicOrdering::Relaxed));
1628
1629        // Saturated scratch budget: the next dropped head is pure discard and
1630        // must engage reader back-pressure.
1631        shell.scratch_workspace_root = Some(temp_dir.path().to_path_buf());
1632        shell.scratch_bytes = SCRATCH_MAX_BYTES;
1633        shell.offload_dropped_head("dropped beyond the budget");
1634        assert!(shell.discard_throttle.load(AtomicOrdering::Relaxed));
1635
1636        // A new command resets scratch state and releases the throttle.
1637        shell.send_command("echo done")?;
1638        assert!(!shell.discard_throttle.load(AtomicOrdering::Relaxed));
1639        Ok(())
1640    }
1641
1642    #[cfg(unix)] // spawns a real shell
1643    #[test]
1644    fn discard_throttle_engages_when_a_write_reaches_the_cap() -> Result<()> {
1645        let temp_dir = TempDir::new()?;
1646        let mut shell = PtyShell::new(temp_dir.path(), false)?;
1647        shell.scratch_workspace_root = Some(temp_dir.path().to_path_buf());
1648        // One byte of budget left: this write saturates the cap exactly.
1649        shell.scratch_bytes = SCRATCH_MAX_BYTES - 1;
1650        shell.offload_dropped_head("xx");
1651        assert!(shell.discard_throttle.load(AtomicOrdering::Relaxed));
1652        Ok(())
1653    }
1654
1655    #[cfg(unix)] // spawns a real shell
1656    #[test]
1657    fn test_pty_shell_echo() -> Result<()> {
1658        let temp_dir = TempDir::new()?;
1659        let mut shell = PtyShell::new(temp_dir.path(), false)?;
1660
1661        shell.send_command("echo 'hello pty'")?;
1662        let (output, complete) = shell.read_output(2.0)?;
1663
1664        assert!(output.contains("hello pty"), "Output should contain 'hello pty': {output}");
1665        // The bootstrap (prompt export line, shell banner) must have been
1666        // consumed before the first command, and the first command must
1667        // already report its exit code.
1668        assert!(complete, "first command must complete: {output}");
1669        assert!(!output.contains("PROMPT_COMMAND"), "bootstrap leaked into output: {output}");
1670        assert_eq!(shell.last_exit_code, Some(0), "{output}");
1671        Ok(())
1672    }
1673
1674    #[cfg(unix)] // spawns a real shell
1675    #[test]
1676    fn agent_paths_are_exported_to_the_pty() -> Result<()> {
1677        let workspace = TempDir::new()?;
1678        let temporary_artifact_dir = workspace.path().join(".winx/tmp/session-test");
1679        let mut shell = PtyShell::new_with_agent_paths(
1680            workspace.path(),
1681            false,
1682            Some(workspace.path()),
1683            Some(&temporary_artifact_dir),
1684        )?;
1685
1686        shell.send_command("printf '%s\\n%s\\n' \"$WINX_WORKSPACE_ROOT\" \"$WINX_TEMP_DIR\"")?;
1687        let (output, _complete) = shell.read_output(2.0)?;
1688
1689        assert!(output.contains(&workspace.path().to_string_lossy().to_string()), "{output}");
1690        assert!(output.contains(&temporary_artifact_dir.to_string_lossy().to_string()), "{output}");
1691        Ok(())
1692    }
1693
1694    #[cfg(unix)] // spawns a real shell
1695    #[test]
1696    fn completed_nonblocking_poll_is_level_triggered() -> Result<()> {
1697        let temp_dir = TempDir::new()?;
1698        let mut shell = PtyShell::new(temp_dir.path(), false)?;
1699
1700        shell.send_command("true")?;
1701        let deadline = Instant::now() + Duration::from_secs(2);
1702        while Instant::now() < deadline && !shell.poll_output_nonblocking() {
1703            std::thread::sleep(Duration::from_millis(10));
1704        }
1705
1706        assert!(!shell.command_running, "shell did not complete before the deadline");
1707        assert!(
1708            shell.poll_output_nonblocking(),
1709            "a later consumer must still observe the completed state"
1710        );
1711        Ok(())
1712    }
1713
1714    #[cfg(unix)] // spawns a real shell
1715    #[test]
1716    fn test_pty_shell_pwd() -> Result<()> {
1717        let temp_dir = TempDir::new()?;
1718        let mut shell = PtyShell::new(temp_dir.path(), false)?;
1719
1720        // Simply verify shell responds to pwd command
1721        // Use single quotes like echo test for consistency
1722        shell.send_command("pwd && echo 'pwd_done'")?;
1723        let (output, _complete) = shell.read_output(2.0)?;
1724
1725        // Verify the echo marker appears (proves command executed)
1726        assert!(output.contains("pwd_done"), "Output should contain 'pwd_done': {output}");
1727        Ok(())
1728    }
1729
1730    #[cfg(unix)] // spawns a real shell
1731    #[test]
1732    fn test_pty_resize() -> Result<()> {
1733        let temp_dir = TempDir::new()?;
1734        let mut shell = PtyShell::new(temp_dir.path(), false)?;
1735
1736        let result = shell.resize(120, 40);
1737        assert!(result.is_ok());
1738
1739        let (cols, rows) = shell.get_size();
1740        assert_eq!(cols, 120);
1741        assert_eq!(rows, 40);
1742        Ok(())
1743    }
1744
1745    /// `kill(pid, 0)` probes existence without sending a signal: 0 = the pid
1746    /// exists, -1 (ESRCH) = it's gone. A freshly-killed orphan lingers briefly
1747    /// as a zombie under init until reaped, so callers poll.
1748    #[cfg(unix)]
1749    fn pid_alive(pid: i32) -> bool {
1750        u32::try_from(pid).is_ok_and(crate::os::unix::process_exists)
1751    }
1752
1753    #[cfg(unix)]
1754    #[test]
1755    fn dropping_shell_kills_orphaned_background_child() -> Result<()> {
1756        // A background job the shell starts must not outlive the shell. Spawn a
1757        // long `sleep` in the background, record its pid, drop the shell, and
1758        // confirm the sleep is gone - proving the group-kill reached past the
1759        // shell to a child `Child::kill` alone would have orphaned.
1760        let dir = TempDir::new()?;
1761        let pidfile = dir.path().join("child.pid");
1762        let mut shell = PtyShell::new(dir.path(), false)?;
1763
1764        shell
1765            .send_command(&format!("sleep 300 & echo $! > {} ; echo spawned", pidfile.display()))?;
1766
1767        // The PTY echoes the input line, so `out` containing "spawned" only proves
1768        // the line was sent - not that bash ran it. Under CI load bash can lag, so
1769        // poll the pidfile (it only appears once `echo $! > pidfile` executes) while
1770        // draining the PTY, instead of trusting the echo and racing the redirect.
1771        let mut child_pid = None;
1772        for _ in 0..150 {
1773            let _ = shell.read_output(0.1);
1774            if let Some(pid) =
1775                std::fs::read_to_string(&pidfile).ok().and_then(|c| c.trim().parse::<i32>().ok())
1776            {
1777                child_pid = Some(pid);
1778                break;
1779            }
1780            thread::sleep(Duration::from_millis(20));
1781        }
1782        let child_pid =
1783            child_pid.ok_or_else(|| anyhow!("background child pid never materialized"))?;
1784        assert!(pid_alive(child_pid), "background child should be running before drop");
1785
1786        drop(shell);
1787
1788        // The group-kill plus init reaping the orphan are async w.r.t. us; poll.
1789        let mut gone = false;
1790        for _ in 0..150 {
1791            if !pid_alive(child_pid) {
1792                gone = true;
1793                break;
1794            }
1795            thread::sleep(Duration::from_millis(20));
1796        }
1797        assert!(gone, "background child {child_pid} survived shell teardown (orphan leak)");
1798        Ok(())
1799    }
1800}