Skip to main content

vtcode_core/tools/pty/
manager.rs

1use hashbrown::HashMap;
2use std::io::Read;
3use std::path::{Path, PathBuf};
4use std::sync::{
5    Arc, Weak,
6    atomic::{AtomicBool, AtomicU64, Ordering},
7    mpsc,
8};
9use std::thread;
10use std::time::{Duration, Instant};
11
12use anyhow::{Context, Result, anyhow};
13use chrono::Utc;
14use parking_lot::{Mutex, RwLock};
15use portable_pty::{CommandBuilder, PtySize, native_pty_system};
16use sha2::{Digest, Sha256};
17use shell_words::join;
18use tokio::io::AsyncWriteExt;
19use tokio::sync::Mutex as TokioMutex;
20use tokio::sync::mpsc as tokio_mpsc;
21use tracing::{debug, info, warn};
22
23use super::command_utils::{
24    is_long_running_command, is_long_running_command_string, is_sandbox_wrapper_program, is_shell_program,
25};
26use super::formatting::sanitize_session_id;
27use super::manager_utils::{clamp_timeout, exit_status_code, set_command_environment_with_sandbox};
28
29use super::screen_backend::PtyScreenState;
30use super::scrollback::PtyScrollback;
31use super::session::PtySessionHandle;
32use super::types::{PtyCommandRequest, PtyCommandResult};
33
34use std::sync::LazyLock;
35
36/// Per-workspace command locks to serialize long-running toolchain commands.
37/// Keyed by canonicalized workspace path to prevent lockfile contention.
38/// This is more granular than a global lock - different workspaces can run concurrently.
39///
40/// Entries are held weakly: once the last `Arc` returned by `get_command_lock` is
41/// dropped (the command that held it completes), the entry is collected on the
42/// next lookup, so the map stays bounded by the number of concurrently-held
43/// locks rather than the number of workspaces ever seen.
44static WORKSPACE_COMMAND_LOCKS: LazyLock<Mutex<HashMap<PathBuf, Weak<tokio::sync::Mutex<()>>>>> =
45    LazyLock::new(|| Mutex::new(HashMap::new()));
46
47/// Get or create a command lock for the given workspace root
48fn get_command_lock(workspace_root: &Path) -> Arc<tokio::sync::Mutex<()>> {
49    let mut locks = WORKSPACE_COMMAND_LOCKS.lock();
50    let key = workspace_root.to_path_buf();
51    if let Some(lock) = locks.get(&key).and_then(Weak::upgrade) {
52        return lock;
53    }
54    let lock = Arc::new(tokio::sync::Mutex::new(()));
55    locks.insert(key, Arc::downgrade(&lock));
56    lock
57}
58
59/// Grace period to wait for threads to exit after killing the process (ms)
60const THREAD_JOIN_GRACE_PERIOD_MS: u64 = 500;
61
62const PTY_OUTPUT_TRUNCATED_MARKER: &[u8] = b"\n[... output truncated: capture limit reached ...]";
63
64/// Reads to EOF but retains at most `max_bytes`; the surplus is still drained so the child never blocks on a full PTY.
65fn read_pty_output_capped(mut reader: impl Read, max_bytes: usize) -> Result<Vec<u8>> {
66    let mut buffer = [0u8; 4096];
67    let mut collected = Vec::new();
68    let mut truncated = false;
69
70    loop {
71        match reader.read(&mut buffer) {
72            Ok(0) => break,
73            Ok(bytes_read) => {
74                let room = max_bytes.saturating_sub(collected.len());
75                if bytes_read > room {
76                    truncated = true;
77                }
78                collected.extend_from_slice(&buffer[..bytes_read.min(room)]);
79            }
80            Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
81            Err(error) => return Err(error).context("failed to read PTY command output"),
82        }
83    }
84
85    if truncated {
86        collected.extend_from_slice(PTY_OUTPUT_TRUNCATED_MARKER);
87    }
88    Ok(collected)
89}
90
91use crate::audit::PermissionAuditLog;
92use crate::config::{CommandsConfig, PtyConfig};
93use crate::telemetry::perf;
94use crate::tools::exec_session::create_live_spool_file;
95use crate::tools::output_spooler::{SpoolIntegrity, SpoolLineCounter, encode_digest_hex};
96use crate::tools::path_env;
97use crate::tools::shell::resolve_fallback_shell;
98use crate::tools::types::VTCodePtySession;
99use crate::utils::gatekeeper;
100use crate::utils::path::ensure_path_within_workspace;
101use crate::utils::unicode_monitor::UNICODE_MONITOR;
102use vtcode_commons::canonicalize;
103use vtcode_commons::tokens::CHARS_PER_TOKEN;
104
105mod session_ops;
106
107#[derive(Clone)]
108pub struct PtyManager {
109    workspace_root: PathBuf,
110    config: PtyConfig,
111    inner: Arc<PtyState>,
112    audit_log: Option<Arc<TokioMutex<PermissionAuditLog>>>,
113    extra_paths: Arc<RwLock<Arc<Vec<PathBuf>>>>,
114}
115
116#[derive(Default)]
117struct PtyState {
118    sessions: Mutex<HashMap<String, Arc<PtySessionHandle>>>,
119}
120
121impl PtyManager {
122    pub fn new(workspace_root: PathBuf, config: PtyConfig) -> Self {
123        let resolved_root = canonicalize(&workspace_root).unwrap_or_else(|_| workspace_root.clone());
124
125        let default_paths =
126            path_env::compute_extra_search_paths(&CommandsConfig::default().extra_path_entries, &resolved_root);
127
128        Self {
129            workspace_root: resolved_root,
130            config,
131            inner: Arc::new(PtyState::default()),
132            audit_log: None,
133            extra_paths: Arc::new(RwLock::new(Arc::new(default_paths))),
134        }
135    }
136
137    pub fn with_audit_log(mut self, audit_log: Arc<TokioMutex<PermissionAuditLog>>) -> Self {
138        self.audit_log = Some(audit_log);
139        self
140    }
141
142    pub fn config(&self) -> &PtyConfig {
143        &self.config
144    }
145
146    pub fn apply_commands_config(&self, commands_config: &CommandsConfig) {
147        let new_paths = path_env::compute_extra_search_paths(&commands_config.extra_path_entries, &self.workspace_root);
148        *self.extra_paths.write() = Arc::new(new_paths);
149    }
150
151    pub(crate) fn merge_command_path(&self, current: Option<&std::ffi::OsStr>) -> Option<std::ffi::OsString> {
152        path_env::merge_path_env(current, &self.extra_paths.read())
153    }
154
155    pub fn describe_working_dir(&self, path: &Path) -> String {
156        self.format_working_dir(path)
157    }
158
159    pub async fn run_command(&self, mut request: PtyCommandRequest) -> Result<PtyCommandResult> {
160        if request.command.is_empty() {
161            return Err(anyhow!("PTY command cannot be empty"));
162        }
163
164        let mut command = std::mem::take(&mut request.command);
165        let program = command.remove(0);
166        let args = command;
167        let timeout = clamp_timeout(request.timeout);
168        let work_dir = std::mem::take(&mut request.working_dir);
169        let size = request.size;
170        let start = Instant::now();
171
172        let mut tags = HashMap::new();
173        tags.insert("subsystem".to_string(), "pty".to_string());
174        tags.insert("program".to_string(), program.clone());
175        perf::record_value("vtcode.perf.spawn_count", 1.0, tags);
176
177        gatekeeper::check_quarantine_for_program(&program);
178        self.ensure_within_workspace(&work_dir)?;
179        let workspace_root = self.workspace_root.clone();
180        let extra_paths = self.extra_paths.read().clone();
181        let max_tokens = request.max_tokens;
182        let max_capture_bytes = self.config.max_scrollback_bytes;
183
184        // Determine if this command needs serialization to avoid contention
185        let needs_lock = is_long_running_command(&program)
186            || (is_shell_program(&program) && args.iter().any(|arg| is_long_running_command_string(arg)));
187
188        // Acquire per-workspace lock if needed to prevent lockfile contention.
189        // This prevents "blocking waiting for file lock" errors when the agent
190        // triggers multiple long-running commands before previous ones complete.
191        // Using per-workspace lock allows concurrent commands in different workspaces.
192        let command_lock = if needs_lock {
193            Some(get_command_lock(&workspace_root))
194        } else {
195            None
196        };
197        let _command_guard = if let Some(ref lock) = command_lock {
198            debug!(
199                target: "vtcode.pty.command_lock",
200                program = %program,
201                workspace = %workspace_root.display(),
202                "Acquiring per-workspace command lock to serialize long-running invocations"
203            );
204            Some(lock.lock().await)
205        } else {
206            None
207        };
208
209        let result = tokio::task::spawn_blocking(move || -> Result<PtyCommandResult> {
210            let timeout_duration = Duration::from_millis(timeout);
211
212            // Use login shell for command execution to ensure user's PATH and environment
213            // is properly initialized from their shell configuration files (~/.bashrc, ~/.zshrc, etc).
214            // However, we avoid double-wrapping if the command is already a shell invocation.
215            let (exec_program, exec_args, display_program, _use_shell_wrapper) = if (is_shell_program(&program)
216                && args.iter().any(|arg| arg == "-c" || arg == "/C"))
217                || is_sandbox_wrapper_program(&program, &args)
218            {
219                // Already a shell command or sandbox wrapper, don't wrap again.
220                (program.clone(), args.clone(), program.clone(), false)
221            } else {
222                let shell = resolve_fallback_shell();
223                let full_command = join(std::iter::once(program.clone()).chain(args.iter().cloned()));
224                (shell.clone(), vec!["-lc".to_owned(), full_command.clone()], program.clone(), true)
225            };
226
227            let mut builder = CommandBuilder::new(exec_program.clone());
228            for arg in &exec_args {
229                builder.arg(arg);
230            }
231            builder.cwd(&work_dir);
232            let extra_env = HashMap::new();
233            let sandbox_active = is_sandbox_wrapper_program(&program, &args);
234            set_command_environment_with_sandbox(
235                &mut builder,
236                &display_program,
237                size,
238                &workspace_root,
239                &extra_paths,
240                &extra_env,
241                &HashMap::new(),
242                sandbox_active,
243            );
244
245            #[cfg(unix)]
246            apply_process_owner(&mut builder, &exec_program, &exec_args)?;
247
248            let pty_system = native_pty_system();
249            let pair = pty_system.openpty(size).context("failed to allocate PTY pair")?;
250
251            let mut child = pair
252                .slave
253                .spawn_command(builder)
254                .with_context(|| format!("failed to spawn PTY command '{display_program}'"))?;
255            let child_pid = child.process_id();
256            let mut killer = child.clone_killer();
257            drop(pair.slave);
258
259            let reader = pair.master.try_clone_reader().context("failed to clone PTY reader")?;
260
261            let (wait_tx, wait_rx) = mpsc::channel();
262            let wait_thread = thread::spawn(move || {
263                let status = child.wait();
264                let _ = wait_tx.send(());
265                status
266            });
267
268            let reader_thread = thread::spawn(move || read_pty_output_capped(reader, max_capture_bytes));
269
270            let wait_result = match wait_rx.recv_timeout(timeout_duration) {
271                Ok(()) => wait_thread
272                    .join()
273                    .map_err(|panic| anyhow!("PTY command wait thread panicked: {panic:?}"))?,
274                Err(mpsc::RecvTimeoutError::Timeout) => {
275                    // Kill the process group and the direct child process handle.
276                    // vtcode_bash_runner::graceful_kill_process_group_default now handles
277                    // the robust 'more kills' pattern which ensures descendants do not survive.
278                    if let Some(pid) = child_pid {
279                        let _ = vtcode_bash_runner::graceful_kill_process_group_default(pid);
280                    } else {
281                        let _ = killer.kill();
282                    }
283
284                    // Wait with a grace period - don't hang forever
285                    let grace_period = Duration::from_millis(THREAD_JOIN_GRACE_PERIOD_MS);
286                    match wait_rx.recv_timeout(grace_period) {
287                        Ok(()) | Err(mpsc::RecvTimeoutError::Disconnected) => {
288                            // Process exited, try to join threads with timeout
289                            // If they don't exit within grace period, detach them
290                        }
291                        Err(mpsc::RecvTimeoutError::Timeout) => {
292                            warn!(
293                                target: "vtcode.pty.timeout",
294                                timeout_ms = timeout,
295                                grace_ms = THREAD_JOIN_GRACE_PERIOD_MS,
296                                "PTY command did not exit within grace period after kill, detaching threads"
297                            );
298                            // Detach threads by dropping handles - they may leak but we don't hang
299                            drop(wait_thread);
300                            drop(reader_thread);
301                            return Err(anyhow!(
302                                "PTY command timed out after {timeout} milliseconds and did not respond to kill signal"
303                            ));
304                        }
305                    }
306
307                    // Try to join wait thread (should be quick since process exited)
308                    match wait_thread.join() {
309                        Ok(result) => {
310                            if let Err(error) = result {
311                                warn!(
312                                    target: "vtcode.pty.timeout",
313                                    error = %error,
314                                    "PTY command wait error after timeout"
315                                );
316                            }
317                        }
318                        Err(panic) => {
319                            warn!(
320                                target: "vtcode.pty.timeout",
321                                "PTY wait thread panicked: {:?}",
322                                panic
323                            );
324                        }
325                    }
326
327                    // Try to join reader thread (may take a moment for PTY to close)
328                    // Use a thread-local timeout via a parking_lot based approach
329                    // For simplicity, just drop the handle if it doesn't complete quickly
330                    let reader_handle = thread::spawn(move || reader_thread.join());
331                    match reader_handle.join() {
332                        Ok(Ok(Ok(_))) => {}
333                        Ok(Ok(Err(e))) => {
334                            warn!(
335                                target: "vtcode.pty.timeout",
336                                error = %e,
337                                "PTY reader error after timeout"
338                            );
339                        }
340                        Ok(Err(panic)) => {
341                            warn!(
342                                target: "vtcode.pty.timeout",
343                                "PTY reader thread panicked: {:?}",
344                                panic
345                            );
346                        }
347                        Err(_) => {
348                            warn!(
349                                target: "vtcode.pty.timeout",
350                                "Failed to join PTY reader thread wrapper"
351                            );
352                        }
353                    }
354
355                    return Err(anyhow!("PTY command timed out after {timeout} milliseconds"));
356                }
357                Err(mpsc::RecvTimeoutError::Disconnected) => {
358                    // Channel disconnected - process likely crashed
359                    // Try to join with grace period
360                    let grace_period = Duration::from_millis(THREAD_JOIN_GRACE_PERIOD_MS);
361
362                    // Spawn wrapper thread to allow timeout on join
363                    let wait_wrapper = thread::spawn(move || wait_thread.join());
364                    thread::sleep(grace_period);
365                    if wait_wrapper.is_finished() {
366                        match wait_wrapper.join() {
367                            Ok(Ok(result)) => {
368                                if let Err(error) = result {
369                                    return Err(error)
370                                        .context("failed to wait for PTY command after channel disconnect");
371                                }
372                            }
373                            Ok(Err(panic)) => {
374                                return Err(anyhow!("PTY wait thread panicked: {panic:?}"));
375                            }
376                            Err(_) => {
377                                return Err(anyhow!("PTY wait channel disconnected and thread join failed"));
378                            }
379                        }
380                    } else {
381                        warn!(
382                            target: "vtcode.pty.disconnect",
383                            "PTY wait thread did not exit within grace period, detaching"
384                        );
385                        drop(reader_thread);
386                        return Err(anyhow!("PTY command wait channel disconnected unexpectedly"));
387                    }
388
389                    // Also try to get reader output
390                    match reader_thread.join() {
391                        Ok(Ok(_)) => {}
392                        Ok(Err(e)) => {
393                            warn!(
394                                target: "vtcode.pty.disconnect",
395                                error = %e,
396                                "PTY reader error after channel disconnect"
397                            );
398                        }
399                        Err(panic) => {
400                            warn!(
401                                target: "vtcode.pty.disconnect",
402                                "PTY reader panicked: {:?}",
403                                panic
404                            );
405                        }
406                    }
407
408                    return Err(anyhow!("PTY command wait channel disconnected unexpectedly"));
409                }
410            };
411
412            let status = wait_result.context("failed to wait for PTY command to exit")?;
413
414            let output_bytes = reader_thread
415                .join()
416                .map_err(|panic| anyhow!("PTY command reader thread panicked: {panic:?}"))?
417                .context("failed to read PTY command output")?;
418            // Fast zero-copy path for valid UTF-8 (the common case); only
419            // allocate a lossy copy when the bytes are actually invalid.
420            let mut output =
421                String::from_utf8(output_bytes).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned());
422            let exit_code = exit_status_code(status);
423
424            // Apply max_tokens truncation if specified
425            if let Some(max_tokens) = max_tokens {
426                if max_tokens > 0 {
427                    // Simple byte-based truncation
428                    let max_bytes = max_tokens.saturating_mul(CHARS_PER_TOKEN);
429                    if output.len() > max_bytes {
430                        let truncate_point = max_bytes.min(output.len());
431                        output.truncate(truncate_point);
432                        output.push_str("\n[... truncated by max_tokens ...]");
433                    }
434                } else {
435                    // Keep original if max_tokens is not valid
436                }
437            }
438            // Keep original if max_tokens is None
439
440            Ok(PtyCommandResult {
441                exit_code,
442                output,
443                duration: start.elapsed(),
444                size,
445                applied_max_tokens: max_tokens,
446            })
447        })
448        .await
449        .context("failed to join PTY command task")??;
450
451        Ok(result)
452    }
453
454    /// Lexical cwd shared by launch validation and recovery target lookup.
455    pub(crate) fn working_dir_candidate(&self, requested: Option<&str>) -> Result<PathBuf> {
456        let requested = match requested {
457            Some(dir) if !dir.trim().is_empty() => dir.trim(),
458            _ => return Ok(self.workspace_root.clone()),
459        };
460
461        let candidate = self.workspace_root.join(requested);
462        ensure_path_within_workspace(&candidate, &self.workspace_root)
463            .map_err(|e| anyhow!("Working directory '{}' escapes the workspace root: {e}", candidate.display()))
464    }
465
466    pub async fn resolve_working_dir(&self, requested: Option<&str>) -> Result<PathBuf> {
467        let normalized = self.working_dir_candidate(requested)?;
468        if requested.is_none_or(|dir| dir.trim().is_empty()) {
469            return Ok(normalized);
470        }
471        let candidate = &normalized;
472        // Symlink-aware containment: a symlinked directory inside the
473        // workspace must not move the command cwd outside it.
474        vtcode_commons::paths::ensure_path_within_workspace_resolved(&normalized, &self.workspace_root)
475            .await
476            .map_err(|e| anyhow!("Working directory '{}' escapes the workspace root: {e}", candidate.display()))?;
477        let metadata = tokio::fs::metadata(&normalized)
478            .await
479            .with_context(|| format!("Working directory '{}' does not exist", normalized.display()))?;
480        if !metadata.is_dir() {
481            return Err(anyhow!("Working directory '{}' is not a directory", normalized.display()));
482        }
483        Ok(normalized)
484    }
485
486    pub fn create_session(
487        &self,
488        session_id: String,
489        command: Vec<String>,
490        working_dir: PathBuf,
491        size: PtySize,
492    ) -> Result<VTCodePtySession> {
493        self.create_session_with_bridge(session_id, command, working_dir, size, HashMap::new(), None)
494    }
495
496    fn create_session_with_bridge(
497        &self,
498        session_id: String,
499        command: Vec<String>,
500        working_dir: PathBuf,
501        size: PtySize,
502        extra_env: HashMap<String, String>,
503        zsh_exec_bridge: Option<crate::zsh_exec_bridge::ZshExecBridgeSession>,
504    ) -> Result<VTCodePtySession> {
505        self.create_session_with_bridge_sandboxed(
506            session_id,
507            command,
508            working_dir,
509            size,
510            extra_env,
511            zsh_exec_bridge,
512            HashMap::new(),
513            false,
514        )
515    }
516
517    pub(crate) fn create_session_with_bridge_sandboxed(
518        &self,
519        session_id: String,
520        command: Vec<String>,
521        working_dir: PathBuf,
522        size: PtySize,
523        extra_env: HashMap<String, String>,
524        zsh_exec_bridge: Option<crate::zsh_exec_bridge::ZshExecBridgeSession>,
525        trusted_env: HashMap<String, String>,
526        sandbox_active: bool,
527    ) -> Result<VTCodePtySession> {
528        if command.is_empty() {
529            return Err(anyhow!(
530                "PTY session command cannot be empty.\n\
531                 This is an internal error - command validation should have caught this earlier.\n\
532                 Please report this with the command-session parameters used."
533            ));
534        }
535
536        // Use entry API to avoid double lookup
537        let mut sessions = self.inner.sessions.lock();
538        use hashbrown::hash_map::Entry;
539        let entry = match sessions.entry(session_id.clone()) {
540            Entry::Occupied(_) => {
541                return Err(anyhow!("PTY session '{session_id}' already exists"));
542            }
543            Entry::Vacant(e) => e,
544        };
545
546        let mut command_parts = command;
547        let program = command_parts.remove(0);
548        let args = command_parts;
549        let extra_paths = self.extra_paths.read().clone();
550
551        // Use login shell for command execution to ensure user's PATH and environment
552        // is properly initialized from their shell configuration files (~/.bashrc, ~/.zshrc, etc).
553        // However, we avoid double-wrapping if the command is already a shell invocation.
554        let (exec_program, exec_args, display_program) = if (is_shell_program(&program)
555            && args.iter().any(|arg| arg == "-c" || arg == "/C"))
556            || is_sandbox_wrapper_program(&program, &args)
557        {
558            // Already a shell command, don't wrap again
559            (program.clone(), args.clone(), program.clone())
560        } else {
561            let shell = resolve_fallback_shell();
562            let full_command = join(std::iter::once(program.clone()).chain(args.iter().cloned()));
563
564            // Verify we have a valid command string
565            if full_command.is_empty() {
566                return Err(anyhow!("Failed to construct command string from program '{program}' and args {args:?}"));
567            }
568
569            (shell.clone(), vec!["-lc".to_owned(), full_command.clone()], program.clone())
570        };
571
572        let pty_system = native_pty_system();
573        let pair = pty_system.openpty(size).context("failed to allocate PTY pair")?;
574
575        let mut builder = CommandBuilder::new(exec_program.clone());
576        for arg in &exec_args {
577            builder.arg(arg);
578        }
579        builder.cwd(&working_dir);
580        self.ensure_within_workspace(&working_dir)?;
581        set_command_environment_with_sandbox(
582            &mut builder,
583            &display_program,
584            size,
585            &self.workspace_root,
586            &extra_paths,
587            &extra_env,
588            &trusted_env,
589            sandbox_active,
590        );
591
592        #[cfg(unix)]
593        apply_process_owner(&mut builder, &exec_program, &exec_args)?;
594
595        let child = pair
596            .slave
597            .spawn_command(builder)
598            .with_context(|| format!("failed to spawn PTY session command '{display_program}'"))?;
599
600        // Capture the child process ID for process group management
601        let child_pid = child.process_id();
602
603        drop(pair.slave);
604
605        let master = pair.master;
606        let mut reader = master.try_clone_reader().context("failed to clone PTY reader")?;
607        let writer = master.take_writer().context("failed to take PTY writer")?;
608
609        let screen_state = Arc::new(Mutex::new(PtyScreenState::new(size, self.config.scrollback_lines)));
610        let scrollback =
611            Arc::new(Mutex::new(PtyScrollback::new(self.config.scrollback_lines, self.config.max_scrollback_bytes)));
612
613        let (output_spool_relative_path, output_spool_file) =
614            create_live_spool_file(&self.workspace_root, &sanitize_session_id(&session_id));
615        let output_spool_path = output_spool_relative_path.to_string_lossy().replace('\\', "/");
616        let (output_spool_tx, mut output_spool_rx) = tokio_mpsc::channel::<Vec<u8>>(64);
617        let output_total_bytes = Arc::new(AtomicU64::new(0));
618        let output_total_bytes_for_reader = Arc::clone(&output_total_bytes);
619        let output_spool_failed = Arc::new(AtomicBool::new(false));
620        let output_spool_failed_for_task = Arc::clone(&output_spool_failed);
621        let output_spool_ready = Arc::new(AtomicBool::new(false));
622        let output_spool_ready_for_task = Arc::clone(&output_spool_ready);
623        let output_spool_finished = Arc::new(AtomicBool::new(false));
624        let output_spool_finished_for_task = Arc::clone(&output_spool_finished);
625        let output_spool_integrity = Arc::new(Mutex::new(None));
626        let output_spool_integrity_for_task = Arc::clone(&output_spool_integrity);
627
628        let output_spool_task = async move {
629            // Spool files are live-read while the session runs, so every
630            // chunk must reach disk immediately; buffering would hide output
631            // from concurrent readers until `flush`.
632            let mut spool_file = output_spool_file.map(tokio::fs::File::from_std);
633
634            if spool_file.is_none() {
635                output_spool_failed_for_task.store(true, Ordering::Release);
636            } else {
637                output_spool_ready_for_task.store(true, Ordering::Release);
638            }
639            let mut spool_redactor = vtcode_commons::sanitizer::StreamingSecretRedactor::default();
640            let mut spool_hasher = Sha256::new();
641            let mut spool_byte_count = 0_u64;
642            let mut spool_lines = SpoolLineCounter::default();
643            // Reads can split a multibyte character; decode across chunk boundaries.
644            let mut utf8_decoder = vtcode_commons::Utf8StreamDecoder::new();
645
646            while let Some(chunk) = output_spool_rx.recv().await {
647                let Some(file) = spool_file.as_mut() else {
648                    continue;
649                };
650                let text = utf8_decoder.push_cow(&chunk);
651                let sanitized = spool_redactor.push(&text);
652                if !sanitized.is_empty() {
653                    if file.write_all(sanitized.as_bytes()).await.is_err() {
654                        output_spool_failed_for_task.store(true, Ordering::Release);
655                        spool_file = None;
656                    } else {
657                        spool_hasher.update(sanitized.as_bytes());
658                        spool_lines.append(sanitized.as_bytes());
659                        spool_byte_count = spool_byte_count.saturating_add(sanitized.len() as u64);
660                    }
661                }
662            }
663
664            if let Some(file) = spool_file.as_mut() {
665                // A truncated final character becomes one U+FFFD rather than vanishing.
666                let mut sanitized = spool_redactor.push(&utf8_decoder.finish());
667                sanitized.push_str(&spool_redactor.finish());
668                let write_failed = !sanitized.is_empty() && file.write_all(sanitized.as_bytes()).await.is_err();
669                if !write_failed && !sanitized.is_empty() {
670                    spool_hasher.update(sanitized.as_bytes());
671                    spool_lines.append(sanitized.as_bytes());
672                    spool_byte_count = spool_byte_count.saturating_add(sanitized.len() as u64);
673                }
674                // Spool files are live-read while the session runs, so every
675                // chunk must reach disk immediately; buffering would hide
676                // output from concurrent readers until `flush`.
677                if write_failed || file.sync_all().await.is_err() {
678                    output_spool_failed_for_task.store(true, Ordering::Release);
679                } else {
680                    *output_spool_integrity_for_task.lock() = Some(SpoolIntegrity {
681                        byte_count: spool_byte_count,
682                        line_count: spool_lines.line_count(),
683                        sha256: encode_digest_hex(spool_hasher.finalize()),
684                    });
685                }
686            }
687            output_spool_finished_for_task.store(true, Ordering::Release);
688        };
689
690        if let Ok(handle) = tokio::runtime::Handle::try_current() {
691            handle.spawn(output_spool_task);
692        } else {
693            output_spool_failed.store(true, Ordering::Release);
694            output_spool_finished.store(true, Ordering::Release);
695        }
696
697        debug!(
698            session_id = %session_id,
699            rows = size.rows,
700            cols = size.cols,
701            "Created PTY session"
702        );
703        let screen_state_clone = Arc::clone(&screen_state);
704        let scrollback_clone = Arc::clone(&scrollback);
705        let reader_completed = Arc::new(AtomicBool::new(false));
706        let reader_completed_clone = Arc::clone(&reader_completed);
707        let session_name = session_id.clone();
708        let output_spool_failed_for_reader = Arc::clone(&output_spool_failed);
709        let mut output_spool_tx_for_reader = Some(output_spool_tx);
710        // Start unicode monitoring for this session
711        UNICODE_MONITOR.start_session();
712
713        let reader_thread = thread::Builder::new()
714            .name(format!("vtcode-pty-reader-{session_name}"))
715            .spawn(move || {
716                let mut buffer = [0u8; 8192]; // Increased buffer size for better performance
717                let mut utf8_buffer: Vec<u8> = Vec::with_capacity(8192); // Pre-allocate buffer
718                let mut total_bytes = 0usize;
719                let mut unicode_detection_hits = 0usize;
720
721                loop {
722                    match reader.read(&mut buffer) {
723Ok(0) => {
724    if !utf8_buffer.is_empty() {
725        let mut scrollback = scrollback_clone.lock();
726        scrollback.push_utf8(&mut utf8_buffer, true);
727    }
728    debug!("PTY session '{}' reader reached EOF (processed {} bytes, {} unicode detections)",
729           session_name, total_bytes, unicode_detection_hits);
730    break;
731}
732                        Ok(bytes_read) => {
733                            let chunk = &buffer[..bytes_read];
734                            total_bytes += bytes_read;
735                            output_total_bytes_for_reader.fetch_add(bytes_read as u64, Ordering::Relaxed);
736                            let send_result = output_spool_tx_for_reader
737                                .as_ref()
738                                .map(|sender| sender.blocking_send(chunk.to_vec()));
739                            if matches!(send_result, Some(Err(_))) {
740                                output_spool_failed_for_reader.store(true, Ordering::Release);
741                                warn!(
742                                    "PTY session '{}' spool receiver closed after {} bytes; retaining screen and scrollback output",
743                                    session_name, total_bytes
744                                );
745                                output_spool_tx_for_reader = None;
746                            }
747
748    // Quick unicode detection heuristic
749    let likely_unicode = chunk.iter().any(|&b| b >= 0x80);
750    if likely_unicode {
751        unicode_detection_hits += 1;
752    }
753
754    {
755        let mut screen_state = screen_state_clone.lock();
756        screen_state.process(chunk);
757    }
758
759    utf8_buffer.extend_from_slice(chunk);
760    {
761        let mut scrollback = scrollback_clone.lock();
762        scrollback.push_utf8(&mut utf8_buffer, false);
763    }
764
765    // Periodic buffer cleanup to prevent excessive memory usage
766    if utf8_buffer.capacity() > 32768 && utf8_buffer.len() < 1024 {
767        utf8_buffer.shrink_to_fit();
768    }
769}
770Err(error) => {
771    warn!("PTY session '{}' reader error: {} (processed {} bytes)",
772          session_name, error, total_bytes);
773    break;
774}
775                    }
776                }
777                debug!("PTY session '{}' reader thread finished (total: {} bytes, unicode detections: {})",
778                       session_name, total_bytes, unicode_detection_hits);
779
780                // Signal that the reader thread has finished pushing all data.
781                // This must be set BEFORE any further scrollback lock acquisitions
782                // so that is_output_drained() sees both pending==false and completed==true
783                // atomically under the scrollback lock.
784                reader_completed_clone.store(true, Ordering::Release);
785
786                // End unicode monitoring for this session
787                UNICODE_MONITOR.end_session();
788
789                // Log unicode statistics if any unicode was detected
790                if unicode_detection_hits > 0 {
791                    let scrollback = scrollback_clone.lock();
792                    let metrics = scrollback.metrics();
793                    if metrics.unicode_errors > 0 {
794warn!("PTY session '{}' had {} unicode errors during processing",
795      session_name, metrics.unicode_errors);
796                    }
797                    if metrics.total_unicode_chars > 0 {
798info!("PTY session '{}' processed {} unicode characters across {} sessions with {} buffer remainder",
799      session_name, metrics.total_unicode_chars, metrics.unicode_sessions, metrics.utf8_buffer_size);
800                    }
801                }
802            })
803            .context("failed to spawn PTY reader thread")?;
804
805        let metadata = VTCodePtySession {
806            id: session_id.clone(),
807            command: program,
808            args,
809            working_dir: Some(self.format_working_dir(&working_dir)),
810            rows: size.rows,
811            cols: size.cols,
812            child_pid,
813            started_at: Some(Utc::now()),
814            lifecycle_state: Some(crate::tools::types::VTCodeSessionLifecycleState::Running),
815            exit_code: None,
816            screen_contents: None,
817            scrollback: None,
818        };
819
820        // Use the entry we obtained earlier to insert without additional lookup
821        entry.insert(Arc::new(PtySessionHandle {
822            master: Mutex::new(master),
823            child: Mutex::new(child),
824            child_pid,
825            writer: Mutex::new(Some(writer)),
826            screen_state,
827            scrollback,
828            reader_thread: Mutex::new(Some(reader_thread)),
829            reader_completed,
830            metadata: metadata.clone(),
831            last_input: Mutex::new(None),
832            _zsh_exec_bridge: zsh_exec_bridge,
833            output_total_bytes,
834            output_spool_failed,
835            output_spool_ready,
836            output_spool_finished,
837            output_spool_path,
838            output_spool_integrity,
839        }));
840
841        Ok(metadata)
842    }
843
844    /// Delegates to the shared contract so PTY and pipe sessions cannot drift.
845    fn format_working_dir(&self, path: &Path) -> String {
846        vtcode_commons::workspace_relative_slash(&self.workspace_root, path)
847    }
848
849    fn ensure_within_workspace(&self, candidate: &Path) -> Result<()> {
850        ensure_path_within_workspace(candidate, &self.workspace_root).map(|_| ())
851    }
852}
853
854/// Apply lifetime ownership after environment/sandbox selection, retaining the
855/// builder's PTY, cwd, and environment policy and the admitted command's argv.
856#[cfg(unix)]
857fn apply_process_owner(builder: &mut CommandBuilder, program: &str, args: &[String]) -> Result<()> {
858    use vtcode_bash_runner::process_owner::{OWNER_SOCKET_ENV, OwnedCommand};
859    if let Some(owned) = OwnedCommand::from_environment(program.as_ref(), args, None)? {
860        let argv = builder.get_argv_mut();
861        argv.clear();
862        argv.push(owned.executable.into_os_string());
863        argv.extend(owned.arguments);
864        builder.env(OWNER_SOCKET_ENV, owned.owner_socket);
865    }
866    Ok(())
867}
868
869#[cfg(test)]
870mod tests;