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.

wezterm-client: a unix domain can be the local session host

RoversX909f85cc3ab2
diff --git a/config/src/unix.rs b/config/src/unix.rs
index 467b0f4a..a244413c 100644
--- a/config/src/unix.rs
+++ b/config/src/unix.rs
@@ -62,6 +62,15 @@ pub struct UnixDomain {
/// instead.
#[dynamic(default)]
pub overlay_lag_indicator: bool,
+
+ /// This domain is the session server of the machine the GUI runs on:
+ /// the GUI keeps its local terminals in it so they survive the GUI
+ /// quitting, crashing or updating. Set by the GUI from its own
+ /// settings, not meant for the configuration file. The client
+ /// reconnects to such a domain, starts its server again when it is
+ /// gone, and takes an older server over instead of refusing it.
+ #[dynamic(default)]
+ pub local_session_host: bool,
}
impl Default for UnixDomain {
@@ -78,6 +87,7 @@ impl Default for UnixDomain {
local_echo_threshold_ms: None,
proxy_command: None,
overlay_lag_indicator: false,
+ local_session_host: false,
}
}
}
diff --git a/wezterm-client/src/client.rs b/wezterm-client/src/client.rs
index 14b4ee04..3077b9a2 100644
--- a/wezterm-client/src/client.rs
+++ b/wezterm-client/src/client.rs
@@ -652,7 +652,7 @@ fn process_unilateral(
if domain.connection_generation() != Some(connection_generation) {
return Ok(());
}
- crate::domain::deliver_thinkterm_tree(domain.domain_name(), state.tree);
+ crate::domain::deliver_thinkterm_tree(domain.client_domain_config(), state.tree);
anyhow::Result::<()>::Ok(())
})
.detach();
@@ -1232,12 +1232,18 @@ impl Reconnectable {
matches!(&self.config, ClientDomainConfig::Unix(_))
}
+ fn is_local_session_host(&self) -> bool {
+ self.config.is_local_session_host()
+ }
+
fn reconnectable(&mut self) -> bool {
match &self.config {
- // It doesn't make sense to reconnect to a unix socket; we only
- // get disconnected it it dies, so respawning it would not preserve
- // the set of tabs and we'd have confusing and inconsistent state
- ClientDomainConfig::Unix(_) => false,
+ // The session server of this machine: it exits when a newer
+ // build takes its panes over (same runtime id, the client
+ // rebinds) and it can crash (a replacement, restored from the
+ // saved layout). Any other unix domain only goes away when its
+ // server dies, and respawning one would not bring the tabs back.
+ ClientDomainConfig::Unix(unix) => unix.local_session_host,
ClientDomainConfig::Tls(_) => true,
// An ssh transport dies whenever the network path changes
// (VPN egress rotation, sleep/wake, flaky wifi); the remote mux
@@ -1255,7 +1261,13 @@ impl Reconnectable {
/// common case by far is a network-level drop, we still reconnect. The
/// reconnect UI is cancellable for the rare deliberate-shutdown case.
fn reconnect_on_eof(&self) -> bool {
- matches!(&self.config, ClientDomainConfig::Ssh(_))
+ match &self.config {
+ ClientDomainConfig::Ssh(_) => true,
+ // EOF is how a handoff or a crash of the local session server
+ // shows up.
+ ClientDomainConfig::Unix(unix) => unix.local_session_host,
+ ClientDomainConfig::Tls(_) => false,
+ }
}
fn connect(
@@ -1374,7 +1386,11 @@ impl Reconnectable {
let stream = match unix_connect_with_retry(&target, false, max_attempts) {
Ok(stream) => stream,
Err(e) => {
- if no_auto_start || unix_dom.no_serve_automatically || !initial {
+ // The session server of this machine is started again on a
+ // reconnect too: nothing answering after the retries means
+ // it is gone, and the replacement restores the saved layout.
+ let may_start_on_reconnect = initial || unix_dom.local_session_host;
+ if no_auto_start || unix_dom.no_serve_automatically || !may_start_on_reconnect {
bail!("failed to connect to {:?}: {}", target, e);
}
log::warn!(
@@ -1874,7 +1890,15 @@ impl Client {
// revive the server after a couple of instant
// deaths — it still only spawns one if connecting
// to the existing socket fails.
- let no_auto_start = short_sessions < 2;
+ // The local session host is started again
+ // whenever nothing answers -- unless what was
+ // started keeps dying at once, which no restart
+ // fixes; then the backoff and the give-up apply.
+ let no_auto_start = if reconnectable.is_local_session_host() {
+ short_sessions >= 3
+ } else {
+ short_sessions < 2
+ };
match reconnectable.connect(initial, &mut ui, no_auto_start) {
Ok(_) => {
log::info!("Transport reconnected; restoring mux session");
@@ -2011,6 +2035,11 @@ impl Client {
self.fatal_connection_error.lock().unwrap().replace(reason);
}
+ /// See `ClientDomainConfig::is_local_session_host`.
+ pub fn is_local_session_host(&self) -> bool {
+ self.client_domain_config.is_local_session_host()
+ }
+
pub fn into_client_domain_config(self) -> ClientDomainConfig {
self.client_domain_config
}
@@ -2422,6 +2451,30 @@ mod tests {
use super::{
describe_server_build_mismatch, is_auth_cancelled, Reconnectable, RegistrationBarrier,
};
+ use crate::domain::ClientDomainConfig;
+
+ #[test]
+ fn only_the_local_session_host_reconnects_over_a_unix_socket() {
+ let plain = Reconnectable::new(
+ ClientDomainConfig::Unix(config::UnixDomain::default()),
+ None,
+ );
+ let mut plain = plain;
+ assert!(!plain.reconnectable());
+ assert!(!plain.reconnect_on_eof());
+ assert!(!plain.is_local_session_host());
+
+ let mut host = Reconnectable::new(
+ ClientDomainConfig::Unix(config::UnixDomain {
+ local_session_host: true,
+ ..Default::default()
+ }),
+ None,
+ );
+ assert!(host.reconnectable());
+ assert!(host.reconnect_on_eof());
+ assert!(host.is_local_session_host());
+ }
#[test]
fn an_identical_build_is_not_worth_warning_about() {
diff --git a/wezterm-client/src/domain.rs b/wezterm-client/src/domain.rs
index 122381a7..855df767 100644
--- a/wezterm-client/src/domain.rs
+++ b/wezterm-client/src/domain.rs
@@ -1285,6 +1285,43 @@ impl ClientInner {
targets
}
+ /// The runtime these bindings named is gone and nothing on the
+ /// replacement corresponds to them: forget them before anything is
+ /// asked of the new server by an old id. The local mirrors stay until
+ /// `reap_dead_runtime_mirrors`.
+ fn forget_dead_runtime_bindings(&self) {
+ self.pending_recovery_windows.lock().unwrap().clear();
+ self.remote_to_local_window.lock().unwrap().clear();
+ self.remote_to_local_tab.lock().unwrap().clear();
+ self.remote_to_local_pane.lock().unwrap().clear();
+ self.remote_to_local_stack.lock().unwrap().clear();
+ self.reported_viewports.lock().unwrap().clear();
+ self.remote_agent_statuses.lock().unwrap().clear();
+ }
+
+ /// Kill every local mirror of this domain: the terminals they showed
+ /// died with the old runtime. Nothing is sent to the server (the ids
+ /// mean nothing there), and the windows left empty are pruned, which
+ /// is what makes the GUI rebuild them from its layout store.
+ fn reap_dead_runtime_mirrors(&self) {
+ let mux = Mux::get();
+ let mut dead = Vec::new();
+ for pane in mux.iter_panes() {
+ if pane.domain_id() != self.local_domain_id {
+ continue;
+ }
+ if let Some(client_pane) = pane.downcast_ref::<ClientPane>() {
+ client_pane.ignore_next_kill();
+ }
+ dead.push(pane.pane_id());
+ }
+ log::info!(
+ "dropping {} mirrors of the replaced session server's terminals",
+ dead.len()
+ );
+ mux.domain_was_detached(self.local_domain_id);
+ }
+
/// Prepare to bind a fresh mux runtime into the local windows that were
/// already displaying it. The old tabs stay alive and opaque until the
/// replacement topology has been installed; they are removed only after
@@ -1407,7 +1444,14 @@ impl ClientInner {
};
match access.mode {
codec::FrontendAccessMode::Handoff => {
- return Ok(self.remote_owner_is_self(access.owner.as_ref()));
+ // No owner: the server decides (the first screen, or the
+ // one that was driving and came back, is let through and
+ // becomes the owner on its first viewport; anyone else is
+ // refused there). Refusing here would refuse the splits of
+ // a layout restored before anything was painted.
+ return Ok(
+ access.owner.is_none() || self.remote_owner_is_self(access.owner.as_ref())
+ );
}
codec::FrontendAccessMode::TmuxLatest => {}
}
@@ -1470,6 +1514,12 @@ impl ClientDomainConfig {
}
}
+ /// The session server of the machine the GUI runs on; see
+ /// `UnixDomain::local_session_host`.
+ pub fn is_local_session_host(&self) -> bool {
+ matches!(self, ClientDomainConfig::Unix(unix) if unix.local_session_host)
+ }
+
pub fn local_echo_threshold_ms(&self) -> Option<u64> {
match self {
ClientDomainConfig::Unix(unix) => unix.local_echo_threshold_ms,
@@ -1956,13 +2006,33 @@ fn request_thinkterm_frontend_recovery(
}
}
-pub(crate) fn deliver_thinkterm_tree(domain_name: &str, tree: codec::ThinkTermTree) {
+pub(crate) fn deliver_thinkterm_tree(config: &ClientDomainConfig, tree: codec::ThinkTermTree) {
+ // The local session host keeps this machine's terminals, not a remote
+ // Space: its tree never reaches the sidebar.
+ if config.is_local_session_host() {
+ return;
+ }
let sink = *THINKTERM_TREE_SINK.lock().unwrap();
if let Some(sink) = sink {
- sink(domain_name, tree);
+ sink(config.name(), tree);
}
}
+/// Told when the local session host came back as a different, empty
+/// server: every mirror of this domain shows a terminal that no longer
+/// exists. The GUI rebuilds each affected window's thread from its layout
+/// store; without a sink the mirrors are simply dropped.
+pub type LocalSessionHostReplacedSink = fn(DomainId);
+
+lazy_static::lazy_static! {
+ static ref LOCAL_SESSION_HOST_REPLACED_SINK: Mutex<Option<LocalSessionHostReplacedSink>> =
+ Mutex::new(None);
+}
+
+pub fn set_local_session_host_replaced_sink(sink: LocalSessionHostReplacedSink) {
+ LOCAL_SESSION_HOST_REPLACED_SINK.lock().unwrap().replace(sink);
+}
+
pub(crate) fn deliver_thinkterm_connected(domain_name: &str, connection_generation: u64) {
let sink = *THINKTERM_CONNECT_SINK.lock().unwrap();
if let Some(sink) = sink {
@@ -1982,6 +2052,52 @@ pub(crate) fn deliver_thinkterm_session(
}
impl ClientDomain {
+ /// Whether this domain is the session server of the machine the GUI
+ /// runs on: its panes are local terminals kept out of process, not a
+ /// remote host, and the GUI treats them as local everywhere it would
+ /// otherwise treat a client domain as remote.
+ pub fn is_local_session_host(&self) -> bool {
+ self.config.is_local_session_host()
+ }
+
+ pub fn client_domain_config(&self) -> &ClientDomainConfig {
+ &self.config
+ }
+
+ /// The command to ask the server for. The session server of this
+ /// machine builds its commands in its own process, where the shell the
+ /// user chose in the GUI is not known: a spawn that asks for the
+ /// default program names that shell explicitly.
+ fn command_spec_for(&self, command: Option<&CommandBuilder>) -> Option<CommandSpec> {
+ let wants_default_prog = command.map_or(true, CommandBuilder::is_default_prog);
+ let chosen = if self.is_local_session_host() && wants_default_prog {
+ mux::default_prog::preferred_argv()
+ } else {
+ None
+ };
+ let Some(argv) = chosen else {
+ return command.map(CommandSpec::from_command_builder);
+ };
+ // Applied the way the in-process domain applies it: a bare shell
+ // travels as `SHELL`, so the server still runs it as the login
+ // shell; a shell with arguments is taken literally.
+ let mut cmd = command
+ .cloned()
+ .unwrap_or_else(CommandBuilder::new_default_prog);
+ match mux::default_prog::shell_application(&argv, cfg!(windows)) {
+ Some(mux::default_prog::ShellApplication::ShellEnv(shell)) => {
+ if cmd.get_env("SHELL").is_none() {
+ cmd.env("SHELL", shell);
+ }
+ }
+ Some(mux::default_prog::ShellApplication::Argv(argv)) => {
+ *cmd.get_argv_mut() = argv.into_iter().map(Into::into).collect();
+ }
+ None => {}
+ }
+ Some(CommandSpec::from_command_builder(&cmd))
+ }
+
/// The unix socket this domain connects to, if it is a unix domain
/// that connects to a socket at all. A mux server uses it to tell a
/// client domain that leads back to its own socket from one that leads
@@ -2419,10 +2535,26 @@ impl ClientDomain {
)
})?
.tree;
- deliver_thinkterm_tree(client.config.name(), tree.clone());
-
+ deliver_thinkterm_tree(&client.config, tree.clone());
+
+ // The session server of this machine has no layout of its own to
+ // restore from: a replacement is empty, and the terminals the old
+ // one held are gone. Their mirrors are dropped once this attach is
+ // through, and the GUI rebuilds the visible Space from its layout
+ // store, as it does for any window whose mux window died.
+ let host_replaced = server_replaced && client.is_local_session_host();
+ if host_replaced {
+ log::warn!(
+ "session server {} was replaced ({:?} -> {}); its terminals are gone, \
+ the visible Space is rebuilt from the local layout store",
+ client.config.name(),
+ prior_server_id,
+ server.server_id
+ );
+ inner.forget_dead_runtime_bindings();
+ }
let mut restored_targets = Vec::new();
- if server_replaced {
+ if server_replaced && !host_replaced {
inner.remember_recovery_targets(&recovery_targets);
log::info!(
"mux runtime changed from {:?} to {}; restoring {} visible workspaces",
@@ -2496,7 +2628,7 @@ impl ClientDomain {
}
}
let mut replacement = None;
- if server_replaced {
+ if server_replaced && !host_replaced {
if restored_targets.is_empty() {
bail!(
"replacement mux has no visible frontend workspace to restore for generation {connection_generation}"
@@ -2575,7 +2707,7 @@ impl ClientDomain {
log::warn!("failed to fetch agent statuses on reattach: {err:#}");
}
- if server_replaced {
+ if server_replaced && !host_replaced {
let active_remote_tabs = replacement_session
.as_ref()
.map(active_remote_tabs_by_workspace)
@@ -2687,6 +2819,13 @@ impl ClientDomain {
bail!("generation {connection_generation} was superseded during topology sync");
}
inner.mark_server_recovered();
+ if host_replaced {
+ let sink = *LOCAL_SESSION_HOST_REPLACED_SINK.lock().unwrap();
+ match sink {
+ Some(sink) => sink(domain_id),
+ None => inner.reap_dead_runtime_mirrors(),
+ }
+ }
Ok(true)
}
@@ -2907,7 +3046,7 @@ impl ClientDomain {
.mutate_thinkterm_tree(codec::MutateThinkTermTree { ops })
.await?;
let tree = response.tree;
- deliver_thinkterm_tree(self.config.name(), tree.clone());
+ deliver_thinkterm_tree(&self.config, tree.clone());
Ok(tree)
}
@@ -2980,7 +3119,7 @@ impl ClientDomain {
.inner()
.ok_or_else(|| anyhow!("domain is not attached"))?;
let response = inner.client.get_thinkterm_tree().await?;
- deliver_thinkterm_tree(self.config.name(), response.tree);
+ deliver_thinkterm_tree(&self.config, response.tree);
Ok(())
}
@@ -4659,7 +4798,7 @@ impl Domain for ClientDomain {
.client
.spawn_pane_in_stack(codec::SpawnPaneInStack {
pane_id: pane.remote_pane_id,
- command: command.as_ref().map(CommandSpec::from_command_builder),
+ command: self.command_spec_for(command.as_ref()),
command_dir,
domain: SpawnTabDomain::CurrentPaneDomain,
})
@@ -4854,9 +4993,9 @@ impl Domain for ClientDomain {
domain: SpawnTabDomain::DefaultDomain,
window_id: inner.local_to_remote_window(window),
size,
- command: command.as_ref().map(CommandSpec::from_command_builder),
+ command: self.command_spec_for(command.as_ref()),
command_dir,
- workspace,
+ workspace: workspace.clone(),
})
.await?;
@@ -4877,6 +5016,23 @@ impl Domain for ClientDomain {
let mux = Mux::get();
mux.add_tab_and_active_pane(&tab)?;
+ // The window was empty while the server answered, and an empty
+ // window is what a pane removal's prune sweeps away; the tab then
+ // needs a window of its own rather than a fatal error.
+ let window = if mux.get_window(window).is_some() {
+ window
+ } else {
+ let replacement = *mux.new_empty_window_for_domain(
+ Some(workspace.clone()),
+ None,
+ Some(self.local_domain_id),
+ );
+ log::warn!(
+ "local window {window} for the new tab was pruned while spawning; using {replacement}"
+ );
+ inner.record_remote_to_local_window_mapping(result.window_id, replacement);
+ replacement
+ };
mux.add_tab_to_window(&tab, window)?;
Ok(tab)
@@ -4983,7 +5139,7 @@ impl Domain for ClientDomain {
domain: SpawnTabDomain::CurrentPaneDomain,
pane_id: target_remote_pane_id,
split_request,
- command: command.as_ref().map(CommandSpec::from_command_builder),
+ command: self.command_spec_for(command.as_ref()),
command_dir,
move_pane_id,
})
@@ -5093,8 +5249,12 @@ impl Domain for ClientDomain {
}
}
+ /// The local session host is never detached: not when its last window
+ /// closes (the mux would drop it, and the next window spawns into it),
+ /// and not by a detach action. Closing the GUI is what ends this
+ /// connection.
fn detachable(&self) -> bool {
- true
+ !self.is_local_session_host()
}
fn detach(&self) -> anyhow::Result<()> {
@@ -5225,7 +5385,53 @@ impl ClientDomain {
let mut client = connect(config.clone(), ui.clone()).await?;
ui.output_str("Checking server version\n");
- if let Err(err) = client.verify_version_compat(&ui).await {
+ let verified = client.verify_version_compat(&ui).await;
+ // The session server of this machine is brought to this
+ // client's build whenever the two differ, codec mismatch or
+ // not: the running one hands its panes over and exits. A
+ // failed takeover leaves a compatible server serving and
+ // an incompatible one refused as before.
+ if let (ClientDomainConfig::Unix(unix), true) =
+ (&config, config.is_local_session_host())
+ {
+ let needs_takeover = match &verified {
+ Ok(info) => info.version_string != config::wezterm_version(),
+ Err(err)
+ if err
+ .downcast_ref::<crate::client::IncompatibleVersionError>()
+ .is_some() =>
+ {
+ true
+ }
+ // A stalled handshake or a refused registration is
+ // not something a takeover repairs.
+ Err(_) => return Err(verified.unwrap_err()),
+ };
+ if needs_takeover {
+ let outcome = {
+ let unix = unix.clone();
+ let ui = ui.clone();
+ spawn_into_new_thread(move || {
+ crate::local_update::take_over_local_server(&unix, &ui)
+ })
+ .await
+ };
+ match outcome {
+ Ok(true) => {
+ ui.output_str("Reconnecting to the updated server\n");
+ client = connect(config.clone(), ui.clone()).await?;
+ client.verify_version_compat(&ui).await?;
+ }
+ Ok(false) => {
+ verified?;
+ }
+ Err(takeover_err) => {
+ ui.output_str(&format!("Local update failed: {takeover_err:#}\n"));
+ verified?;
+ }
+ }
+ }
+ } else if let Err(err) = verified {
// A codec mismatch over ssh is the one connect failure
// this side can repair: the installer runs over the same
// hop, at this client's version. Anything else, and a
@@ -5284,8 +5490,10 @@ impl ClientDomain {
// The sidebar structure lives on the server. Fetching it is not worth
// failing an otherwise-good attach over: without it the Space simply
- // shows no rows until the next push or reconnect.
- if let Err(err) = self.fetch_thinkterm_tree().await {
+ // shows no rows until the next push or reconnect. The local session
+ // host has no Space of its own; its tree stays where it is.
+ if self.is_local_session_host() {
+ } else if let Err(err) = self.fetch_thinkterm_tree().await {
log::warn!(
"failed to fetch the ThinkTerm tree from {}: {err:#}",
self.config.name()
diff --git a/wezterm-client/src/lib.rs b/wezterm-client/src/lib.rs
index e5753a8b..db662aeb 100644
--- a/wezterm-client/src/lib.rs
+++ b/wezterm-client/src/lib.rs
@@ -1,5 +1,6 @@
pub mod client;
pub mod discovery;
pub mod domain;
+pub mod local_update;
pub mod pane;
pub mod remote_update;
diff --git a/wezterm-client/src/local_update.rs b/wezterm-client/src/local_update.rs
new file mode 100644
index 00000000..1ff55d19
--- /dev/null
+++ b/wezterm-client/src/local_update.rs
@@ -0,0 +1,136 @@
+//! Bringing the session server of this machine to the client's build.
+//!
+//! The GUI keeps its local terminals in a `thinkterm-mux-server` (see
+//! `UnixDomain::local_session_host`). After the application is updated the
+//! next launch finds a server of the previous build still running with
+//! every session in it. Rather than refuse it (codec mismatch) or serve
+//! stale behaviour (same codec, older build), the client runs the new
+//! server binary with `--takeover`: the running one hands its panes over
+//! and exits, and the client reconnects to the same runtime id.
+
+use anyhow::Context as _;
+use config::UnixDomain;
+use mux::connui::ConnectionUI;
+use std::io::Read;
+use std::process::{Command, Stdio};
+
+/// Run the server this client ships with as a successor of the one
+/// listening on `unix`'s socket. `Ok(true)` when it now serves; `Ok(false)`
+/// when the running server refused or the takeover failed (its output was
+/// relayed to the UI); `Err` when the command could not be run at all.
+pub fn take_over_local_server(unix: &UnixDomain, ui: &ConnectionUI) -> anyhow::Result<bool> {
+ let argv = takeover_argv(unix)?;
+ ui.output_str(&format!(
+ "Handing the sessions of the running mux server to this build ({})...\n",
+ config::wezterm_version()
+ ));
+ let mut cmd = Command::new(&argv[0]);
+ cmd.args(&argv[1..])
+ .stdin(Stdio::null())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
+ // The GUI runs with a locked-down umask; the server and every shell it
+ // spawns must get the one the user had (as unix_connect does).
+ #[cfg(unix)]
+ if let Some(mask) = umask::UmaskSaver::saved_umask() {
+ use std::os::unix::process::CommandExt;
+ unsafe {
+ cmd.pre_exec(move || {
+ libc::umask(mask);
+ Ok(())
+ });
+ }
+ }
+ let mut child = cmd
+ .spawn()
+ .with_context(|| format!("running {:?}", argv))?;
+ let stdout = child.stdout.take();
+ let stderr = child.stderr.take();
+ let relay = |ui: ConnectionUI, mut pipe: Box<dyn Read + Send>| {
+ std::thread::spawn(move || {
+ let mut buf = [0u8; 1024];
+ while let Ok(len) = pipe.read(&mut buf) {
+ if len == 0 {
+ break;
+ }
+ ui.output_str(&String::from_utf8_lossy(&buf[..len]));
+ }
+ })
+ };
+ let out_thread = stdout.map(|pipe| relay(ui.clone(), Box::new(pipe)));
+ let err_thread = stderr.map(|pipe| relay(ui.clone(), Box::new(pipe)));
+ // A daemonizing takeover reports within seconds; a serve command that
+ // does not daemonize would never return, so wait with a limit.
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120);
+ let status = loop {
+ if let Some(status) = child.try_wait().context("waiting for the takeover")? {
+ break status;
+ }
+ if std::time::Instant::now() >= deadline {
+ let _ = child.kill();
+ let _ = child.wait();
+ anyhow::bail!("the takeover did not report within 120 s");
+ }
+ std::thread::sleep(std::time::Duration::from_millis(100));
+ };
+ if let Some(thread) = out_thread {
+ let _ = thread.join();
+ }
+ if let Some(thread) = err_thread {
+ let _ = thread.join();
+ }
+ if status.success() {
+ ui.output_str("Handed over; reconnecting.\n");
+ Ok(true)
+ } else {
+ ui.output_str(&format!(
+ "The running server could not hand over ({status}); keeping it.\n"
+ ));
+ Ok(false)
+ }
+}
+
+/// The serve command of the domain (`thinkterm-mux-server --daemonize` next
+/// to this executable unless configured otherwise) with `--takeover`
+/// appended, so a custom serve command (`wsl -e ...`) takes over the same
+/// way it starts.
+fn takeover_argv(unix: &UnixDomain) -> anyhow::Result<Vec<std::ffi::OsString>> {
+ let mut argv = unix.serve_command()?;
+ if argv.is_empty() {
+ anyhow::bail!("the serve command of domain {} is empty", unix.name);
+ }
+ argv.push("--takeover".into());
+ Ok(argv)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::takeover_argv;
+ use config::UnixDomain;
+
+ #[test]
+ fn the_takeover_is_the_serve_command_plus_the_flag() {
+ let unix = UnixDomain {
+ name: "unix".into(),
+ serve_command: Some(vec!["wsl".into(), "-e".into(), "thinkterm-mux-server".into(), "--daemonize".into()]),
+ ..Default::default()
+ };
+ let argv = takeover_argv(&unix).unwrap();
+ assert_eq!(
+ argv,
+ vec!["wsl", "-e", "thinkterm-mux-server", "--daemonize", "--takeover"]
+ .into_iter()
+ .map(std::ffi::OsString::from)
+ .collect::<Vec<_>>()
+ );
+ }
+
+ #[test]
+ fn the_default_serve_command_is_the_bundled_server() {
+ let argv = takeover_argv(&UnixDomain::default()).unwrap();
+ let exe = std::path::Path::new(&argv[0]);
+ assert!(exe.ends_with("thinkterm-mux-server"), "{exe:?}");
+ assert_eq!(argv[1], "--daemonize");
+ assert_eq!(argv[2], "--takeover");
+ }
+}