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