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(mux): pause pane readers and take handoff parts on Windows
RoversXd353c592134e
diff --git a/mux/Cargo.toml b/mux/Cargo.tomlindex b3937cd4..7f56c5d6 100644--- a/mux/Cargo.toml+++ b/mux/Cargo.toml@@ -58,6 +58,7 @@ wezterm-uds.workspace = truewinapi = { workspace=true, features = ["errhandlingapi","handleapi",+ "ioapiset","memoryapi","psapi","processthreadsapi",diff --git a/mux/src/lib.rs b/mux/src/lib.rsindex a1ba2687..65e372db 100644--- a/mux/src/lib.rs+++ b/mux/src/lib.rs@@ -954,7 +954,19 @@ fn allocate_socketpair() -> anyhow::Result<(FileDescriptor, FileDescriptor)> {/// has been applied to the terminal.pub struct ReaderControl {/// A byte written here breaks the reader out of its poll.+ #[cfg(unix)]wake: parking_lot::Mutex<FileDescriptor>,+ /// The reader thread. A pipe cannot be polled on Windows, so a pause+ /// cancels the blocking read the thread is in instead; a cancelled read+ /// takes nothing from the pipe.+ #[cfg(windows)]+ thread: std::os::windows::io::OwnedHandle,+ /// Whether the reader is inside its read, the only call a cancel may+ /// hit. A lock, not a flag: the reader cannot leave the read for its+ /// write to the parser while a cancel is being issued, so the cancel+ /// never lands on that write.+ #[cfg(windows)]+ in_read: parking_lot::Mutex<bool>,paused: AtomicBool,/// Whether the reader is parked; `changed` is signalled by both sides.parked: std::sync::Mutex<bool>,@@ -969,6 +981,7 @@ pub struct ReaderControl {}impl ReaderControl {+ #[cfg(unix)]fn new(wake: FileDescriptor) -> Self {Self {wake: parking_lot::Mutex::new(wake),@@ -980,6 +993,28 @@ impl ReaderControl {}}+ /// For the calling thread, which is the reader.+ #[cfg(windows)]+ fn for_this_thread() -> anyhow::Result<Self> {+ // A real handle: GetCurrentThread's means "the calling thread".+ let thread = unsafe {+ std::os::windows::io::BorrowedHandle::borrow_raw(+ winapi::um::processthreadsapi::GetCurrentThread() as _,+ )+ }+ .try_clone_to_owned()+ .context("a handle on the reader thread")?;+ Ok(Self {+ thread,+ in_read: parking_lot::Mutex::new(false),+ paused: AtomicBool::new(false),+ parked: std::sync::Mutex::new(false),+ changed: std::sync::Condvar::new(),+ pending_bytes: AtomicUsize::new(0),+ holding: AtomicBool::new(false),+ })+ }+/// Park the reader and wait until what it read has been applied./// Times out on a reader that never parks, or on a parser that never/// finishes: an output batch held for synchronized output, or a pane@@ -987,10 +1022,17 @@ impl ReaderControl {fn pause(&self, timeout: Duration) -> anyhow::Result<()> {let deadline = Instant::now() + timeout;self.paused.store(true, Ordering::SeqCst);+ #[cfg(unix)]if let Err(err) = self.wake.lock().write_all(&[1]) {self.resume();return Err(err).context("waking the pane reader");}+ // A cancel finds nothing when the reader is between checking the+ // flag and entering its read, so it is repeated until the park.+ #[cfg(windows)]+ let interval = Duration::from_millis(10);+ #[cfg(not(windows))]+ let interval = timeout;{let mut parked = self.parked.lock().unwrap();while !*parked {@@ -1000,7 +1042,19 @@ impl ReaderControl {self.resume();anyhow::bail!("the pane reader did not park within {timeout:?}");}- parked = self.changed.wait_timeout(parked, left).unwrap().0;+ #[cfg(windows)]+ {+ let in_read = self.in_read.lock();+ if *in_read {+ use std::os::windows::io::AsRawHandle;+ unsafe {+ winapi::um::ioapiset::CancelSynchronousIo(+ self.thread.as_raw_handle() as _,+ )+ };+ }+ }+ parked = self.changed.wait_timeout(parked, left.min(interval)).unwrap().0;}}loop {@@ -1073,7 +1127,8 @@ impl Drop for PausedReader {/// applied to the terminal, so that the terminal is exactly what the pty/// produced up to the park. Output the program writes meanwhile waits in/// the kernel's pty buffer for whoever reads next. Panes without a pty-/// (or on a platform without poll) cannot be paused.+/// cannot be paused on unix; on Windows every reader can, as a pause+/// cancels the read it blocks in.pub fn pause_pane_reader(pane_id: PaneId, timeout: Duration) -> anyhow::Result<PausedReader> {let control = PANE_READERS.lock()@@ -1124,6 +1179,7 @@ fn read_from_pane_pty(// The wake pipe and the control exist only when the pty can be polled;// without them the loop below is the plain blocking read.+ #[cfg(unix)]let pausable = pty_fd.and_then(|fd| match filedescriptor::Pipe::new() {Ok(pipe) => Some((fd, pipe)),Err(err) => {@@ -1131,6 +1187,7 @@ fn read_from_pane_pty(None}});+ #[cfg(unix)]let (control, mut wake_read, poll_fd) = match pausable {Some((fd, pipe)) => {let control = Arc::new(ReaderControl::new(pipe.write));@@ -1139,6 +1196,22 @@ fn read_from_pane_pty(}None => (None, None, None),};+ // Every reader can be paused here: a cancel ends the read it blocks in.+ #[cfg(windows)]+ let control = {+ let _ = pty_fd;+ match ReaderControl::for_this_thread() {+ Ok(control) => {+ let control = Arc::new(control);+ PANE_READERS.lock().insert(pane_id, Arc::clone(&control));+ Some(control)+ }+ Err(err) => {+ log::warn!("pane {pane_id}: the reader cannot be paused: {err:#}");+ None+ }+ }+ };let heartbeat = parse_watchdog::register(pane_id);let exit_watch = pane.clone();@@ -1153,6 +1226,14 @@ fn read_from_pane_pty(}while !dead.load(Ordering::Relaxed) {+ #[cfg(windows)]+ if let Some(control) = &control {+ if control.paused.load(Ordering::SeqCst) {+ control.park();+ continue;+ }+ }+ #[cfg(unix)]if let (Some(control), Some(wake_read), Some(fd)) = (&control, &mut wake_read, poll_fd) {let mut pfd = [pollfd {@@ -1197,7 +1278,22 @@ fn read_from_pane_pty(continue;}}- match reader.read(&mut buf) {+ #[cfg(windows)]+ if let Some(control) = &control {+ *control.in_read.lock() = true;+ }+ let read = reader.read(&mut buf);+ #[cfg(windows)]+ if let Some(control) = &control {+ *control.in_read.lock() = false;+ // A pause cancelled the read; nothing was taken from the pipe.+ if matches!(&read, Err(err) if err.raw_os_error()+ == Some(winapi::shared::winerror::ERROR_OPERATION_ABORTED as i32))+ {+ continue;+ }+ }+ match read {Ok(size) if size == 0 => {log::trace!("read_pty EOF: pane_id {}", pane_id);break;diff --git a/mux/src/localpane.rs b/mux/src/localpane.rsindex ac5d22db..984d23fa 100644--- a/mux/src/localpane.rs+++ b/mux/src/localpane.rs@@ -1544,6 +1544,35 @@ pub struct PaneHandoffParts {pub description: String,}+/// What a pane hands to a successor server besides its terminal, on+/// Windows: see `LocalPane::handoff_parts`.+#[cfg(windows)]+pub struct PaneHandoffParts {+ pub pid: u32,+ /// Waitable, killable, and enough to read the exit code.+ pub process: std::os::windows::io::OwnedHandle,+ pub conpty: portable_pty::win::conpty::ConPtyHandoff,+ pub description: String,+}++#[cfg(windows)]+fn open_child_process(pid: u32) -> std::io::Result<std::os::windows::io::OwnedHandle> {+ use std::os::windows::io::FromRawHandle;+ use winapi::um::processthreadsapi::OpenProcess;+ use winapi::um::winnt::{PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_TERMINATE, SYNCHRONIZE};+ let handle = unsafe {+ OpenProcess(+ PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_TERMINATE | SYNCHRONIZE,+ 0,+ pid,+ )+ };+ if handle.is_null() {+ return Err(std::io::Error::last_os_error());+ }+ Ok(unsafe { std::os::windows::io::OwnedHandle::from_raw_handle(handle as _) })+}+impl LocalPane {/// The pieces a successor server needs to adopt this pane, or None/// for a pane that cannot travel: one over a channel rather than a@@ -1575,6 +1604,34 @@ impl LocalPane {})}+ /// The Windows sibling of the above: the pseudo console's handles in+ /// place of the pty descriptor, and the process itself, which a+ /// successor can wait on only with a handle. Err for a pane that should+ /// travel and whose parts could not be taken; the caller decides.+ #[cfg(windows)]+ pub fn handoff_parts(&self) -> Option<anyhow::Result<PaneHandoffParts>> {+ if self.tmux_domain.lock().is_some() {+ return None;+ }+ let pid = match &*self.process.lock() {+ ProcessState::Running { pid: Some(pid), .. } => *pid,+ _ => return None,+ };+ Some((|| {+ // Its waiter holds a handle until it exits, so the pid names+ // this process and no other.+ let process = open_child_process(pid)+ .map_err(|err| anyhow::anyhow!("opening process {pid}: {err}"))?;+ let conpty = self.pty.lock().conpty_handoff()?;+ Ok(PaneHandoffParts {+ pid,+ process,+ conpty,+ description: self.command_description.clone(),+ })+ })())+ }+/// Forget the process without touching it: this pane was staged for/// a takeover that did not happen, and the process still belongs to/// the server that is keeping it. Dropping the pane afterwards sendsdiff --git a/mux/src/session_server.rs b/mux/src/session_server.rsindex 5c25b436..5ba38d70 100644--- a/mux/src/session_server.rs+++ b/mux/src/session_server.rs@@ -205,10 +205,14 @@ pub fn stop(_pid_file: &Path, _socket: &Path, _wait: Duration) -> anyhow::Result#[cfg(windows)]pub use windows::{create_stop_event, StopEvent};+/// Whether `pid` is a live mux server, by its program's name: the one test+/// for "this process is the server", shared with the handoff.+#[cfg(windows)]+pub use windows::is_mux_server_process;+#[cfg(windows)]mod windows {use anyhow::Context as _;- use std::os::windows::ffi::OsStringExt as _;use std::os::windows::fs::OpenOptionsExt as _;use std::path::Path;use std::time::{Duration, Instant};@@ -216,7 +220,7 @@ mod windows {use winapi::um::handleapi::{CloseHandle, INVALID_HANDLE_VALUE};use winapi::um::processthreadsapi::OpenProcess;use winapi::um::synchapi::{CreateEventW, OpenEventW, SetEvent, WaitForSingleObject};- use winapi::um::winbase::{QueryFullProcessImageNameW, INFINITE};+ use winapi::um::winbase::INFINITE;use winapi::um::winnt::{EVENT_MODIFY_STATE, FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, HANDLE,PROCESS_QUERY_LIMITED_INFORMATION,@@ -244,22 +248,19 @@ mod windows {}/// Whether `pid` is a live process whose image is the mux server.- pub(super) fn is_mux_server_process(pid: u32) -> bool {+ pub fn is_mux_server_process(pid: u32) -> bool {+ use std::os::windows::io::FromRawHandle as _;let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };if handle.is_null() {return false;}- let mut buf = vec![0u16; 32 * 1024];- let mut len = buf.len() as u32;- let ok = unsafe { QueryFullProcessImageNameW(handle, 0, buf.as_mut_ptr(), &mut len) };- unsafe { CloseHandle(handle) };- if ok == 0 {- return false;- }- let path = std::path::PathBuf::from(std::ffi::OsString::from_wide(&buf[..len as usize]));- path.file_stem()- .and_then(|stem| stem.to_str())- .is_some_and(|stem| stem.eq_ignore_ascii_case(SERVER_IMAGE_STEM))+ let process = unsafe { std::os::windows::io::OwnedHandle::from_raw_handle(handle as _) };+ portable_pty::win::process_image_name(&process).is_ok_and(|name| {+ Path::new(&name)+ .file_stem()+ .and_then(|stem| stem.to_str())+ .is_some_and(|stem| stem.eq_ignore_ascii_case(SERVER_IMAGE_STEM))+ })}fn holder_pid(pid_file: &Path) -> Option<u32> {