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
mux-server: a daemonized takeover tells the shell that ran it how it went
RoversX5eec1774f918
diff --git a/wezterm-mux-server-impl/src/handoff.rs b/wezterm-mux-server-impl/src/handoff.rsindex cea91ac9..40132933 100644--- a/wezterm-mux-server-impl/src/handoff.rs+++ b/wezterm-mux-server-impl/src/handoff.rs@@ -230,12 +230,34 @@ fn decode_snapshot(bytes: &[u8]) -> anyhow::Result<TerminalSnapshot> {// ------------------------------------------------------- the old serverstatic PID_FILE_FD: AtomicI32 = AtomicI32::new(-1);+static REPORT_FD: AtomicI32 = AtomicI32::new(-1);/// The pid file this daemon holds locked, to pass on with everything else.pub fn remember_pid_file_fd(fd: RawFd) {PID_FILE_FD.store(fd, Ordering::SeqCst);}+/// The pipe back to the shell that ran `--daemonize --takeover`.+pub fn remember_report_fd(fd: RawFd) {+ REPORT_FD.store(fd, Ordering::SeqCst);+}++/// Tell the shell that ran `--daemonize --takeover` how it went, once;+/// nothing happens when it was not asked. The line is `ok` or+/// `error: <why>`, and the pipe closes with it.+pub fn report_takeover(outcome: Result<(), &str>) {+ let fd = REPORT_FD.swap(-1, Ordering::SeqCst);+ if fd < 0 {+ return;+ }+ let mut pipe = unsafe { std::fs::File::from_raw_fd(fd) };+ let line = match outcome {+ Ok(()) => "ok\n".to_string(),+ Err(why) => format!("error: {}\n", why.replace('\n', " ")),+ };+ pipe.write_all(line.as_bytes()).ok();+}+/// Listen for a successor at `<socket_path>.handoff`. One takeover at a/// time; a failed one leaves this server as it was.pub fn spawn_handoff_listener(socket_path: PathBuf) -> anyhow::Result<()> {diff --git a/wezterm-mux-server/src/daemonize.rs b/wezterm-mux-server/src/daemonize.rsindex 3ea57f23..f38021c8 100644--- a/wezterm-mux-server/src/daemonize.rs+++ b/wezterm-mux-server/src/daemonize.rs@@ -2,7 +2,7 @@use anyhow::Context;use libc::pid_t;use std::io::Write;-use std::os::unix::io::{AsRawFd, IntoRawFd, RawFd};+use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};enum Fork {#[allow(dead_code)]@@ -64,13 +64,35 @@ fn lock_pid_file(config: &config::ConfigHandle) -> anyhow::Result<std::fs::File>Ok(file)}-/// `lock_pid_file` is false for a server that is taking over from a-/// running one: that one holds the lock, and hands the locked file over-/// with everything else.+/// What the daemon inherits from the process that launched it.+pub struct Daemonized {+ /// The locked pid file, to keep open for the life of the daemon.+ pub pid_file_fd: Option<RawFd>,+ /// The write end of the report pipe: the daemon writes one line to+ /// say how the takeover went, and the launching process relays it.+ pub report_fd: Option<RawFd>,+}++/// `lock_pid` is false for a server that is taking over from a running+/// one: that one holds the lock, and hands the locked file over with+/// everything else. With `report`, the process that ran the command does+/// not exit until the daemon has said how the takeover went, and exits+/// the way it went: forking twice would otherwise report success before+/// anything had happened.pub fn daemonize(config: &config::ConfigHandle,lock_pid: bool,-) -> anyhow::Result<Option<RawFd>> {+ report: bool,+) -> anyhow::Result<Daemonized> {+ let report_pipe = if report {+ let mut fds = [0 as RawFd; 2];+ if unsafe { libc::pipe(fds.as_mut_ptr()) } != 0 {+ return Err(std::io::Error::last_os_error()).context("pipe for the takeover report");+ }+ Some((fds[0], fds[1]))+ } else {+ None+ };let pid_file = if lock_pid && !config::running_under_wsl() {// pid file locking is only partly functional when running under// WSL 1; it is possible for the pid file to exist after a reboot@@ -90,6 +112,10 @@ pub fn daemonize(Fork::Parent(pid) => {let mut status = 0;unsafe { libc::waitpid(pid, &mut status, 0) };+ if let Some((read_fd, write_fd)) = report_pipe {+ unsafe { libc::close(write_fd) };+ std::process::exit(relay_takeover_report(read_fd));+ }std::process::exit(0);}Fork::Child(_) => {}@@ -121,7 +147,36 @@ pub fn daemonize(unsafe { libc::dup2(stdout.as_raw_fd(), libc::STDOUT_FILENO) };unsafe { libc::dup2(stderr.as_raw_fd(), libc::STDERR_FILENO) };- Ok(pid_file_fd)+ let report_fd = report_pipe.map(|(read_fd, write_fd)| {+ unsafe { libc::close(read_fd) };+ set_cloexec(write_fd, false);+ write_fd+ });++ Ok(Daemonized {+ pid_file_fd,+ report_fd,+ })+}++/// Wait for the daemon's one-line report and turn it into an exit status:+/// `ok` is 0 and silent, `error: <why>` prints why and is 1, nothing at+/// all (the daemon died first) is 1 too.+fn relay_takeover_report(read_fd: RawFd) -> i32 {+ use std::io::Read;+ let mut report = String::new();+ let mut pipe = unsafe { std::fs::File::from_raw_fd(read_fd) };+ pipe.read_to_string(&mut report).ok();+ let line = report.lines().next().unwrap_or("").trim();+ if line == "ok" {+ return 0;+ }+ if let Some(why) = line.strip_prefix("error: ") {+ eprintln!("takeover failed: {why}");+ } else {+ eprintln!("the takeover did not report an outcome; see the server log");+ }+ 1}pub fn set_cloexec(fd: RawFd, enable: bool) {diff --git a/wezterm-mux-server/src/main.rs b/wezterm-mux-server/src/main.rsindex 10937d51..3b6d4e91 100644--- a/wezterm-mux-server/src/main.rs+++ b/wezterm-mux-server/src/main.rs@@ -64,6 +64,12 @@ struct Opt {#[arg(long, hide = true)]pid_file_fd: Option<i32>,+ /// The pipe a daemonized takeover reports its outcome on; see+ /// daemonize::Daemonized.+ #[cfg(unix)]+ #[arg(long, hide = true)]+ takeover_report_fd: Option<i32>,+/// Instead of executing your shell, run PROG./// For example: `thinkterm start -- bash -l` will spawn bash/// as if it were a login shell.@@ -75,6 +81,8 @@ fn main() {if let Err(err) = run() {wezterm_blob_leases::clear_storage();log::error!("{:#}", err);+ #[cfg(unix)]+ wezterm_mux_server_impl::handoff::report_takeover(Err(&format!("{err:#}")));std::process::exit(1);}wezterm_blob_leases::clear_storage();@@ -96,6 +104,10 @@ fn run() -> anyhow::Result<()> {if let Some(fd) = opts.pid_file_fd {daemonize::set_cloexec(fd, true);}+ if let Some(fd) = opts.takeover_report_fd {+ daemonize::set_cloexec(fd, true);+ wezterm_mux_server_impl::handoff::remember_report_fd(fd);+ }}config::common_init(@@ -113,11 +125,15 @@ fn run() -> anyhow::Result<()> {#[cfg(unix)]let mut pid_file = None;+ #[cfg(unix)]+ let mut report_fd = None;#[cfg(unix)]{if opts.daemonize {- pid_file = daemonize::daemonize(&config, !opts.takeover)?;+ let daemonized = daemonize::daemonize(&config, !opts.takeover, opts.takeover)?;+ pid_file = daemonized.pid_file_fd;+ report_fd = daemonized.report_fd;// When we reach this line, we are in a forked child process,// and the fork will have broken the async-io/reactor state// of the smol runtime.@@ -142,6 +158,10 @@ fn run() -> anyhow::Result<()> {cmd.arg("--pid-file-fd");cmd.arg(&fd.to_string());}+ if let Some(fd) = report_fd {+ cmd.arg("--takeover-report-fd");+ cmd.arg(&fd.to_string());+ }}if opts.skip_config {cmd.arg("-n");@@ -373,9 +393,11 @@ async fn async_run(// Nothing of ours is registered and the layout files are// the running server's: leave without the exit flush.log::error!("taking over from the running server failed: {err:#}");+ wezterm_mux_server_impl::handoff::report_takeover(Err(&format!("{err:#}")));std::process::exit(2);}};+ wezterm_mux_server_impl::handoff::report_takeover(Ok(()));if let Some(fd) = pid_file_fd {adopt_pid_file(fd);}