1use std::fmt;
13use std::io;
14use std::sync::Arc;
15use std::sync::Mutex as StdMutex;
16use std::sync::MutexGuard as StdMutexGuard;
17use std::sync::atomic::{AtomicBool, Ordering};
18
19use bytes::Bytes;
20use tokio::sync::{broadcast, mpsc, oneshot};
21use tokio::task::{AbortHandle, JoinHandle};
22
23const POST_EXIT_DRAIN_QUIET_MS: u64 = 50;
24const POST_EXIT_DRAIN_MAX_MS: u64 = 500;
25
26pub trait ChildTerminator: Send + Sync {
30 fn kill(&mut self) -> io::Result<()>;
32}
33
34pub trait PtyHandle: Send {}
54
55impl<T: Send> PtyHandle for T {}
56
57pub struct PtyHandles {
62 pub _slave: Option<Box<dyn PtyHandle>>,
64 pub _master: Box<dyn PtyHandle>,
66}
67
68impl fmt::Debug for PtyHandles {
69 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70 f.debug_struct("PtyHandles").finish()
71 }
72}
73
74#[derive(Clone, Copy, Debug, Default)]
84pub(crate) struct ProcessExitState {
85 status_recorded: bool,
86 observed: bool,
87 code: Option<i32>,
88}
89
90impl ProcessExitState {
91 pub(crate) fn publish(state: &StdMutex<Self>, observed: bool, code: i32) {
95 let mut guard = state.lock().unwrap_or_else(|e| e.into_inner());
96 guard.status_recorded = true;
97 guard.observed = observed;
98 guard.code = Some(code);
99 state.clear_poison();
102 }
103}
104
105pub struct ProcessHandle {
113 writer_tx: mpsc::Sender<Vec<u8>>,
114 output_tx: broadcast::Sender<Bytes>,
115 killer: StdMutex<Option<Box<dyn ChildTerminator>>>,
116 reader_handle: StdMutex<Option<JoinHandle<()>>>,
117 reader_abort_handles: StdMutex<Vec<AbortHandle>>,
118 writer_handle: StdMutex<Option<JoinHandle<()>>>,
119 wait_handle: StdMutex<Option<JoinHandle<()>>>,
120 exit_state: Arc<StdMutex<ProcessExitState>>,
121 _pty_handles: StdMutex<Option<PtyHandles>>,
123}
124
125impl fmt::Debug for ProcessHandle {
126 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127 f.debug_struct("ProcessHandle")
128 .field("has_exited", &self.has_exited())
129 .field("exit_code", &self.exit_code())
130 .finish()
131 }
132}
133
134impl ProcessHandle {
135 #[allow(
137 clippy::too_many_arguments,
138 reason = "Intentional compatibility, platform, or test-only suppression."
139 )]
140 pub(crate) fn new(
141 writer_tx: mpsc::Sender<Vec<u8>>,
142 output_tx: broadcast::Sender<Bytes>,
143 initial_output_rx: broadcast::Receiver<Bytes>,
144 killer: Box<dyn ChildTerminator>,
145 reader_handle: JoinHandle<()>,
146 reader_abort_handles: Vec<AbortHandle>,
147 writer_handle: JoinHandle<()>,
148 wait_handle: JoinHandle<()>,
149 exit_state: Arc<StdMutex<ProcessExitState>>,
150 pty_handles: Option<PtyHandles>,
151 ) -> (Self, broadcast::Receiver<Bytes>) {
152 (
153 Self {
154 writer_tx,
155 output_tx,
156 killer: StdMutex::new(Some(killer)),
157 reader_handle: StdMutex::new(Some(reader_handle)),
158 reader_abort_handles: StdMutex::new(reader_abort_handles),
159 writer_handle: StdMutex::new(Some(writer_handle)),
160 wait_handle: StdMutex::new(Some(wait_handle)),
161 exit_state,
162 _pty_handles: StdMutex::new(pty_handles),
163 },
164 initial_output_rx,
165 )
166 }
167
168 fn exit_state(&self) -> StdMutexGuard<'_, ProcessExitState> {
172 self.exit_state.lock().unwrap_or_else(|e| e.into_inner())
173 }
174
175 #[inline]
183 pub fn writer_sender(&self) -> mpsc::Sender<Vec<u8>> {
184 self.writer_tx.clone()
185 }
186
187 #[inline]
192 pub fn output_receiver(&self) -> broadcast::Receiver<Bytes> {
193 self.output_tx.subscribe()
194 }
195
196 #[inline]
199 pub fn has_exited(&self) -> bool {
200 self.exit_state().status_recorded
201 }
202
203 #[inline]
206 pub fn has_observed_exit(&self) -> bool {
207 self.exit_state().observed
208 }
209
210 #[inline]
212 pub fn exit_code(&self) -> Option<i32> {
213 self.exit_state().code
214 }
215
216 #[inline]
218 pub fn is_output_drained(&self) -> bool {
219 self.reader_handle
220 .lock()
221 .ok()
222 .and_then(|guard| guard.as_ref().map(JoinHandle::is_finished))
223 .unwrap_or(true)
224 }
225
226 pub fn terminate(&self) {
230 self.terminate_internal();
231 }
232
233 pub fn terminate_process(&self) {
239 let _ = self.try_terminate_process();
240 }
241
242 pub fn try_terminate_process(&self) -> io::Result<()> {
248 let mut killer = self
249 .killer
250 .lock()
251 .map_err(|_error| io::Error::other("process termination lock poisoned"))?;
252 if let Some(terminator) = killer.as_mut() {
253 terminator.kill()?;
254 *killer = None;
255 }
256 Ok(())
257 }
258
259 fn terminate_internal(&self) {
261 if let Ok(mut killer_opt) = self.killer.lock()
263 && let Some(mut killer) = killer_opt.take()
264 {
265 let _ = killer.kill();
266 }
267
268 self.abort_tasks();
269 }
270
271 fn abort_tasks(&self) {
273 if let Ok(mut h) = self.reader_handle.lock()
275 && let Some(handle) = h.take()
276 {
277 handle.abort();
278 }
279
280 if let Ok(mut handles) = self.reader_abort_handles.lock() {
282 for handle in handles.drain(..) {
283 handle.abort();
284 }
285 }
286
287 if let Ok(mut h) = self.writer_handle.lock()
289 && let Some(handle) = h.take()
290 {
291 handle.abort();
292 }
293
294 if let Ok(mut h) = self.wait_handle.lock()
296 && let Some(handle) = h.take()
297 {
298 handle.abort();
299 }
300 }
301
302 #[inline]
304 pub fn is_running(&self) -> bool {
305 !self.has_exited() && !self.is_writer_closed()
306 }
307
308 pub async fn write(&self, bytes: impl Into<Vec<u8>>) -> Result<(), mpsc::error::SendError<Vec<u8>>> {
312 self.writer_tx.send(bytes.into()).await
313 }
314
315 #[inline]
317 pub fn is_writer_closed(&self) -> bool {
318 self.writer_tx.is_closed()
319 }
320}
321
322impl Drop for ProcessHandle {
323 fn drop(&mut self) {
324 self.terminate_internal();
334 }
335}
336
337#[derive(Debug)]
341pub struct SpawnedProcess {
342 pub session: ProcessHandle,
344 pub process_id: u32,
346 pub output_rx: broadcast::Receiver<Bytes>,
348 pub reliable_output_rx: mpsc::Receiver<Bytes>,
352 pub(crate) reliable_output_enabled: bool,
354 pub exit_rx: oneshot::Receiver<i32>,
356}
357
358impl SpawnedProcess {
359 pub async fn wait_with_output(self, timeout_ms: u64) -> (Vec<u8>, i32) {
363 if self.reliable_output_enabled {
364 collect_reliable_output_until_exit(self.reliable_output_rx, self.exit_rx, timeout_ms).await
365 } else {
366 collect_output_until_exit(self.output_rx, self.exit_rx, timeout_ms).await
367 }
368 }
369}
370
371async fn collect_reliable_output_until_exit(
373 mut output_rx: mpsc::Receiver<Bytes>,
374 exit_rx: oneshot::Receiver<i32>,
375 timeout_ms: u64,
376) -> (Vec<u8>, i32) {
377 let mut collected = Vec::new();
378 let deadline = tokio::time::Instant::now() + tokio::time::Duration::from_millis(timeout_ms);
379 tokio::pin!(exit_rx);
380
381 loop {
382 tokio::select! {
383 chunk = output_rx.recv() => {
384 if let Some(chunk) = chunk {
385 collected.extend_from_slice(&chunk);
386 } else {
387 return (collected, exit_rx.await.unwrap_or(-1));
388 }
389 }
390 res = &mut exit_rx => {
391 let code = res.unwrap_or(-1);
392 let quiet = tokio::time::Duration::from_millis(POST_EXIT_DRAIN_QUIET_MS);
397 let max_deadline = tokio::time::Instant::now()
398 + tokio::time::Duration::from_millis(POST_EXIT_DRAIN_MAX_MS);
399 while tokio::time::Instant::now() < max_deadline {
400 match tokio::time::timeout(quiet, output_rx.recv()).await {
401 Ok(Some(chunk)) => collected.extend_from_slice(&chunk),
402 Ok(None) | Err(_) => break,
403 }
404 }
405 return (collected, code);
406 }
407 _ = tokio::time::sleep_until(deadline) => {
408 return (collected, -1);
409 }
410 }
411 }
412}
413
414pub async fn collect_output_until_exit(
418 mut output_rx: broadcast::Receiver<Bytes>,
419 exit_rx: oneshot::Receiver<i32>,
420 timeout_ms: u64,
421) -> (Vec<u8>, i32) {
422 let mut collected = Vec::new();
423 let deadline = tokio::time::Instant::now() + tokio::time::Duration::from_millis(timeout_ms);
424 tokio::pin!(exit_rx);
425
426 loop {
427 tokio::select! {
428 res = output_rx.recv() => {
429 if let Ok(chunk) = res {
430 collected.extend_from_slice(&chunk);
431 }
432 }
433 res = &mut exit_rx => {
434 let code = res.unwrap_or(-1);
435 let quiet = tokio::time::Duration::from_millis(POST_EXIT_DRAIN_QUIET_MS);
437 let max_deadline = tokio::time::Instant::now()
438 + tokio::time::Duration::from_millis(POST_EXIT_DRAIN_MAX_MS);
439
440 while tokio::time::Instant::now() < max_deadline {
441 match tokio::time::timeout(quiet, output_rx.recv()).await {
442 Ok(Ok(chunk)) => collected.extend_from_slice(&chunk),
443 Ok(Err(broadcast::error::RecvError::Lagged(count))) => {
444 vtcode_commons::diagnostics::stderr(format_args!("Warning: output stream lagged ({count} dropped)"));
445 continue;
446 }
447 Ok(Err(broadcast::error::RecvError::Closed)) => break,
448 Err(_) => break, }
450 }
451 return (collected, code);
452 }
453 _ = tokio::time::sleep_until(deadline) => {
454 return (collected, -1);
455 }
456 }
457 }
458}
459
460pub type ExecCommandSession = ProcessHandle;
462
463pub type SpawnedPty = SpawnedProcess;
465
466#[cfg(test)]
467mod tests {
468 use super::*;
469
470 struct NoopTerminator;
471 impl ChildTerminator for NoopTerminator {
472 fn kill(&mut self) -> io::Result<()> {
473 Ok(())
474 }
475 }
476
477 fn fresh_exit_state() -> Arc<StdMutex<ProcessExitState>> {
478 Arc::new(StdMutex::new(ProcessExitState::default()))
479 }
480
481 #[tokio::test]
482 async fn test_process_handle_debug() {
483 let (writer_tx, _) = mpsc::channel(1);
485 let (output_tx, initial_rx) = broadcast::channel(1);
486
487 let (handle, _) = ProcessHandle::new(
488 writer_tx,
489 output_tx,
490 initial_rx,
491 Box::new(NoopTerminator),
492 tokio::spawn(async {}),
493 vec![],
494 tokio::spawn(async {}),
495 tokio::spawn(async {}),
496 fresh_exit_state(),
497 None,
498 );
499
500 let debug_str = format!("{handle:?}");
501 assert!(debug_str.contains("ProcessHandle"));
502 }
503
504 #[tokio::test]
505 async fn exit_facts_are_one_coherent_snapshot() {
506 let exit_state = fresh_exit_state();
507
508 let (writer_tx, _) = mpsc::channel(1);
509 let (output_tx, initial_rx) = broadcast::channel(1);
510
511 let (handle, _) = ProcessHandle::new(
512 writer_tx,
513 output_tx,
514 initial_rx,
515 Box::new(NoopTerminator),
516 tokio::spawn(async {}),
517 vec![],
518 tokio::spawn(async {}),
519 tokio::spawn(async {}),
520 Arc::clone(&exit_state),
521 None,
522 );
523
524 assert!(!handle.has_exited());
525 assert!(!handle.has_observed_exit());
526 assert_eq!(handle.exit_code(), None);
527
528 ProcessExitState::publish(&exit_state, false, -1);
532 assert!(handle.has_exited());
533 assert!(!handle.has_observed_exit(), "a completed wait is not necessarily a successful wait");
534 assert_eq!(handle.exit_code(), Some(-1));
535
536 ProcessExitState::publish(&exit_state, true, 7);
537 assert!(handle.has_exited());
538 assert!(handle.has_observed_exit());
539 assert_eq!(handle.exit_code(), Some(7));
540 }
541
542 #[tokio::test]
543 async fn poisoned_exit_state_recovers_and_publish_clears_poison() {
544 let exit_state = fresh_exit_state();
545 let poisoner = Arc::clone(&exit_state);
546 let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
547 let _guard = poisoner.lock().unwrap();
548 panic!("intentional poison of exit state");
549 }));
550 assert!(outcome.is_err());
551 assert!(exit_state.is_poisoned());
552
553 let (writer_tx, _) = mpsc::channel(1);
554 let (output_tx, initial_rx) = broadcast::channel(1);
555 let (handle, _) = ProcessHandle::new(
556 writer_tx,
557 output_tx,
558 initial_rx,
559 Box::new(NoopTerminator),
560 tokio::spawn(async {}),
561 vec![],
562 tokio::spawn(async {}),
563 tokio::spawn(async {}),
564 Arc::clone(&exit_state),
565 None,
566 );
567
568 assert!(!handle.has_exited());
570 assert_eq!(handle.exit_code(), None);
571
572 ProcessExitState::publish(&exit_state, true, 5);
574 assert!(!exit_state.is_poisoned());
575 assert!(handle.has_exited());
576 assert!(handle.has_observed_exit());
577 assert_eq!(handle.exit_code(), Some(5));
578 }
579
580 struct RecordingTerminator(Arc<AtomicBool>);
581 impl ChildTerminator for RecordingTerminator {
582 fn kill(&mut self) -> io::Result<()> {
583 self.0.store(true, Ordering::SeqCst);
584 Ok(())
585 }
586 }
587
588 struct FailOnceTerminator(Arc<std::sync::atomic::AtomicUsize>);
589 impl ChildTerminator for FailOnceTerminator {
590 fn kill(&mut self) -> io::Result<()> {
591 if self.0.fetch_add(1, Ordering::SeqCst) == 0 {
592 Err(io::Error::other("simulated kill failure"))
593 } else {
594 Ok(())
595 }
596 }
597 }
598
599 #[tokio::test]
600 async fn failed_termination_retains_the_handle_for_retry() {
601 let attempts = Arc::new(std::sync::atomic::AtomicUsize::new(0));
602 let (writer_tx, _) = mpsc::channel(1);
603 let (output_tx, initial_rx) = broadcast::channel(1);
604 let (handle, _) = ProcessHandle::new(
605 writer_tx,
606 output_tx,
607 initial_rx,
608 Box::new(FailOnceTerminator(Arc::clone(&attempts))),
609 tokio::spawn(async {}),
610 vec![],
611 tokio::spawn(async {}),
612 tokio::spawn(async {}),
613 fresh_exit_state(),
614 None,
615 );
616 assert!(handle.try_terminate_process().is_err());
617 assert!(handle.try_terminate_process().is_ok());
618 assert!(handle.try_terminate_process().is_ok());
619 assert_eq!(attempts.load(Ordering::SeqCst), 2);
620 }
621
622 #[tokio::test]
627 async fn drop_kills_child_synchronously_without_bridging_runtime() {
628 let killed = Arc::new(AtomicBool::new(false));
629 let (writer_tx, _) = mpsc::channel(1);
630 let (output_tx, initial_rx) = broadcast::channel(1);
631
632 let (handle, _) = ProcessHandle::new(
634 writer_tx,
635 output_tx,
636 initial_rx,
637 Box::new(RecordingTerminator(Arc::clone(&killed))),
638 tokio::spawn(std::future::pending()),
639 vec![],
640 tokio::spawn(std::future::pending()),
641 tokio::spawn(std::future::pending()),
642 fresh_exit_state(),
643 None,
644 );
645
646 let started = std::time::Instant::now();
647 drop(handle);
648 assert!(killed.load(Ordering::SeqCst), "Drop must kill the child");
649 assert!(started.elapsed() < std::time::Duration::from_millis(250), "Drop must not block on async cleanup");
650 }
651}