A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.
Rust agentagent-orchestrationaiai-agentsclaude-codecodexcoding-agentlinuxmacosmultiplayermultiplexerrustterminalterminal-emulatorterminal-multiplexertmuxtuiweztermwindows
feat(pty): let a Windows pseudo console be handed to another process
RoversX4c7def53982a
diff --git a/pty/Cargo.toml b/pty/Cargo.tomlindex fed6ae3c..9c706ade 100644--- a/pty/Cargo.toml+++ b/pty/Cargo.toml@@ -32,8 +32,11 @@ winapi = { workspace=true, features = ["consoleapi","handleapi","fileapi",+ "libloaderapi","namedpipeapi",+ "processthreadsapi","synchapi",+ "winbase",]}winreg.workspace = truediff --git a/pty/src/lib.rs b/pty/src/lib.rsindex 9e56c0de..b0247086 100644--- a/pty/src/lib.rs+++ b/pty/src/lib.rs@@ -122,6 +122,13 @@ pub trait MasterPty: Downcast + Send {fn get_termios(&self) -> Option<nix::sys::termios::Termios> {None}++ /// Duplicates of the handles a successor process needs to adopt this+ /// pseudo console; only a ConPTY has them.+ #[cfg(windows)]+ fn conpty_handoff(&self) -> Result<win::conpty::ConPtyHandoff, Error> {+ anyhow::bail!("this pty cannot be handed over")+ }}impl_downcast!(MasterPty);diff --git a/pty/src/win/conpty.rs b/pty/src/win/conpty.rsindex 0e9a18c6..2aad0107 100644--- a/pty/src/win/conpty.rs+++ b/pty/src/win/conpty.rs@@ -3,9 +3,92 @@ use crate::win::psuedocon::PsuedoCon;use crate::{Child, MasterPty, PtyPair, PtySize, PtySystem, SlavePty};use anyhow::Error;use filedescriptor::{FileDescriptor, Pipe};+use std::os::windows::io::{AsRawHandle, FromRawHandle, IntoRawHandle, OwnedHandle};use std::sync::{Arc, Mutex};use winapi::um::wincon::COORD;+/// A pseudo console as handles another process can adopt: what one mux+/// server hands to its successor for each pane. See+/// `MasterPty::conpty_handoff` and `master_from_handoff`.+pub struct ConPtyHandoff {+ /// The pipe the program's input is written to.+ pub input: OwnedHandle,+ /// The pipe the program's output is read from.+ pub output: OwnedHandle,+ /// The pseudo console: its signal pipe, its reference and the console+ /// host process.+ pub console: [OwnedHandle; 3],+}++impl ConPtyHandoff {+ /// How many handles `into_handles` yields and `from_handles` takes.+ pub const HANDLES: usize = 5;++ pub fn into_handles(self) -> Vec<OwnedHandle> {+ let [signal, reference, server] = self.console;+ vec![self.input, self.output, signal, reference, server]+ }++ pub fn from_handles(handles: Vec<OwnedHandle>) -> anyhow::Result<Self> {+ let count = handles.len();+ let mut handles = handles.into_iter();+ match (+ handles.next(),+ handles.next(),+ handles.next(),+ handles.next(),+ handles.next(),+ handles.next(),+ ) {+ (Some(input), Some(output), Some(signal), Some(reference), Some(server), None) => {+ Ok(Self {+ input,+ output,+ console: [signal, reference, server],+ })+ }+ _ => anyhow::bail!(+ "a pseudo console is {} handles, not {count}",+ Self::HANDLES+ ),+ }+ }+}++/// Whether this process's pseudo consoles can be handed over at all: not+/// with the system's own, without the conpty.dll shipped alongside.+pub fn handoff_supported() -> bool {+ crate::win::psuedocon::handoff_supported()+}++/// The pty of a pane a predecessor handed over, from its handles. `size` is+/// what the pane last knew; the console host keeps its own.+pub fn master_from_handoff(+ handoff: ConPtyHandoff,+ size: PtySize,+) -> anyhow::Result<Box<dyn MasterPty + Send>> {+ let ConPtyHandoff {+ input,+ output,+ console,+ } = handoff;+ let con = PsuedoCon::from_handoff(console)?;+ Ok(Box::new(ConPtyMasterPty {+ inner: Arc::new(Mutex::new(Inner {+ con,+ readable: unsafe { FileDescriptor::from_raw_handle(output.into_raw_handle()) },+ writable: Some(unsafe { FileDescriptor::from_raw_handle(input.into_raw_handle()) }),+ input_for_handoff: None,+ size,+ })),+ }))+}++fn owned(fd: &FileDescriptor) -> anyhow::Result<OwnedHandle> {+ Ok(unsafe { std::os::windows::io::BorrowedHandle::borrow_raw(fd.as_raw_handle()) }+ .try_clone_to_owned()?)+}+#[derive(Default)]pub struct ConPtySystem {}@@ -28,6 +111,7 @@ impl PtySystem for ConPtySystem {con,readable: stdout.read,writable: Some(stdin.write),+ input_for_handoff: None,size,})),};@@ -47,6 +131,9 @@ struct Inner {con: PsuedoCon,readable: FileDescriptor,writable: Option<FileDescriptor>,+ /// A second handle on the input pipe once the writer is taken, for a+ /// handoff: the writer itself goes where this side cannot reach it.+ input_for_handoff: Option<FileDescriptor>,size: PtySize,}@@ -97,14 +184,27 @@ impl MasterPty for ConPtyMasterPty {}fn take_writer(&self) -> anyhow::Result<Box<dyn std::io::Write + Send>> {- Ok(Box::new(- self.inner- .lock()- .unwrap()- .writable- .take()- .ok_or_else(|| anyhow::anyhow!("writer already taken"))?,- ))+ let mut inner = self.inner.lock().unwrap();+ let writer = inner+ .writable+ .take()+ .ok_or_else(|| anyhow::anyhow!("writer already taken"))?;+ inner.input_for_handoff = writer.try_clone().ok();+ Ok(Box::new(writer))+ }++ fn conpty_handoff(&self) -> anyhow::Result<ConPtyHandoff> {+ let inner = self.inner.lock().unwrap();+ let input = inner+ .writable+ .as_ref()+ .or(inner.input_for_handoff.as_ref())+ .ok_or_else(|| anyhow::anyhow!("the pty's input pipe is gone"))?;+ Ok(ConPtyHandoff {+ input: owned(input)?,+ output: owned(&inner.readable)?,+ console: inner.con.handoff_handles()?,+ })}}diff --git a/pty/src/win/mod.rs b/pty/src/win/mod.rsindex 24f8f536..11662de3 100644--- a/pty/src/win/mod.rs+++ b/pty/src/win/mod.rs@@ -17,6 +17,33 @@ mod psuedocon;use filedescriptor::OwnedHandle;+/// The file name of the program `process` runs, e.g. `OpenConsole.exe`.+pub fn process_image_name(process: &impl AsRawHandle) -> IoResult<String> {+ use winapi::um::winbase::QueryFullProcessImageNameW;+ let mut buf = vec![0u16; 32 * 1024];+ let mut len = buf.len() as DWORD;+ let ok = unsafe {+ QueryFullProcessImageNameW(process.as_raw_handle() as _, 0, buf.as_mut_ptr(), &mut len)+ };+ if ok == 0 {+ return Err(IoError::last_os_error());+ }+ let path = std::path::PathBuf::from(String::from_utf16_lossy(&buf[..len as usize]));+ Ok(path+ .file_name()+ .map(|name| name.to_string_lossy().into_owned())+ .unwrap_or_default())+}++/// A process another server spawned and handed over with its pane, as the+/// process handle that server held.+pub fn adopted_child(process: std::os::windows::io::OwnedHandle) -> Box<dyn Child + Send + Sync> {+ use std::os::windows::io::{FromRawHandle, IntoRawHandle};+ Box::new(WinChild {+ proc: Mutex::new(unsafe { OwnedHandle::from_raw_handle(process.into_raw_handle()) }),+ })+}+#[derive(Debug)]pub struct WinChild {proc: Mutex<OwnedHandle>,diff --git a/pty/src/win/psuedocon.rs b/pty/src/win/psuedocon.rsindex 13c7c5db..f492e941 100644--- a/pty/src/win/psuedocon.rs+++ b/pty/src/win/psuedocon.rs@@ -8,14 +8,19 @@ use shared_library::shared_library;use std::ffi::OsString;use std::io::Error as IoError;use std::os::windows::ffi::OsStringExt;-use std::os::windows::io::{AsRawHandle, FromRawHandle};+use std::os::windows::io::{+ AsRawHandle, BorrowedHandle, FromRawHandle, IntoRawHandle, OwnedHandle as StdOwnedHandle,+};use std::path::Path;use std::sync::Mutex;use std::{mem, ptr};use winapi::shared::minwindef::DWORD;use winapi::shared::winerror::{HRESULT, S_OK};+use winapi::um::fileapi::GetFileType;use winapi::um::handleapi::*;+use winapi::um::libloaderapi::{GetModuleHandleW, GetProcAddress};use winapi::um::processthreadsapi::*;+use winapi::um::winbase::FILE_TYPE_PIPE;use winapi::um::winbase::{CREATE_UNICODE_ENVIRONMENT, EXTENDED_STARTUPINFO_PRESENT, STARTF_USESTDHANDLES, STARTUPINFOEXW,};@@ -42,7 +47,18 @@ shared_library!(ConPtyFuncs,pub fn ClosePseudoConsole(hpc: HPCON),);-fn load_conpty() -> ConPtyFuncs {+/// `ConptyPackPseudoConsole(hServerProcess, hRef, hSignal, phPC)`: a pseudo+/// console made of handles another process handed over.+type PackPseudoConsole = unsafe extern "system" fn(HANDLE, HANDLE, HANDLE, *mut HPCON) -> HRESULT;++struct ConPty {+ funcs: ConPtyFuncs,+ /// Only the conpty.dll shipped alongside has it; with the system's+ /// pseudo console nothing can be handed over.+ pack: Option<PackPseudoConsole>,+}++fn load_conpty() -> ConPty {// If the kernel doesn't export these functions then their system is// too old and we cannot run.let kernel = ConPtyFuncs::open(Path::new("kernel32.dll")).expect(@@ -53,14 +69,41 @@ fn load_conpty() -> ConPtyFuncs {// alongside the application. We check for this after checking for kernel// support so that we don't try to proceed and do something crazy.if let Ok(sideloaded) = ConPtyFuncs::open(Path::new("conpty.dll")) {- sideloaded+ ConPty {+ funcs: sideloaded,+ pack: sideloaded_pack_function(),+ }+ } else {+ ConPty {+ funcs: kernel,+ pack: None,+ }+ }+}++fn sideloaded_pack_function() -> Option<PackPseudoConsole> {+ let name: Vec<u16> = "conpty.dll\0".encode_utf16().collect();+ let module = unsafe { GetModuleHandleW(name.as_ptr()) };+ if module.is_null() {+ return None;+ }+ let function =+ unsafe { GetProcAddress(module, b"ConptyPackPseudoConsole\0".as_ptr() as *const i8) };+ if function.is_null() {+ None} else {- kernel+ Some(unsafe { mem::transmute::<_, PackPseudoConsole>(function) })}}lazy_static! {- static ref CONPTY: ConPtyFuncs = load_conpty();+ static ref CONPTY: ConPty = load_conpty();+}++/// Whether the pseudo consoles of this process can be handed to another:+/// only with the conpty.dll shipped alongside.+pub fn handoff_supported() -> bool {+ CONPTY.pack.is_some()}pub struct PsuedoCon {@@ -72,15 +115,78 @@ unsafe impl Sync for PsuedoCon {}impl Drop for PsuedoCon {fn drop(&mut self) {- unsafe { (CONPTY.ClosePseudoConsole)(self.con) };+ unsafe { (CONPTY.funcs.ClosePseudoConsole)(self.con) };}}impl PsuedoCon {+ /// Duplicates of the three handles the pseudo console is made of -- its+ /// signal pipe, the reference that keeps it open and the console host+ /// process, in that order -- for a successor process to rebuild it with+ /// `from_handoff`. conpty.dll has no function that returns them: its+ /// HPCON points at exactly these three, so they are read from there, and+ /// only from the conpty.dll shipped alongside, which can pack them again.+ /// What is read is checked before it is used.+ pub fn handoff_handles(&self) -> Result<[StdOwnedHandle; 3], Error> {+ ensure!(+ CONPTY.pack.is_some(),+ "the system's pseudo console cannot be handed over"+ );+ let [signal, reference, server] = unsafe { ptr::read(self.con as *const [HANDLE; 3]) };+ let duplicate = |handle: HANDLE| {+ unsafe { BorrowedHandle::borrow_raw(handle as _) }.try_clone_to_owned()+ };+ let signal = duplicate(signal)?;+ let reference = duplicate(reference)?;+ let server = duplicate(server)?;+ ensure!(+ unsafe { GetFileType(signal.as_raw_handle() as _) } == FILE_TYPE_PIPE,+ "the pseudo console's signal handle is not a pipe"+ );+ let host = super::process_image_name(&server)?;+ ensure!(+ ["openconsole.exe", "conhost.exe"]+ .iter()+ .any(|name| host.eq_ignore_ascii_case(name)),+ "the pseudo console's host process is {host}, not a console host"+ );+ Ok([signal, reference, server])+ }++ /// The pseudo console a predecessor handed over (see `handoff_handles`).+ /// The handles become the console's own.+ pub fn from_handoff(handles: [StdOwnedHandle; 3]) -> Result<Self, Error> {+ let pack = CONPTY+ .pack+ .ok_or_else(|| anyhow::anyhow!("this conpty.dll cannot adopt a handed-over console"))?;+ let [signal, reference, server] = handles;+ let mut con: HPCON = INVALID_HANDLE_VALUE;+ let result = unsafe {+ pack(+ server.as_raw_handle() as _,+ reference.as_raw_handle() as _,+ signal.as_raw_handle() as _,+ &mut con,+ )+ };+ ensure!(+ result == S_OK,+ "failed to adopt a pseudo console: HRESULT {}",+ result+ );+ // Closed by ClosePseudoConsole from now on.+ let _ = (+ signal.into_raw_handle(),+ reference.into_raw_handle(),+ server.into_raw_handle(),+ );+ Ok(Self { con })+ }+pub fn new(size: COORD, input: FileDescriptor, output: FileDescriptor) -> Result<Self, Error> {let mut con: HPCON = INVALID_HANDLE_VALUE;let result = unsafe {- (CONPTY.CreatePseudoConsole)(+ (CONPTY.funcs.CreatePseudoConsole)(size,input.as_raw_handle() as _,output.as_raw_handle() as _,@@ -99,7 +205,7 @@ impl PsuedoCon {}pub fn resize(&self, size: COORD) -> Result<(), Error> {- let result = unsafe { (CONPTY.ResizePseudoConsole)(self.con, size) };+ let result = unsafe { (CONPTY.funcs.ResizePseudoConsole)(self.con, size) };ensure!(result == S_OK,"failed to resize console to {}x{}: HRESULT: {}",