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