vtcode_core/tools/pty/manager/
session_ops.rs1use super::super::PtyCloseMode;
2use super::super::formatting::{format_terminal_file, sanitize_session_id};
3use super::super::manager_utils::exit_status_code;
4use super::super::session::{CommandEchoState, PtySessionHandle};
5use super::PtyManager;
6use crate::tools::types::VTCodePtySession;
7use crate::utils::file_utils::{ensure_dir_exists, write_file_with_context};
8use anyhow::{Context, Result, anyhow};
9use portable_pty::PtySize;
10use std::io::Write;
11use std::sync::Arc;
12use tracing::warn;
13
14impl PtyManager {
15 pub fn list_sessions(&self) -> Vec<VTCodePtySession> {
16 let sessions = self.inner.sessions.lock();
17 sessions.values().map(|handle| handle.snapshot_metadata()).collect()
18 }
19
20 pub fn snapshot_session(&self, session_id: &str) -> Result<VTCodePtySession> {
21 let handle = self.session_handle(session_id)?;
22 Ok(handle.snapshot_metadata())
23 }
24
25 pub fn read_session_output(&self, session_id: &str, drain: bool) -> Result<Option<String>> {
26 let handle = self.session_handle(session_id)?;
27 Ok(handle.read_output(drain))
28 }
29
30 pub(crate) fn output_stats(&self, session_id: &str) -> Result<Option<super::super::PtyOutputStats>> {
31 let handle = self.session_handle(session_id)?;
32 let scrollback_truncated = handle.scrollback.lock().output_truncated();
33 let spool_ready = handle.output_spool_ready.load(std::sync::atomic::Ordering::Acquire);
34 let spool_finished = handle.output_spool_finished.load(std::sync::atomic::Ordering::Acquire);
35 let spool_failed = handle.output_spool_failed.load(std::sync::atomic::Ordering::Acquire);
36 Ok(Some(super::super::PtyOutputStats {
37 total_bytes: handle.output_total_bytes.load(std::sync::atomic::Ordering::Relaxed),
38 truncated: scrollback_truncated || spool_failed,
39 spool_path: handle.output_spool_path.clone(),
40 spool_available: spool_ready && !spool_failed,
41 spool_complete: spool_ready && spool_finished && !spool_failed,
42 spool_integrity: handle.output_spool_integrity.lock().clone(),
43 }))
44 }
45
46 pub fn is_output_drained(&self, session_id: &str) -> Result<bool> {
48 let handle = self.session_handle(session_id)?;
49 Ok(handle.is_output_drained())
50 }
51
52 pub fn send_input_to_session(&self, session_id: &str, data: &[u8], append_newline: bool) -> Result<usize> {
53 let handle = self.session_handle(session_id)?;
54
55 {
57 let mut last_input = handle.last_input.lock();
58 *last_input = if let Ok(input_text) = std::str::from_utf8(data) {
59 CommandEchoState::new(input_text, append_newline)
60 } else {
61 None
62 };
63 }
64
65 {
67 let mut writer_guard = handle.writer.lock();
68 let writer = writer_guard
69 .as_mut()
70 .ok_or_else(|| anyhow!("PTY session '{session_id}' is no longer writable"))?;
71
72 writer.write_all(data).context("failed to write input to PTY session")?;
73
74 if append_newline {
75 writer.write_all(b"\n").context("failed to write newline to PTY session")?;
76 }
77
78 writer.flush().context("failed to flush PTY session input")?;
79 }
80
81 let written = data.len() + if append_newline { 1 } else { 0 };
82 Ok(written)
83 }
84
85 pub fn resize_session(&self, session_id: &str, size: PtySize) -> Result<VTCodePtySession> {
86 let handle = self.session_handle(session_id)?;
87
88 {
89 let master = handle.master.lock();
90 master.resize(size).context("failed to resize PTY session")?;
91 }
92
93 {
94 let mut screen_state = handle.screen_state.lock();
95 screen_state.resize(size);
96 }
97
98 Ok(handle.snapshot_metadata())
99 }
100
101 pub fn is_session_completed(&self, session_id: &str) -> Result<Option<i32>> {
102 let handle = self.session_handle(session_id)?;
103 let mut child = handle.child.lock();
104 child
105 .try_wait()
106 .context("failed to poll PTY session status")
107 .map(|opt| opt.map(exit_status_code))
108 }
109
110 pub fn terminate_session(&self, session_id: &str) -> Result<()> {
111 let handle = self.session_handle(session_id)?;
112
113 {
114 let mut writer_guard = handle.writer.lock();
115 if let Some(mut writer) = writer_guard.take() {
116 let _ = writer.write_all(b"exit\n");
117 let _ = writer.flush();
118 }
119 }
120
121 handle.graceful_terminate();
122 Ok(())
123 }
124
125 pub fn force_terminate_session(&self, session_id: &str) -> Result<()> {
126 let handle = self.session_handle(session_id)?;
127 if !handle.force_terminate() {
128 return Err(anyhow!("PTY session '{session_id}' child exit was not confirmed"));
129 }
130 Ok(())
131 }
132
133 pub async fn sync_sessions_to_files(&self) -> Result<Vec<std::path::PathBuf>> {
140 let terminals_dir = self.workspace_root.join(".vtcode").join("terminals");
141 ensure_dir_exists(&terminals_dir)
142 .await
143 .with_context(|| format!("Failed to create terminals directory: {}", terminals_dir.display()))?;
144
145 let sessions = self.list_sessions();
146 let mut written_files = Vec::with_capacity(sessions.len());
147
148 for session in &sessions {
149 let output = match self.read_session_output(&session.id, false) {
150 Ok(Some(output)) => output,
151 Ok(None) => String::new(),
152 Err(_) => continue,
153 };
154
155 let content = format_terminal_file(session, &output);
156 let file_path = terminals_dir.join(format!("{}.txt", sanitize_session_id(&session.id)));
157
158 if let Err(e) = write_file_with_context(&file_path, &content, "terminal session file").await {
159 warn!(
160 session_id = %session.id,
161 error = %e,
162 "Failed to sync terminal session to file"
163 );
164 continue;
165 }
166
167 written_files.push(file_path);
168 }
169
170 let index_content = self.generate_terminals_index(&sessions);
172 let index_path = terminals_dir.join("index.md");
173 write_file_with_context(&index_path, &index_content, "terminals index")
174 .await
175 .with_context(|| format!("Failed to write terminals index: {}", index_path.display()))?;
176
177 tracing::info!(sessions = sessions.len(), files = written_files.len(), "Synced terminal sessions to files");
178
179 Ok(written_files)
180 }
181
182 fn generate_terminals_index(&self, sessions: &[VTCodePtySession]) -> String {
184 let mut content = String::new();
185 content.push_str("# Terminal Sessions Index\n\n");
186 content.push_str("This file lists all active terminal sessions for dynamic discovery.\n");
187 content.push_str("Use `read_file` on individual session files for full output.\n\n");
188
189 if sessions.is_empty() {
190 content.push_str("*No active terminal sessions.*\n");
191 } else {
192 content.push_str(&format!("**Active Sessions**: {}\n\n", sessions.len()));
193 content.push_str("| Session ID | Command | Working Dir | Size |\n");
194 content.push_str("|------------|---------|-------------|------|\n");
195
196 for session in sessions {
197 let cwd = session.working_dir.as_deref().unwrap_or("-");
198 let cmd_truncated = vtcode_commons::formatting::truncate_byte_budget(&session.command, 22, "...");
199
200 content.push_str(&format!(
201 "| `{}` | {} | {} | {}x{} |\n",
202 session.id,
203 cmd_truncated.replace('|', "\\|"),
204 cwd.replace('|', "\\|"),
205 session.cols,
206 session.rows
207 ));
208 }
209
210 content.push_str("\n## Session Details\n\n");
211 for session in sessions {
212 content.push_str(&format!("### {}\n\n", session.id));
213 content.push_str(&format!("- **Command**: `{}`\n", session.command));
214 if !session.args.is_empty() {
215 content.push_str(&format!("- **Args**: {}\n", session.args.join(" ")));
216 }
217 if let Some(cwd) = &session.working_dir {
218 content.push_str(&format!("- **Working Dir**: {cwd}\n"));
219 }
220 content.push_str(&format!("- **Terminal Size**: {}x{}\n", session.cols, session.rows));
221 content
222 .push_str(&format!("- **File**: `.vtcode/terminals/{}.txt`\n\n", sanitize_session_id(&session.id)));
223 }
224 }
225
226 content.push_str("---\n");
227 content.push_str("*Generated automatically. Do not edit manually.*\n");
228
229 content
230 }
231
232 pub fn terminals_dir(&self) -> std::path::PathBuf {
234 self.workspace_root.join(".vtcode").join("terminals")
235 }
236
237 pub fn close_session(&self, session_id: &str) -> Result<VTCodePtySession> {
238 self.close_session_with_mode(session_id, PtyCloseMode::Graceful)
239 }
240
241 pub fn close_session_with_mode(&self, session_id: &str, mode: PtyCloseMode) -> Result<VTCodePtySession> {
242 let handle = {
244 let mut sessions = self.inner.sessions.lock();
245 sessions
246 .remove(session_id)
247 .ok_or_else(|| anyhow!("PTY session '{session_id}' not found"))?
248 };
249
250 if mode == PtyCloseMode::Graceful {
256 let mut writer_guard = handle.writer.lock();
257 if let Some(mut writer) = writer_guard.take() {
258 let _ = writer.write_all(b"exit\n");
259 let _ = writer.flush();
260 }
261 } else {
262 drop(handle.writer.lock().take());
263 }
264
265 match mode {
269 PtyCloseMode::Graceful => handle.graceful_terminate(),
270 PtyCloseMode::Immediate => {
271 let _ = handle.force_terminate();
272 }
273 }
274
275 {
279 let mut thread_guard = handle.reader_thread.lock();
280 if let Some(reader_thread) = thread_guard.take() {
281 super::super::session::join_reader_thread_bounded(reader_thread);
282 }
283 }
284
285 Ok(handle.snapshot_metadata())
287 }
288
289 pub fn terminate_all_sessions(&self) {
290 self.terminate_all_sessions_with_mode(PtyCloseMode::Graceful);
291 }
292
293 pub fn terminate_all_sessions_with_mode(&self, mode: PtyCloseMode) {
294 let session_ids: Vec<String> = {
295 let sessions = self.inner.sessions.lock();
296 sessions.keys().cloned().collect()
297 };
298 for id in session_ids {
299 if let Err(e) = self.close_session_with_mode(&id, mode) {
300 warn!("Failed to close PTY session {}: {}", id, e);
301 }
302 }
303 }
304
305 fn session_handle(&self, session_id: &str) -> Result<Arc<PtySessionHandle>> {
306 let sessions = self.inner.sessions.lock();
307 sessions
308 .get(session_id)
309 .cloned()
310 .ok_or_else(|| anyhow!("PTY session '{session_id}' not found"))
311 }
312}