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 anyhow::{anyhow, Context, Result};
11use portable_pty::{native_pty_system, Child, CommandBuilder, MasterPty, PtySize};
12use std::collections::hash_map::DefaultHasher;
13use std::collections::VecDeque;
14use std::hash::{Hash, Hasher};
15use std::io::{Read, Write};
16use std::path::Path;
17use std::sync::mpsc::{self, TryRecvError};
18use std::sync::Arc;
19use std::thread;
20use std::time::{Duration, Instant};
21use tokio::sync::Mutex;
22use tracing::{debug, info, warn};
23
24/// Default terminal dimensions (columns x rows)
25pub const DEFAULT_COLS: u16 = 200;
26pub const DEFAULT_ROWS: u16 = 50;
27
28/// Maximum output buffer size to prevent memory issues
29const MAX_OUTPUT_SIZE: usize = 1_000_000;
30
31/// How many fully-formed lines to keep in the per-shell ringbuffer. Callers can
32/// ask for at most this many lines of historical context via
33/// `StatusCheck.scrollback_lines`.
34pub const RING_BUFFER_LINES: usize = 2_000;
35
36/// WCGW-style prompt pattern for command completion detection
37const WCGW_PROMPT_PATTERN: &str = "◉";
38const WCGW_PROMPT_END: &str = "──➤";
39
40/// Real PTY-based interactive shell
41///
42/// Uses portable-pty for true pseudo-terminal functionality,
43/// enabling proper handling of interactive programs like sudo, vim, etc.
44pub struct PtyShell {
45    /// The PTY master handle for resize operations
46    master: Box<dyn MasterPty + Send>,
47    /// Child process running the shell
48    child: Box<dyn Child + Send + Sync>,
49    /// Writer for PTY input (taken from master)
50    writer: Box<dyn Write + Send>,
51    /// Channel receiver for output from reader thread
52    output_rx: mpsc::Receiver<String>,
53    /// Current terminal size
54    size: PtySize,
55    /// Last command executed
56    pub last_command: String,
57    /// Accumulated output buffer
58    pub output_buffer: String,
59    /// Whether a command is currently running
60    pub command_running: bool,
61    /// Maximum output size before truncation
62    max_output_size: usize,
63    /// Flag for output truncation
64    pub output_truncated: bool,
65    /// Rolling buffer of fully-emitted lines for opt-in scrollback. The newest
66    /// line is at the back; capped at `RING_BUFFER_LINES`.
67    pub line_ring: VecDeque<String>,
68    /// Carries the unterminated tail across reads so partial lines aren't
69    /// double-counted when more bytes arrive.
70    line_ring_partial: String,
71    /// Hash of the last rendered output we shipped to the caller. Used by the
72    /// delta path in `status_check` to elide repeats when the screen is idle.
73    pub last_returned_hash: Option<u64>,
74}
75
76impl std::fmt::Debug for PtyShell {
77    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
78        f.debug_struct("PtyShell")
79            .field("size", &format!("{}x{}", self.size.cols, self.size.rows))
80            .field("last_command", &self.last_command)
81            .field("command_running", &self.command_running)
82            .field("output_truncated", &self.output_truncated)
83            .field("output_buffer_len", &self.output_buffer.len())
84            .finish_non_exhaustive()
85    }
86}
87
88impl PtyShell {
89    /// Create a new PTY shell session
90    ///
91    /// # Arguments
92    /// * `initial_dir` - Starting directory for the shell
93    /// * `restricted_mode` - Whether to use bash restricted mode (-r)
94    ///
95    /// # Returns
96    /// A new `PtyShell` instance with an active bash session
97    pub fn new(initial_dir: &Path, restricted_mode: bool) -> Result<Self> {
98        info!(
99            "Creating new PTY shell (restricted: {}) in {}",
100            restricted_mode,
101            initial_dir.display()
102        );
103
104        // Initialize the native PTY system
105        let pty_system = native_pty_system();
106
107        // Configure terminal size
108        let size =
109            PtySize { rows: DEFAULT_ROWS, cols: DEFAULT_COLS, pixel_width: 0, pixel_height: 0 };
110
111        // Open the PTY pair (master + slave)
112        let pair = pty_system.openpty(size).context("Failed to open PTY pair")?;
113
114        // Build the command
115        let mut cmd = CommandBuilder::new("bash");
116        if restricted_mode {
117            cmd.arg("-r");
118        }
119
120        // Set up environment for proper terminal behavior
121        cmd.env("TERM", "xterm-256color");
122        cmd.env("COLORTERM", "truecolor");
123        cmd.env("PAGER", "cat");
124        cmd.env("GIT_PAGER", "cat");
125        cmd.env("COLUMNS", DEFAULT_COLS.to_string());
126        cmd.env("ROWS", DEFAULT_ROWS.to_string());
127        // WCGW-style prompt for command completion detection
128        // Note: removed \r\e[2K which was erasing the prompt before it could be detected
129        cmd.env("PROMPT_COMMAND", r#"printf "◉ %s──➤ " "$PWD""#);
130        cmd.cwd(initial_dir);
131
132        // Spawn bash in the PTY slave
133        let child = pair.slave.spawn_command(cmd).context("Failed to spawn bash in PTY")?;
134
135        // Get reader and writer from master
136        let mut reader = pair.master.try_clone_reader().context("Failed to clone PTY reader")?;
137        let writer = pair.master.take_writer().context("Failed to take PTY writer")?;
138
139        // Create channel for output from reader thread
140        let (output_tx, output_rx) = mpsc::channel::<String>();
141
142        // Spawn a background thread to read from the PTY
143        // This prevents blocking the main thread
144        thread::spawn(move || {
145            let mut buf = [0u8; 4096];
146            loop {
147                match reader.read(&mut buf) {
148                    Ok(0) => {
149                        // EOF - PTY closed
150                        break;
151                    }
152                    Ok(n) => {
153                        let chunk = String::from_utf8_lossy(&buf[..n]).to_string();
154                        if output_tx.send(chunk).is_err() {
155                            // Receiver dropped, exit thread
156                            break;
157                        }
158                    }
159                    Err(e) => {
160                        debug!("PTY reader thread error: {}", e);
161                        break;
162                    }
163                }
164            }
165            debug!("PTY reader thread exiting");
166        });
167
168        // Create the shell instance
169        let mut shell = Self {
170            master: pair.master,
171            child,
172            writer,
173            output_rx,
174            size,
175            last_command: String::new(),
176            output_buffer: String::new(),
177            command_running: false,
178            max_output_size: MAX_OUTPUT_SIZE,
179            output_truncated: false,
180            line_ring: VecDeque::with_capacity(RING_BUFFER_LINES),
181            line_ring_partial: String::new(),
182            last_returned_hash: None,
183        };
184
185        // Initialize the shell with WCGW-style prompt
186        shell.initialize_prompt()?;
187
188        debug!("PTY shell created successfully");
189        Ok(shell)
190    }
191
192    /// Initialize the shell prompt for WCGW compatibility
193    fn initialize_prompt(&mut self) -> Result<()> {
194        // Set up the dynamic prompt - matches WCGW Python PROMPT_STATEMENT
195        // Note: removed \r\e[2K which was erasing the prompt before it could be detected
196        let prompt_statement =
197            r#"export GIT_PAGER=cat PAGER=cat PROMPT_COMMAND='printf "◉ %s──➤ " "$PWD"'"#;
198
199        self.write_command(prompt_statement)?;
200
201        // Wait for prompt to be ready
202        std::thread::sleep(Duration::from_millis(100));
203        let _ = self.drain_output();
204
205        Ok(())
206    }
207
208    /// Write a command to the PTY
209    fn write_command(&mut self, command: &str) -> Result<()> {
210        // Commands in PTY need \r\n for proper terminal behavior
211        let cmd_with_newline = format!("{command}\n");
212        self.writer.write_all(cmd_with_newline.as_bytes()).context("Failed to write to PTY")?;
213        self.writer.flush().context("Failed to flush PTY")?;
214        Ok(())
215    }
216
217    /// Drain any pending output from the PTY channel
218    fn drain_output(&mut self) -> String {
219        let mut output = String::new();
220        let deadline = Instant::now() + Duration::from_millis(200);
221
222        // Drain all available output from the channel
223        while Instant::now() < deadline {
224            match self.output_rx.try_recv() {
225                Ok(chunk) => {
226                    output.push_str(&chunk);
227
228                    // Prevent runaway reads
229                    if output.len() > self.max_output_size {
230                        self.output_truncated = true;
231                        break;
232                    }
233                }
234                Err(TryRecvError::Empty) => {
235                    // No more data, wait briefly for more
236                    thread::sleep(Duration::from_millis(10));
237                }
238                Err(TryRecvError::Disconnected) => {
239                    // Reader thread died
240                    break;
241                }
242            }
243        }
244
245        output
246    }
247
248    /// Send a command to the shell and start reading output
249    pub fn send_command(&mut self, command: &str) -> Result<()> {
250        debug!("PTY sending command: {}", command);
251
252        // Clear previous state
253        self.output_buffer.clear();
254        self.output_truncated = false;
255        self.last_command = command.to_string();
256        self.command_running = true;
257        // A new command means the next status_check should return whatever
258        // shows up — drop the dedup hash so we don't elide the first response.
259        self.last_returned_hash = None;
260
261        // Write the command
262        self.write_command(command)?;
263
264        Ok(())
265    }
266
267    /// Push freshly-arrived bytes through the line-oriented ringbuffer so
268    /// callers can request bounded scrollback later.
269    fn ingest_into_ring(&mut self, chunk: &str) {
270        let combined = if self.line_ring_partial.is_empty() {
271            chunk.to_string()
272        } else {
273            let mut s = std::mem::take(&mut self.line_ring_partial);
274            s.push_str(chunk);
275            s
276        };
277
278        let mut last_nl_end: Option<usize> = None;
279        for (idx, ch) in combined.char_indices() {
280            if ch == '\n' {
281                let end = idx + ch.len_utf8();
282                let start = last_nl_end.unwrap_or(0);
283                let line = combined[start..idx].trim_end_matches('\r').to_string();
284                if self.line_ring.len() == RING_BUFFER_LINES {
285                    self.line_ring.pop_front();
286                }
287                self.line_ring.push_back(line);
288                last_nl_end = Some(end);
289            }
290        }
291
292        if let Some(end) = last_nl_end {
293            self.line_ring_partial = combined[end..].to_string();
294        } else {
295            self.line_ring_partial = combined;
296        }
297    }
298
299    /// Return up to `lines` recent lines from the ringbuffer, oldest first.
300    /// Includes any in-flight partial line.
301    pub fn collect_scrollback(&self, lines: usize) -> String {
302        if lines == 0 {
303            return String::new();
304        }
305        let start = self.line_ring.len().saturating_sub(lines);
306        let mut out = String::new();
307        for line in self.line_ring.iter().skip(start) {
308            out.push_str(line);
309            out.push('\n');
310        }
311        if !self.line_ring_partial.is_empty() {
312            out.push_str(&self.line_ring_partial);
313        }
314        out
315    }
316
317    /// Hash arbitrary rendered output into a u64 dedup key.
318    pub fn fingerprint(text: &str) -> u64 {
319        let mut hasher = DefaultHasher::new();
320        text.hash(&mut hasher);
321        hasher.finish()
322    }
323
324    /// Read output from the PTY with timeout
325    ///
326    /// Returns (output, `is_complete`) tuple where `is_complete` indicates
327    /// whether the command has finished (prompt detected)
328    pub fn read_output(&mut self, timeout_secs: f32) -> Result<(String, bool)> {
329        let timeout = Duration::from_secs_f32(timeout_secs.clamp(0.1, 60.0));
330        let start = Instant::now();
331        let mut complete = false;
332        let mut no_data_count = 0;
333        let mut prompt_detected_at: Option<Instant> = None;
334
335        while start.elapsed() < timeout {
336            match self.output_rx.try_recv() {
337                Ok(chunk) => {
338                    self.output_buffer.push_str(&chunk);
339                    self.ingest_into_ring(&chunk);
340                    no_data_count = 0;
341
342                    // Check for WCGW prompt indicating command completion
343                    if prompt_detected_at.is_none()
344                        && (Self::check_prompt_complete(&chunk)
345                            || Self::check_prompt_complete(&self.output_buffer))
346                    {
347                        prompt_detected_at = Some(Instant::now());
348                        debug!("Prompt detected, draining remaining output...");
349                    }
350
351                    // Truncate if too large
352                    if self.output_buffer.len() > self.max_output_size {
353                        self.output_truncated = true;
354                        let truncate_msg = "\n(...output truncated...)\n";
355                        let keep_size = self.max_output_size / 2;
356                        self.output_buffer = format!(
357                            "{}{}",
358                            truncate_msg,
359                            &self.output_buffer[self.output_buffer.len() - keep_size..]
360                        );
361                    }
362                }
363                Err(TryRecvError::Empty) => {
364                    // No data available, wait briefly
365                    thread::sleep(Duration::from_millis(10));
366                    no_data_count += 1;
367
368                    // If prompt was detected, check if we've drained long enough
369                    if let Some(detected_time) = prompt_detected_at {
370                        // Wait 100ms after prompt detection to capture any trailing output
371                        if detected_time.elapsed() > Duration::from_millis(100) {
372                            complete = true;
373                            debug!("Command completed - prompt detected and drained");
374                            break;
375                        }
376                    } else if no_data_count > 10 && Self::check_prompt_complete(&self.output_buffer)
377                    {
378                        // Prompt detected during empty reads
379                        prompt_detected_at = Some(Instant::now());
380                        debug!("Prompt detected after wait, draining...");
381                    }
382                }
383                Err(TryRecvError::Disconnected) => {
384                    // Reader thread died - PTY closed
385                    warn!("PTY reader disconnected");
386                    complete = true;
387                    break;
388                }
389            }
390        }
391
392        if complete || prompt_detected_at.is_some() {
393            self.command_running = false;
394            complete = true;
395        }
396
397        Ok((self.output_buffer.clone(), complete))
398    }
399
400    /// Check if the output contains the WCGW-style prompt
401    fn check_prompt_complete(text: &str) -> bool {
402        // Look for the WCGW prompt pattern: ◉ /path──➤
403        text.contains(WCGW_PROMPT_PATTERN) && text.contains(WCGW_PROMPT_END)
404    }
405
406    /// Send Ctrl+C (interrupt) to the PTY
407    pub fn send_interrupt(&mut self) -> Result<()> {
408        debug!("PTY sending Ctrl+C");
409        self.writer
410            .write_all(&[0x03]) // ASCII ETX (Ctrl+C)
411            .context("Failed to send Ctrl+C")?;
412        self.writer.flush()?;
413        Ok(())
414    }
415
416    /// Send Ctrl+D (EOF) to the PTY
417    pub fn send_eof(&mut self) -> Result<()> {
418        debug!("PTY sending Ctrl+D");
419        self.writer
420            .write_all(&[0x04]) // ASCII EOT (Ctrl+D)
421            .context("Failed to send Ctrl+D")?;
422        self.writer.flush()?;
423        Ok(())
424    }
425
426    /// Send Ctrl+Z (suspend) to the PTY
427    pub fn send_suspend(&mut self) -> Result<()> {
428        debug!("PTY sending Ctrl+Z");
429        self.writer
430            .write_all(&[0x1A]) // ASCII SUB (Ctrl+Z)
431            .context("Failed to send Ctrl+Z")?;
432        self.writer.flush()?;
433        Ok(())
434    }
435
436    /// Send text directly to the PTY (for interactive input)
437    pub fn send_text(&mut self, text: &str) -> Result<()> {
438        debug!("PTY sending text: {:?}", text);
439        self.send_bytes(text.as_bytes()).context("Failed to send text")?;
440        Ok(())
441    }
442
443    /// Send raw bytes directly to the PTY.
444    pub fn send_bytes(&mut self, bytes: &[u8]) -> Result<()> {
445        self.writer.write_all(bytes).context("Failed to send bytes")?;
446        self.writer.flush()?;
447        Ok(())
448    }
449
450    /// Send a special key sequence
451    pub fn send_special_key(&mut self, key: &str) -> Result<()> {
452        let bytes: &[u8] = match key {
453            "Enter" => b"\r",
454            "Tab" => b"\t",
455            "Backspace" => b"\x7F",
456            "Escape" => b"\x1B",
457            "Up" | "KeyUp" => b"\x1B[A",
458            "Down" | "KeyDown" => b"\x1B[B",
459            "Right" | "KeyRight" => b"\x1B[C",
460            "Left" | "KeyLeft" => b"\x1B[D",
461            "Home" => b"\x1B[H",
462            "End" => b"\x1B[F",
463            "PageUp" => b"\x1B[5~",
464            "PageDown" => b"\x1B[6~",
465            "Delete" => b"\x1B[3~",
466            "Insert" => b"\x1B[2~",
467            "CtrlC" | "Ctrl-C" => b"\x03",
468            "CtrlD" | "Ctrl-D" => b"\x04",
469            "CtrlZ" | "Ctrl-Z" => b"\x1A",
470            "CtrlL" | "Ctrl-L" => b"\x0C",
471            _ => return Err(anyhow!("Unknown special key: {key}")),
472        };
473
474        debug!("PTY sending special key: {} ({:?})", key, bytes);
475        self.send_bytes(bytes)?;
476        Ok(())
477    }
478
479    /// Resize the terminal
480    pub fn resize(&mut self, cols: u16, rows: u16) -> Result<()> {
481        debug!("PTY resizing to {}x{}", cols, rows);
482
483        let new_size = PtySize { rows, cols, pixel_width: 0, pixel_height: 0 };
484
485        self.master.resize(new_size).context("Failed to resize PTY")?;
486
487        self.size = new_size;
488        Ok(())
489    }
490
491    /// Get current terminal size
492    pub fn get_size(&self) -> (u16, u16) {
493        (self.size.cols, self.size.rows)
494    }
495
496    /// Check if the shell is still alive
497    pub fn is_alive(&mut self) -> bool {
498        self.child.try_wait().is_ok_and(|status| status.is_none())
499    }
500}
501
502/// Thread-safe wrapper for `PtyShell`
503pub type SharedPtyShell = Arc<Mutex<Option<PtyShell>>>;
504
505/// Create a new shared PTY shell
506pub fn create_shared_pty(initial_dir: &Path, restricted_mode: bool) -> Result<SharedPtyShell> {
507    let shell = PtyShell::new(initial_dir, restricted_mode)?;
508    Ok(Arc::new(Mutex::new(Some(shell))))
509}
510
511#[cfg(test)]
512mod tests {
513    use super::*;
514    use tempfile::TempDir;
515
516    #[test]
517    fn test_pty_shell_creation() -> Result<()> {
518        let temp_dir = TempDir::new()?;
519        let result = PtyShell::new(temp_dir.path(), false);
520        assert!(result.is_ok(), "Failed to create PTY shell: {:?}", result.err());
521        Ok(())
522    }
523
524    #[test]
525    fn test_pty_shell_echo() -> Result<()> {
526        let temp_dir = TempDir::new()?;
527        let mut shell = PtyShell::new(temp_dir.path(), false)?;
528
529        shell.send_command("echo 'hello pty'")?;
530        let (output, _complete) = shell.read_output(2.0)?;
531
532        assert!(output.contains("hello pty"), "Output should contain 'hello pty': {output}");
533        Ok(())
534    }
535
536    #[test]
537    fn test_pty_shell_pwd() -> Result<()> {
538        let temp_dir = TempDir::new()?;
539        let mut shell = PtyShell::new(temp_dir.path(), false)?;
540
541        // Simply verify shell responds to pwd command
542        // Use single quotes like echo test for consistency
543        shell.send_command("pwd && echo 'pwd_done'")?;
544        let (output, _complete) = shell.read_output(2.0)?;
545
546        // Verify the echo marker appears (proves command executed)
547        assert!(output.contains("pwd_done"), "Output should contain 'pwd_done': {output}");
548        Ok(())
549    }
550
551    #[test]
552    fn test_pty_resize() -> Result<()> {
553        let temp_dir = TempDir::new()?;
554        let mut shell = PtyShell::new(temp_dir.path(), false)?;
555
556        let result = shell.resize(120, 40);
557        assert!(result.is_ok());
558
559        let (cols, rows) = shell.get_size();
560        assert_eq!(cols, 120);
561        assert_eq!(rows, 40);
562        Ok(())
563    }
564}