diff --git a/codex-rs/utils/pty/src/tests.rs b/codex-rs/utils/pty/src/tests.rs index b3d732bf85..8a7cca2499 100644 --- a/codex-rs/utils/pty/src/tests.rs +++ b/codex-rs/utils/pty/src/tests.rs @@ -17,7 +17,7 @@ use crate::spawn_pty_process; #[path = "windows_tests.rs"] mod windows_tests; -fn find_python() -> Option { +pub(super) fn find_python() -> Option { for candidate in ["python3", "python"] { if let Ok(output) = std::process::Command::new(candidate) .arg("--version") diff --git a/codex-rs/utils/pty/src/win/conpty.rs b/codex-rs/utils/pty/src/win/conpty.rs index c147b6d106..26bc61ab5a 100644 --- a/codex-rs/utils/pty/src/win/conpty.rs +++ b/codex-rs/utils/pty/src/win/conpty.rs @@ -185,7 +185,7 @@ impl MasterPty for ConPtyMasterPty { impl SlavePty for ConPtySlavePty { fn spawn_command(&self, cmd: CommandBuilder) -> anyhow::Result> { - let inner = self.inner.lock().unwrap(); + let mut inner = self.inner.lock().unwrap(); let child = inner.con.spawn_command(cmd)?; Ok(Box::new(child)) } diff --git a/codex-rs/utils/pty/src/win/psuedocon.rs b/codex-rs/utils/pty/src/win/psuedocon.rs index d4c3a41c68..1b83478ca6 100644 --- a/codex-rs/utils/pty/src/win/psuedocon.rs +++ b/codex-rs/utils/pty/src/win/psuedocon.rs @@ -79,6 +79,10 @@ shared_library!(ConPtyFuncs, pub fn ClosePseudoConsole(hpc: HPCON), ); +shared_library!(ConPtyReleaseFuncs, + pub fn ReleasePseudoConsole(hpc: HPCON) -> HRESULT, +); + shared_library!(Ntdll, pub fn RtlGetVersion( version_info: *mut OSVERSIONINFOW @@ -89,6 +93,8 @@ lazy_static! { static ref CONPTY: ConPtyFuncs = ConPtyFuncs::open(Path::new("kernel32.dll")).expect( "this system does not support conpty. Windows 10 October 2018 or newer is required", ); + static ref CONPTY_RELEASE: Option = + ConPtyReleaseFuncs::open(Path::new("kernel32.dll")).ok(); } pub fn conpty_supported() -> bool { @@ -109,10 +115,9 @@ fn windows_build_number() -> Option { pub struct PsuedoCon { con: HPCON, - // CreatePseudoConsole borrows these pipe handles for the lifetime of the - // pseudoconsole, so we must keep owning them until ClosePseudoConsole. - _input: FileDescriptor, - _output: FileDescriptor, + // Retain the creation handles until a client has attached. Keeping the + // output write handle afterward would prevent the reader from seeing EOF. + creation_handles: Option<(FileDescriptor, FileDescriptor)>, } unsafe impl Send for PsuedoCon {} @@ -146,8 +151,7 @@ impl PsuedoCon { ); Ok(Self { con, - _input: input, - _output: output, + creation_handles: Some((input, output)), }) } @@ -163,7 +167,7 @@ impl PsuedoCon { Ok(()) } - pub fn spawn_command(&self, cmd: CommandBuilder) -> anyhow::Result { + pub fn spawn_command(&mut self, cmd: CommandBuilder) -> anyhow::Result { let job = Arc::new(JobObject::create()?); let mut si: STARTUPINFOEXW = unsafe { mem::zeroed() }; si.StartupInfo.cb = mem::size_of::() as u32; @@ -214,10 +218,25 @@ impl PsuedoCon { let _main_thread = unsafe { OwnedHandle::from_raw_handle(pi.hThread as _) }; let proc = unsafe { OwnedHandle::from_raw_handle(pi.hProcess as _) }; + self.creation_handles.take(); + // Windows 11 24H2+ lets the console close its output after the last + // attached client exits, without terminating surviving descendants. + // Older Windows retains its existing ClosePseudoConsole-on-drop path. + if let Some(release) = CONPTY_RELEASE.as_ref() { + let result = unsafe { (release.ReleasePseudoConsole)(self.con) }; + if result != S_OK { + log::warn!("failed to release pseudoconsole ownership: HRESULT {result}"); + } + } + Ok(WinChild::new(proc, job)) } } +#[cfg(test)] +#[path = "psuedocon_tests.rs"] +mod lifecycle_tests; + fn resolve_current_directory(cmd: &CommandBuilder) -> Option> { let home = cmd .get_env("USERPROFILE") diff --git a/codex-rs/utils/pty/src/win/psuedocon_tests.rs b/codex-rs/utils/pty/src/win/psuedocon_tests.rs new file mode 100644 index 0000000000..53ef224511 --- /dev/null +++ b/codex-rs/utils/pty/src/win/psuedocon_tests.rs @@ -0,0 +1,140 @@ +//! Verify natural and terminated console clients close output without losing descendants. + +use std::collections::HashMap; +use std::path::Path; +use std::time::Duration; + +use pretty_assertions::assert_eq; + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn output_closes_after_client_exit_while_session_is_retained() -> anyhow::Result<()> { + if super::CONPTY_RELEASE.is_none() { + eprintln!("automatic ConPTY closure requires Windows 11 24H2 or newer"); + return Ok(()); + } + let env: HashMap = std::env::vars().collect(); + let spawned = crate::spawn_pty_process( + "cmd.exe", + &[ + "/d".to_string(), + "/c".to_string(), + "echo complete".to_string(), + ], + Path::new("."), + &env, + /*arg0*/ &None, + crate::TerminalSize::default(), + &[], + ) + .await?; + let mut output = spawned.stdout_rx; + let bytes = tokio::time::timeout(Duration::from_secs(5), async { + let mut bytes = Vec::new(); + while let Some(chunk) = output.recv().await { + bytes.extend(chunk); + } + bytes + }) + .await?; + assert!(String::from_utf8_lossy(&bytes).contains("complete")); + assert_eq!(spawned.exit_rx.await?, 0); + assert!(spawned.session.has_exited()); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn output_remains_open_for_surviving_console_child() -> anyhow::Result<()> { + if super::CONPTY_RELEASE.is_none() { + eprintln!("automatic ConPTY closure requires Windows 11 24H2 or newer"); + return Ok(()); + } + let Some(python) = crate::tests::find_python() else { + eprintln!("python not found; skipping ConPTY surviving-child test"); + return Ok(()); + }; + let env: HashMap = std::env::vars().collect(); + let spawned = crate::spawn_pty_process( + &python, + &[ + "-u".to_string(), + "-c".to_string(), + "import subprocess,sys; subprocess.Popen([sys.executable,'-u','-c',sys.argv[1]])".to_string(), + "import sys; print('child-ready',flush=True); line=sys.stdin.readline().strip(); print('child-received:'+line,flush=True)".to_string(), + ], + Path::new("."), + &env, + /*arg0*/ &None, + crate::TerminalSize::default(), + &[], + ) + .await?; + let mut output = spawned.stdout_rx; + assert_eq!( + tokio::time::timeout(Duration::from_secs(5), spawned.exit_rx).await??, + 0 + ); + let mut bytes = Vec::new(); + tokio::time::timeout(Duration::from_secs(5), async { + while !String::from_utf8_lossy(&bytes).contains("child-ready") { + bytes.extend( + output + .recv() + .await + .expect("child output closed before readiness"), + ); + } + spawned + .session + .writer_sender() + .send(b"continued\r".to_vec()) + .await?; + while let Some(chunk) = output.recv().await { + bytes.extend(chunk); + } + Ok::<_, anyhow::Error>(()) + }) + .await??; + assert!(String::from_utf8_lossy(&bytes).contains("child-received:continued")); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn output_closes_after_termination_while_session_is_retained() -> anyhow::Result<()> { + if super::CONPTY_RELEASE.is_none() { + eprintln!("automatic ConPTY closure requires Windows 11 24H2 or newer"); + return Ok(()); + } + let env: HashMap = std::env::vars().collect(); + let spawned = crate::spawn_pty_process( + "cmd.exe", + &[ + "/d".to_string(), + "/c".to_string(), + "set /p line=child-ready".to_string(), + ], + Path::new("."), + &env, + /*arg0*/ &None, + crate::TerminalSize::default(), + &[], + ) + .await?; + let mut output = spawned.stdout_rx; + tokio::time::timeout(Duration::from_secs(5), async { + let mut bytes = Vec::new(); + while !String::from_utf8_lossy(&bytes).contains("child-ready") { + bytes.extend( + output + .recv() + .await + .expect("child output closed before readiness"), + ); + } + spawned.session.request_terminate(); + while output.recv().await.is_some() {} + }) + .await?; + assert_ne!(spawned.exit_rx.await?, 0); + assert!(spawned.session.has_exited()); + Ok(()) +}