1use 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
24pub const DEFAULT_COLS: u16 = 200;
26pub const DEFAULT_ROWS: u16 = 50;
27
28const MAX_OUTPUT_SIZE: usize = 1_000_000;
30
31pub const RING_BUFFER_LINES: usize = 2_000;
35
36const WCGW_PROMPT_PATTERN: &str = "◉";
38const WCGW_PROMPT_END: &str = "──➤";
39
40pub struct PtyShell {
45 master: Box<dyn MasterPty + Send>,
47 child: Box<dyn Child + Send + Sync>,
49 writer: Box<dyn Write + Send>,
51 output_rx: mpsc::Receiver<String>,
53 size: PtySize,
55 pub last_command: String,
57 pub output_buffer: String,
59 pub command_running: bool,
61 max_output_size: usize,
63 pub output_truncated: bool,
65 pub line_ring: VecDeque<String>,
68 line_ring_partial: String,
71 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 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 let pty_system = native_pty_system();
106
107 let size =
109 PtySize { rows: DEFAULT_ROWS, cols: DEFAULT_COLS, pixel_width: 0, pixel_height: 0 };
110
111 let pair = pty_system.openpty(size).context("Failed to open PTY pair")?;
113
114 let mut cmd = CommandBuilder::new("bash");
116 if restricted_mode {
117 cmd.arg("-r");
118 }
119
120 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 cmd.env("PROMPT_COMMAND", r#"printf "◉ %s──➤ " "$PWD""#);
130 cmd.cwd(initial_dir);
131
132 let child = pair.slave.spawn_command(cmd).context("Failed to spawn bash in PTY")?;
134
135 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 let (output_tx, output_rx) = mpsc::channel::<String>();
141
142 thread::spawn(move || {
145 let mut buf = [0u8; 4096];
146 loop {
147 match reader.read(&mut buf) {
148 Ok(0) => {
149 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 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 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 shell.initialize_prompt()?;
187
188 debug!("PTY shell created successfully");
189 Ok(shell)
190 }
191
192 fn initialize_prompt(&mut self) -> Result<()> {
194 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 std::thread::sleep(Duration::from_millis(100));
203 let _ = self.drain_output();
204
205 Ok(())
206 }
207
208 fn write_command(&mut self, command: &str) -> Result<()> {
210 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 fn drain_output(&mut self) -> String {
219 let mut output = String::new();
220 let deadline = Instant::now() + Duration::from_millis(200);
221
222 while Instant::now() < deadline {
224 match self.output_rx.try_recv() {
225 Ok(chunk) => {
226 output.push_str(&chunk);
227
228 if output.len() > self.max_output_size {
230 self.output_truncated = true;
231 break;
232 }
233 }
234 Err(TryRecvError::Empty) => {
235 thread::sleep(Duration::from_millis(10));
237 }
238 Err(TryRecvError::Disconnected) => {
239 break;
241 }
242 }
243 }
244
245 output
246 }
247
248 pub fn send_command(&mut self, command: &str) -> Result<()> {
250 debug!("PTY sending command: {}", command);
251
252 self.output_buffer.clear();
254 self.output_truncated = false;
255 self.last_command = command.to_string();
256 self.command_running = true;
257 self.last_returned_hash = None;
260
261 self.write_command(command)?;
263
264 Ok(())
265 }
266
267 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 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 pub fn fingerprint(text: &str) -> u64 {
319 let mut hasher = DefaultHasher::new();
320 text.hash(&mut hasher);
321 hasher.finish()
322 }
323
324 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 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 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 thread::sleep(Duration::from_millis(10));
366 no_data_count += 1;
367
368 if let Some(detected_time) = prompt_detected_at {
370 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_at = Some(Instant::now());
380 debug!("Prompt detected after wait, draining...");
381 }
382 }
383 Err(TryRecvError::Disconnected) => {
384 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 fn check_prompt_complete(text: &str) -> bool {
402 text.contains(WCGW_PROMPT_PATTERN) && text.contains(WCGW_PROMPT_END)
404 }
405
406 pub fn send_interrupt(&mut self) -> Result<()> {
408 debug!("PTY sending Ctrl+C");
409 self.writer
410 .write_all(&[0x03]) .context("Failed to send Ctrl+C")?;
412 self.writer.flush()?;
413 Ok(())
414 }
415
416 pub fn send_eof(&mut self) -> Result<()> {
418 debug!("PTY sending Ctrl+D");
419 self.writer
420 .write_all(&[0x04]) .context("Failed to send Ctrl+D")?;
422 self.writer.flush()?;
423 Ok(())
424 }
425
426 pub fn send_suspend(&mut self) -> Result<()> {
428 debug!("PTY sending Ctrl+Z");
429 self.writer
430 .write_all(&[0x1A]) .context("Failed to send Ctrl+Z")?;
432 self.writer.flush()?;
433 Ok(())
434 }
435
436 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 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 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 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 pub fn get_size(&self) -> (u16, u16) {
493 (self.size.cols, self.size.rows)
494 }
495
496 pub fn is_alive(&mut self) -> bool {
498 self.child.try_wait().is_ok_and(|status| status.is_none())
499 }
500}
501
502pub type SharedPtyShell = Arc<Mutex<Option<PtyShell>>>;
504
505pub 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 shell.send_command("pwd && echo 'pwd_done'")?;
544 let (output, _complete) = shell.read_output(2.0)?;
545
546 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}