Allow ConPTY output to close after the last console client exits (#45504)

## Why

Retaining the pseudoconsole's creation pipe handles prevents output readers from seeing EOF while the session remains alive.

## What changed

Drop the creation handles after a successful process spawn and call `ReleasePseudoConsole` when available on Windows 11 24H2 or newer. This lets output close after the last attached client exits while preserving I/O for surviving console descendants. Older Windows versions retain the `ClosePseudoConsole` cleanup path on drop.

## Testing

Add Windows lifecycle tests for output closure after normal exit and termination while retaining the session, plus continued input and output for a surviving console child. These tests skip when `ReleasePseudoConsole` is unavailable.

GitOrigin-RevId: fb1094fb2a570e6fec0cc80d6356f5d7eb1edcbf
This commit is contained in:
iceweasel-oai authored and copyberry committed 2026-09-14 19:38:45 +00:00
1 parent 973ec2942c
commit 6ce16aadce
4 files changed
+168 -9

No files matched your search

+1 -1
View File
@@ -17,7 +17,7 @@ use crate::spawn_pty_process;
#[path = "windows_tests.rs"]
mod windows_tests;
fn find_python() -> Option<String> {
pub(super) fn find_python() -> Option<String> {
for candidate in ["python3", "python"] {
if let Ok(output) = std::process::Command::new(candidate)
.arg("--version")
+1 -1
View File
@@ -185,7 +185,7 @@ impl MasterPty for ConPtyMasterPty {
impl SlavePty for ConPtySlavePty {
fn spawn_command(&self, cmd: CommandBuilder) -> anyhow::Result<Box<dyn Child + Send + Sync>> {
let inner = self.inner.lock().unwrap();
let mut inner = self.inner.lock().unwrap();
let child = inner.con.spawn_command(cmd)?;
Ok(Box::new(child))
}
+26 -7
View File
@@ -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> =
ConPtyReleaseFuncs::open(Path::new("kernel32.dll")).ok();
}
pub fn conpty_supported() -> bool {
@@ -109,10 +115,9 @@ fn windows_build_number() -> Option<u32> {
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<WinChild> {
pub fn spawn_command(&mut self, cmd: CommandBuilder) -> anyhow::Result<WinChild> {
let job = Arc::new(JobObject::create()?);
let mut si: STARTUPINFOEXW = unsafe { mem::zeroed() };
si.StartupInfo.cb = mem::size_of::<STARTUPINFOEXW>() 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<Vec<u16>> {
let home = cmd
.get_env("USERPROFILE")
@@ -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<String, String> = 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<String, String> = 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<String, String> = 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(())
}