Skip to content

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.

handoff: close the failure paths the review found, and the client leaks

RoversXfb9fa6476e9a
diff --git a/mux/src/lib.rs b/mux/src/lib.rs
index 73eb4438..e839cbba 100644
--- a/mux/src/lib.rs
+++ b/mux/src/lib.rs
@@ -736,6 +736,11 @@ fn parse_buffered_data(
}
unapplied = 0;
}
+ if let Some(control) = &control {
+ control
+ .holding
+ .store(hold && !actions.is_empty(), Ordering::SeqCst);
+ }
}
}
}
@@ -796,6 +801,11 @@ pub struct ReaderControl {
changed: std::sync::Condvar,
/// Bytes read from the pty and not yet applied to the terminal.
pending_bytes: AtomicUsize,
+ /// The parser holds a synchronized-output frame that is not finished:
+ /// what it holds cannot be applied until the program ends the frame,
+ /// which a parked reader would never deliver. A pause accepts that
+ /// state as quiescent; the held frame is lost, the next one redraws.
+ holding: AtomicBool,
}
impl ReaderControl {
@@ -806,6 +816,7 @@ impl ReaderControl {
parked: std::sync::Mutex::new(false),
changed: std::sync::Condvar::new(),
pending_bytes: AtomicUsize::new(0),
+ holding: AtomicBool::new(false),
}
}
@@ -834,7 +845,7 @@ impl ReaderControl {
}
loop {
let pending = self.pending_bytes.load(Ordering::SeqCst);
- if pending == 0 {
+ if pending == 0 || self.holding.load(Ordering::SeqCst) {
return Ok(());
}
if Instant::now() >= deadline {
diff --git a/mux/src/localpane.rs b/mux/src/localpane.rs
index 4a959ff7..c9e8af90 100644
--- a/mux/src/localpane.rs
+++ b/mux/src/localpane.rs
@@ -1360,8 +1360,10 @@ fn split_child(
pub struct PaneHandoffParts {
pub pid: u32,
pub tty_name: Option<std::path::PathBuf>,
- /// The master pty, still owned here; the successor gets a duplicate.
- pub pty_fd: std::os::unix::io::RawFd,
+ /// A duplicate of the master pty, taken under the pty lock: the pane
+ /// may close its own between now and the send, and a bare number
+ /// would then name whatever the kernel handed out next.
+ pub pty_fd: std::os::fd::OwnedFd,
pub description: String,
}
@@ -1379,7 +1381,15 @@ impl LocalPane {
_ => return None,
};
let pty = self.pty.lock();
- let pty_fd = pty.as_raw_fd()?;
+ let raw = pty.as_raw_fd()?;
+ let dup = unsafe { libc::dup(raw) };
+ if dup < 0 {
+ return None;
+ }
+ let pty_fd = unsafe {
+ use std::os::fd::FromRawFd;
+ std::os::fd::OwnedFd::from_raw_fd(dup)
+ };
Some(PaneHandoffParts {
pid,
tty_name: pty.tty_name(),
@@ -1399,7 +1409,12 @@ impl LocalPane {
/// Everything the terminal remembers. Take it with the reader paused
/// (`crate::pause_pane_reader`), or it is a moment behind the pty.
pub fn snapshot_terminal(&self) -> wezterm_term::TerminalSnapshot {
- self.terminal.lock().snapshot()
+ let mut term = self.terminal.lock();
+ // A resize, configuration or focus noted while the parser held
+ // the terminal is the parser's to apply; with the reader parked it
+ // never will, so apply it here or the snapshot lags the pty.
+ self.apply_pending_and_store(&mut term);
+ term.snapshot()
}
pub fn new(
diff --git a/pty/src/lib.rs b/pty/src/lib.rs
index fcb11ca0..27ac4168 100644
--- a/pty/src/lib.rs
+++ b/pty/src/lib.rs
@@ -298,17 +298,28 @@ impl Child for std::process::Child {
/// the process -- init, or a subreaper -- has to reap it.)
#[cfg(unix)]
pub fn adopted_child(pid: u32) -> Box<dyn Child + Send + Sync> {
- Box::new(AdoptedChild { pid })
+ Box::new(AdoptedChild::new(pid))
}
#[cfg(unix)]
#[derive(Debug)]
struct AdoptedChild {
pid: u32,
+ /// On Linux, a descriptor that names this process and not its pid:
+ /// readable once it exits, immune to pid reuse. None elsewhere, or on
+ /// a kernel without pidfd_open, where the pid is polled instead.
+ pidfd: Option<std::os::fd::OwnedFd>,
}
#[cfg(unix)]
impl AdoptedChild {
+ fn new(pid: u32) -> Self {
+ Self {
+ pid,
+ pidfd: pidfd_open(pid),
+ }
+ }
+
fn alive(&self) -> bool {
if unsafe { libc::kill(self.pid as libc::pid_t, 0) } == 0 {
return true;
@@ -316,21 +327,66 @@ impl AdoptedChild {
// EPERM: it exists and is not ours to signal. ESRCH: gone.
std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
}
+
+ /// Whether the process has exited, waiting up to `timeout_ms` (-1:
+ /// forever) when a pidfd can say so; otherwise a look at the pid.
+ fn exited(&self, timeout_ms: i32) -> bool {
+ use std::os::fd::AsRawFd;
+ let Some(pidfd) = &self.pidfd else {
+ return !self.alive();
+ };
+ let mut pfd = libc::pollfd {
+ fd: pidfd.as_raw_fd(),
+ events: libc::POLLIN,
+ revents: 0,
+ };
+ loop {
+ let ready = unsafe { libc::poll(&mut pfd, 1, timeout_ms) };
+ if ready > 0 {
+ return true;
+ }
+ if ready == 0 {
+ return false;
+ }
+ if std::io::Error::last_os_error().kind() != std::io::ErrorKind::Interrupted {
+ return !self.alive();
+ }
+ }
+ }
+}
+
+#[cfg(target_os = "linux")]
+fn pidfd_open(pid: u32) -> Option<std::os::fd::OwnedFd> {
+ use std::os::fd::FromRawFd;
+ let fd = unsafe { libc::syscall(libc::SYS_pidfd_open, pid as libc::pid_t, 0 as libc::c_uint) };
+ if fd < 0 {
+ return None;
+ }
+ Some(unsafe { std::os::fd::OwnedFd::from_raw_fd(fd as i32) })
+}
+
+#[cfg(all(unix, not(target_os = "linux")))]
+fn pidfd_open(_pid: u32) -> Option<std::os::fd::OwnedFd> {
+ None
}
#[cfg(unix)]
impl Child for AdoptedChild {
fn try_wait(&mut self) -> IoResult<Option<ExitStatus>> {
- Ok(if self.alive() {
- None
- } else {
+ Ok(if self.exited(0) {
Some(ExitStatus::with_exit_code(0))
+ } else {
+ None
})
}
fn wait(&mut self) -> IoResult<ExitStatus> {
- while self.alive() {
- std::thread::sleep(std::time::Duration::from_millis(250));
+ if self.pidfd.is_some() {
+ while !self.exited(-1) {}
+ } else {
+ while !self.exited(0) {
+ std::thread::sleep(std::time::Duration::from_millis(250));
+ }
}
Ok(ExitStatus::with_exit_code(0))
}
diff --git a/wezterm-client/src/domain.rs b/wezterm-client/src/domain.rs
index a6208fa2..122381a7 100644
--- a/wezterm-client/src/domain.rs
+++ b/wezterm-client/src/domain.rs
@@ -425,6 +425,10 @@ pub struct ThinkTermFrontendRecoveryTarget {
pub tab_id: TabId,
}
+/// How long a recovery barrier may wait for the frontend before it is
+/// released unacknowledged.
+const FRONTEND_RECOVERY_DEADLINE: Duration = Duration::from_secs(20);
+
#[derive(Debug)]
struct FrontendRecoveryBarrier {
generation: u64,
@@ -1551,6 +1555,7 @@ impl ClientInner {
}
fn structure_mutation_in_flight(&self) -> bool {
+ self.release_stale_frontend_recovery_barrier();
self.mutations_in_flight
.load(std::sync::atomic::Ordering::SeqCst)
> 0
@@ -1568,10 +1573,46 @@ impl ClientInner {
structure: Option<StructureMutationGuard>,
) {
let pending = targets.into_iter().collect::<HashMap<_, _>>();
+ if generation != self.client.connection_generation() {
+ // A newer attempt already owns the slot; a barrier for this
+ // one would never be acknowledged and would hold resyncs back
+ // for good.
+ log::info!(
+ "not arming the frontend recovery barrier for mux generation {generation}: \
+ the connection is at generation {}",
+ self.client.connection_generation()
+ );
+ return;
+ }
*self.frontend_recovery_barrier.lock().unwrap() =
Some(FrontendRecoveryBarrier::new(generation, pending, structure));
}
+ /// Drop a recovery barrier the frontend is never going to acknowledge:
+ /// one from a superseded generation, or one older than
+ /// `FRONTEND_RECOVERY_DEADLINE` (a tab the user switched away from never
+ /// publishes its geometry). Its hold on push-driven resyncs goes with it.
+ fn release_stale_frontend_recovery_barrier(&self) {
+ let stale = {
+ let mut barrier = self.frontend_recovery_barrier.lock().unwrap();
+ let Some(armed) = barrier.as_ref() else {
+ return;
+ };
+ let superseded = armed.generation != self.client.connection_generation();
+ let overdue = armed.started_at.elapsed() > FRONTEND_RECOVERY_DEADLINE;
+ if !superseded && !overdue {
+ return;
+ }
+ barrier.take().map(|b| (b.generation, superseded, b.started_at.elapsed()))
+ };
+ if let Some((generation, superseded, waited)) = stale {
+ log::warn!(
+ "releasing the frontend recovery barrier for mux generation {generation} after {waited:?}: {}",
+ if superseded { "superseded" } else { "never acknowledged" }
+ );
+ }
+ }
+
fn ready_server_id(&self) -> Option<String> {
self.ready_server_id.lock().unwrap().clone()
}
@@ -2467,7 +2508,16 @@ impl ClientDomain {
// the frontend's selected Thread and current size.
replacement = Some(inner.prepare_server_replacement());
}
- Self::process_pane_list(Arc::clone(&inner), panes, None, true, replacement.as_mut())?;
+ if let Err(err) =
+ Self::process_pane_list(Arc::clone(&inner), panes, None, true, replacement.as_mut())
+ {
+ // Windows this attempt made before failing would otherwise
+ // outlive it, as the ones a push-driven resync made used to.
+ if let Some(replacement) = replacement.as_ref() {
+ discard_replacement_windows(&inner, &replacement.created_windows);
+ }
+ return Err(err);
+ }
let created_windows = replacement
.as_ref()
diff --git a/wezterm-client/src/pane/clientpane.rs b/wezterm-client/src/pane/clientpane.rs
index 40767ddc..e9438b55 100644
--- a/wezterm-client/src/pane/clientpane.rs
+++ b/wezterm-client/src/pane/clientpane.rs
@@ -1293,22 +1293,11 @@ impl Pane for ClientPane {
if self.client.remote_tab_input_is_blocked() {
return;
}
- let client = Arc::clone(&self.client);
- let remote_pane_id = self.remote_pane_id;
- let remote_tab_id = self.remote_tab_id();
- promise::spawn::spawn(async move {
- if client.prepare_remote_tab_input(remote_tab_id).await? {
- client
- .client
- .erase_scrollback(EraseScrollbackRequest {
- pane_id: remote_pane_id,
- erase_mode,
- })
- .await?;
- }
- Ok::<(), anyhow::Error>(())
- })
- .detach();
+ // In the queue with the keys: the server applies it in arrival
+ // order, so the client sends it in the order it was asked.
+ if let Err(err) = self.queue_input(PaneInput::EraseScrollback(erase_mode)) {
+ log::warn!("erase scrollback of remote pane {}: {err:#}", self.remote_pane_id);
+ }
}
fn advise_focus(&self) {
@@ -1516,6 +1505,7 @@ enum PaneInput {
},
Paste(String),
Mouse(MouseEvent),
+ EraseScrollback(ScrollbackEraseMode),
}
/// What an input weighs against `INPUT_QUEUE_LIMIT` when it is all
@@ -1527,7 +1517,9 @@ impl PaneInput {
match self {
PaneInput::Bytes(data) => data.len().max(INPUT_ITEM_FLOOR),
PaneInput::Paste(text) => text.len().max(INPUT_ITEM_FLOOR),
- PaneInput::Key { .. } | PaneInput::Mouse(_) => INPUT_ITEM_FLOOR,
+ PaneInput::Key { .. } | PaneInput::Mouse(_) | PaneInput::EraseScrollback(_) => {
+ INPUT_ITEM_FLOOR
+ }
}
}
@@ -1537,6 +1529,7 @@ impl PaneInput {
PaneInput::Key { .. } => "a key".to_string(),
PaneInput::Paste(text) => format!("a paste of {} bytes", text.len()),
PaneInput::Mouse(_) => "a mouse report".to_string(),
+ PaneInput::EraseScrollback(_) => "a scrollback erase".to_string(),
}
}
@@ -1571,6 +1564,12 @@ impl PaneInput {
}),
PaneInput::Paste(data) => Pdu::SendPaste(SendPaste { pane_id, data }),
PaneInput::Mouse(event) => Pdu::SendMouseEvent(SendMouseEvent { pane_id, event }),
+ PaneInput::EraseScrollback(erase_mode) => {
+ Pdu::EraseScrollbackRequest(EraseScrollbackRequest {
+ pane_id,
+ erase_mode,
+ })
+ }
}
}
}
@@ -2281,6 +2280,7 @@ mod input_queue_tests {
PaneInput::Bytes(data) => format!("bytes:{}", String::from_utf8_lossy(data)),
PaneInput::Key { .. } => "key".to_string(),
PaneInput::Paste(text) => format!("paste:{text}"),
+ PaneInput::EraseScrollback(_) => "erase".to_string(),
PaneInput::Mouse(event) => match (&event.kind, &event.button) {
(MouseEventKind::Move, _) => format!("mouse:move@{}", event.x),
(_, MouseButton::WheelDown(n)) => format!("mouse:wheeldown{n}"),
diff --git a/wezterm-mux-server-impl/src/handoff.rs b/wezterm-mux-server-impl/src/handoff.rs
index 40132933..c3a9b69f 100644
--- a/wezterm-mux-server-impl/src/handoff.rs
+++ b/wezterm-mux-server-impl/src/handoff.rs
@@ -54,6 +54,15 @@ pub const HANDOFF_VERSION: u32 = 1;
/// How long either side waits for the other's next message.
const STEP_TIMEOUT: Duration = Duration::from_secs(10);
+/// How long the old server waits for `Owned` after `Commit`: that one step
+/// is the successor restoring every terminal and registering everything,
+/// which grows with the panes and their scrollback. Past it the old server
+/// carries on -- with both reading the same ptys if the successor was
+/// merely slow, which is why it is generous.
+const OWNED_TIMEOUT: Duration = Duration::from_secs(120);
+/// How long the successor waits for `Hello`: the old server is pausing
+/// and snapshotting every pane first, up to `PAUSE_TIMEOUT` each.
+const HELLO_TIMEOUT: Duration = Duration::from_secs(60);
/// How long the old server waits for one pane's reader to park and its
/// parser to catch up.
const PAUSE_TIMEOUT: Duration = Duration::from_secs(2);
@@ -310,7 +319,7 @@ fn serve(mut stream: UnixStream, socket_path: &Path) {
/// Dropping it before the successor owns the panes resumes them.
struct Capture {
hello: Hello,
- panes: Vec<(HandoffPane, RawFd)>,
+ panes: Vec<(HandoffPane, OwnedFd)>,
topology: Vec<HandoffWindow>,
paused: Vec<PausedReader>,
}
@@ -322,6 +331,13 @@ fn serve_inner(stream: &mut UnixStream, socket_path: &Path) -> anyhow::Result<()
if version != HANDOFF_VERSION {
bail!("the successor speaks handoff version {version}, this server speaks {HANDOFF_VERSION}");
}
+ let unix_domains = config::configuration().unix_domains.len();
+ if unix_domains > 1 {
+ bail!(
+ "this server listens for {unix_domains} unix domains and a takeover carries one; \
+ stop and restart it instead"
+ );
+ }
let listener_fd = crate::local::listener_fd_for(socket_path)
.ok_or_else(|| anyhow!("no listening socket registered for {}", socket_path.display()))?;
let pid_file_fd = PID_FILE_FD.load(Ordering::SeqCst);
@@ -344,7 +360,8 @@ fn serve_inner(stream: &mut UnixStream, socket_path: &Path) -> anyhow::Result<()
let pane_id = pane.pane_id;
write_message(stream, &HandoffMessage::Pane(clone_pane(pane)))
.with_context(|| format!("sending pane {pane_id}"))?;
- send_fd(stream, *fd).with_context(|| format!("sending pane {pane_id}'s pty"))?;
+ send_fd(stream, fd.as_raw_fd())
+ .with_context(|| format!("sending pane {pane_id}'s pty"))?;
expect(stream, "Ack").with_context(|| format!("pane {pane_id}"))?;
}
@@ -356,6 +373,7 @@ fn serve_inner(stream: &mut UnixStream, socket_path: &Path) -> anyhow::Result<()
expect(stream, "Ack").context("listener")?;
write_message(stream, &HandoffMessage::Commit)?;
+ stream.set_read_timeout(Some(OWNED_TIMEOUT)).ok();
expect(stream, "Owned")?;
for paused in capture.paused {
@@ -569,7 +587,7 @@ pub fn begin(socket_path: &Path) -> anyhow::Result<Takeover> {
path.display()
)
})?;
- stream.set_read_timeout(Some(STEP_TIMEOUT))?;
+ stream.set_read_timeout(Some(HELLO_TIMEOUT))?;
stream.set_write_timeout(Some(STEP_TIMEOUT))?;
write_message(
&mut stream,
@@ -593,6 +611,7 @@ pub fn begin(socket_path: &Path) -> anyhow::Result<Takeover> {
} else {
None
};
+ stream.set_read_timeout(Some(STEP_TIMEOUT))?;
write_message(&mut stream, &HandoffMessage::Ack)?;
Ok(Takeover {
stream,
@@ -730,8 +749,12 @@ fn install(
for window in windows {
built.push(build_window(window, &by_id)?);
}
- register(staged.commit(), built)?;
+ // The guard stays armed through registration: a failure there must
+ // not drop what was adopted either.
+ register(&staged.panes, built)?;
+ staged.commit();
+ unsafe { libc::fcntl(listener.as_raw_fd(), libc::F_SETFD, libc::FD_CLOEXEC) };
let listener = unsafe { wezterm_uds::UnixListener::from_raw_fd(listener.into_raw_fd()) };
crate::local::remember_listener(socket_path.to_path_buf(), &listener);
let mut listener = crate::local::LocalListener::new(listener);
@@ -746,8 +769,9 @@ fn adopt_pane(item: Received, domain_id: DomainId) -> anyhow::Result<Arc<dyn Pan
let Received { pane, fd, snapshot } = item;
let master = portable_pty::unix::master_from_raw_fd(fd, pane.tty_name.map(PathBuf::from))?;
let writer = master.take_writer()?;
+ let snapshot_size = snapshot.size;
let mut terminal = wezterm_term::Terminal::new(
- snapshot.size,
+ snapshot_size,
Arc::new(config::TermConfig::new()),
"ThinkTerm",
config::wezterm_version(),
@@ -756,6 +780,23 @@ fn adopt_pane(item: Received, domain_id: DomainId) -> anyhow::Result<Arc<dyn Pan
terminal
.restore(snapshot)
.context("restoring the terminal from its snapshot")?;
+ // The old server kept serving between the snapshot and Commit; a
+ // resize in that window reached the pty but not the snapshot.
+ if let Ok(size) = master.get_size() {
+ let current = TerminalSize {
+ rows: size.rows as usize,
+ cols: size.cols as usize,
+ pixel_width: size.pixel_width as usize,
+ pixel_height: size.pixel_height as usize,
+ dpi: snapshot_size.dpi,
+ };
+ if current.rows > 0
+ && current.cols > 0
+ && (current.rows != snapshot_size.rows || current.cols != snapshot_size.cols)
+ {
+ terminal.resize(current);
+ }
+ }
let pane_writer = terminal.writer_handle();
let local = LocalPane::new(
pane.pane_id,
@@ -810,11 +851,11 @@ fn pane_ids_in(node: &PaneNode, out: &mut Vec<PaneId>) {
/// Make the staged panes, tabs and windows the mux's. This is the moment
/// the pane readers start, so it happens once, after everything arrived.
fn register(
- staged: Vec<Arc<dyn Pane>>,
+ staged: &[Arc<dyn Pane>],
windows: Vec<(Window, Vec<Arc<Tab>>, usize)>,
) -> anyhow::Result<()> {
let mux = Mux::get();
- for pane in &staged {
+ for pane in staged {
mux.add_pane(pane)
.with_context(|| format!("registering pane {}", pane.pane_id()))?;
}
@@ -838,8 +879,10 @@ pub fn wait_for_predecessor_exit(mut stream: UnixStream) {
let mut buf = [0u8; 64];
loop {
match stream.read(&mut buf) {
- Ok(0) | Err(_) => return,
+ Ok(0) => return,
Ok(_) => {}
+ Err(err) if err.kind() == std::io::ErrorKind::Interrupted => {}
+ Err(_) => return,
}
}
}
diff --git a/wezterm-mux-server-impl/src/local.rs b/wezterm-mux-server-impl/src/local.rs
index f769eaba..3cf3265c 100644
--- a/wezterm-mux-server-impl/src/local.rs
+++ b/wezterm-mux-server-impl/src/local.rs
@@ -4,27 +4,45 @@ use wezterm_uds::UnixListener;
#[cfg(unix)]
lazy_static::lazy_static! {
- /// The listening socket of each unix domain, by path, so a handoff can
- /// pass it on to the successor.
- static ref LISTENER_FDS: std::sync::Mutex<std::collections::HashMap<std::path::PathBuf, std::os::unix::io::RawFd>> =
+ /// A duplicate of the listening socket of each unix domain, by path,
+ /// so a handoff can pass it on to the successor. A duplicate, not the
+ /// number: should the accept loop end and close its own, the number
+ /// would come to name whatever was opened next.
+ static ref LISTENER_FDS: std::sync::Mutex<std::collections::HashMap<std::path::PathBuf, std::os::fd::OwnedFd>> =
std::sync::Mutex::new(std::collections::HashMap::new());
}
/// The descriptor of the listener bound at `socket_path`, if this server
-/// bound one.
+/// bound one; valid for as long as the registry holds it.
#[cfg(unix)]
pub fn listener_fd_for(socket_path: &std::path::Path) -> Option<std::os::unix::io::RawFd> {
- LISTENER_FDS.lock().unwrap().get(socket_path).copied()
+ use std::os::fd::AsRawFd;
+ LISTENER_FDS
+ .lock()
+ .unwrap()
+ .get(socket_path)
+ .map(|fd| fd.as_raw_fd())
}
/// Remember the listener at `socket_path`, for a later handoff.
#[cfg(unix)]
pub fn remember_listener(socket_path: std::path::PathBuf, listener: &UnixListener) {
+ use std::os::fd::{FromRawFd, OwnedFd};
use std::os::unix::io::AsRawFd;
+ let dup = unsafe { libc::dup(listener.as_raw_fd()) };
+ if dup < 0 {
+ log::error!(
+ "cannot duplicate the listener at {} for a later handoff: {}",
+ socket_path.display(),
+ std::io::Error::last_os_error()
+ );
+ return;
+ }
+ unsafe { libc::fcntl(dup, libc::F_SETFD, libc::FD_CLOEXEC) };
LISTENER_FDS
.lock()
.unwrap()
- .insert(socket_path, listener.as_raw_fd());
+ .insert(socket_path, unsafe { OwnedFd::from_raw_fd(dup) });
}
pub struct LocalListener {
diff --git a/wezterm-mux-server/src/daemonize.rs b/wezterm-mux-server/src/daemonize.rs
index f38021c8..52cc899f 100644
--- a/wezterm-mux-server/src/daemonize.rs
+++ b/wezterm-mux-server/src/daemonize.rs
@@ -36,7 +36,7 @@ fn setsid() -> anyhow::Result<()> {
}
}
-fn lock_pid_file(config: &config::ConfigHandle) -> anyhow::Result<std::fs::File> {
+pub fn lock_pid_file(config: &config::ConfigHandle) -> anyhow::Result<std::fs::File> {
let pid_file = config.daemon_options.pid_file();
let pid_file_dir = pid_file
.parent()
diff --git a/wezterm-mux-server/src/main.rs b/wezterm-mux-server/src/main.rs
index 3b6d4e91..4f7bdb93 100644
--- a/wezterm-mux-server/src/main.rs
+++ b/wezterm-mux-server/src/main.rs
@@ -325,8 +325,9 @@ fn run() -> anyhow::Result<()> {
let activity = Activity::new();
+ let daemonized = opts.daemonize;
promise::spawn::spawn(async move {
- if let Err(err) = async_run(cmd, takeover).await {
+ if let Err(err) = async_run(cmd, takeover, daemonized).await {
terminate_with_error(err);
}
drop(activity);
@@ -364,9 +365,11 @@ fn takeover_socket_path(config: &config::ConfigHandle) -> anyhow::Result<std::pa
async fn async_run(
cmd: Option<CommandBuilder>,
takeover: Option<TakeoverHandle>,
+ daemonized: bool,
) -> anyhow::Result<()> {
let mux = Mux::get();
let config = config::configuration();
+ let took_over = takeover.is_some();
// async_run is entered through SimpleExecutor, so promise's schedulers
// are available before agent detection starts its safety tick.
@@ -398,10 +401,26 @@ async fn async_run(
}
};
wezterm_mux_server_impl::handoff::report_takeover(Ok(()));
- if let Some(fd) = pid_file_fd {
- adopt_pid_file(fd);
+ match pid_file_fd {
+ Some(fd) => adopt_pid_file(fd),
+ // The predecessor ran in the foreground and had no pid file to
+ // hand over; a daemon takes one of its own, or the next
+ // `--daemonize` would bind the socket out from under it.
+ None if daemonized => match daemonize::lock_pid_file(&config) {
+ Ok(mut file) => {
+ use std::io::Write;
+ writeln!(file, "{}", std::process::id()).ok();
+ std::mem::forget(file);
+ }
+ Err(err) => log::warn!("no pid file after the takeover: {err:#}"),
+ },
+ None => {}
+ }
+ // Everything is ours already; not listening for the next successor
+ // is worth a log line, not an exit.
+ if let Err(err) = wezterm_mux_server_impl::handoff::spawn_handoff_listener(socket_path) {
+ log::error!("not listening for a successor: {err:#}");
}
- wezterm_mux_server_impl::handoff::spawn_handoff_listener(socket_path)?;
// The TCP listeners wait for the old server to release its ports.
let tls_servers = config.tls_servers.clone();
thread::spawn(move || {
@@ -414,7 +433,7 @@ async fn async_run(
});
}
#[cfg(not(unix))]
- let _ = takeover;
+ let _ = (takeover, daemonized);
let _config_subscription = config::subscribe_to_config_reload(move || {
promise::spawn::spawn_into_main_thread(async move {
if let Err(err) = update_mux_domains_for_server(&config::configuration()) {
@@ -427,7 +446,9 @@ async fn async_run(
let domain = mux.default_domain();
- {
+ // A takeover continues a mux that started long ago; its startup event
+ // already ran there.
+ if !took_over {
if let Err(err) = config::with_lua_config_on_main_thread(trigger_mux_startup).await {
log::error!("while processing mux-startup event: {:#}", err);
}
@@ -521,8 +542,13 @@ pub fn spawn_listener() -> anyhow::Result<()> {
thread::spawn(move || {
listener.run();
});
+ // Not fatal: a server that cannot be taken over is still a server.
#[cfg(unix)]
- wezterm_mux_server_impl::handoff::spawn_handoff_listener(unix_dom.socket_path())?;
+ if let Err(err) =
+ wezterm_mux_server_impl::handoff::spawn_handoff_listener(unix_dom.socket_path())
+ {
+ log::error!("not listening for a successor: {err:#}");
+ }
}
for tls_server in &config.tls_servers {