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.

Run local sessions in a background session server on Windows

RoversXecb91962fc00
diff --git a/Cargo.lock b/Cargo.lock
index fb81ccd4..f11b5829 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3862,6 +3862,7 @@ dependencies = [
"wezterm-dynamic 0.2.1",
"wezterm-ssh",
"wezterm-term",
+ "wezterm-uds",
"winapi",
]
diff --git a/mux/Cargo.toml b/mux/Cargo.toml
index 41e55926..b3937cd4 100644
--- a/mux/Cargo.toml
+++ b/mux/Cargo.toml
@@ -54,12 +54,18 @@ wezterm-term = { workspace=true, features=["use_serde"] }
[target."cfg(windows)".dependencies]
ntapi.workspace = true
+wezterm-uds.workspace = true
winapi = { workspace=true, features = [
+ "errhandlingapi",
"handleapi",
"memoryapi",
"psapi",
"processthreadsapi",
+ "synchapi",
"tlhelp32",
+ "winbase",
+ "winerror",
+ "winnt",
]}
[dev-dependencies]
diff --git a/mux/src/session_server.rs b/mux/src/session_server.rs
index 20fc9f0a..e7eac3dd 100644
--- a/mux/src/session_server.rs
+++ b/mux/src/session_server.rs
@@ -35,11 +35,53 @@ pub fn pid_holding(pid_file: &Path) -> Option<u32> {
.filter(|pid| *pid > 1)
}
-/// No answer off unix: `daemonize` is `#![cfg(unix)]` entire, so no pid
-/// file is written to hold a lock on. Everything downstream -- `is_running`,
-/// `stop`, and the GUI's session host -- is short-circuited by this, which
-/// is why `socket_answers` below stays a stub too.
-#[cfg(not(unix))]
+/// Windows has no `flock`; the file's sharing mode is the lock. The server
+/// keeps the pid file open with write sharing denied (`lock_pid_file`), and
+/// the kernel drops that the moment its last handle closes -- when it exits
+/// or dies -- exactly as `flock` does. A probe that asks for write access
+/// is refused with ERROR_SHARING_VIOLATION while the server lives.
+///
+/// Unlike `flock`, any process can hold a file open that way (an antivirus
+/// scanner, an indexer), so the pid read from the file is only believed if
+/// it names a live `thinkterm-mux-server`.
+#[cfg(windows)]
+pub fn pid_holding(pid_file: &Path) -> Option<u32> {
+ if !windows::pid_file_held(pid_file) {
+ return None;
+ }
+ let pid = std::fs::read_to_string(pid_file)
+ .ok()?
+ .trim()
+ .parse::<u32>()
+ .ok()
+ .filter(|pid| *pid > 1)?;
+ windows::is_mux_server_process(pid).then_some(pid)
+}
+
+/// The lock the Windows server holds for its lifetime: the pid file opened
+/// with write sharing denied. Sibling of `daemonize::lock_pid_file` on unix.
+/// Truncated on success; the caller writes its pid with `write_pid`.
+///
+/// A scanner holding the file for a moment looks like a holder too, so a
+/// refusal is retried for about a second unless the pid in the file names a
+/// live server, in which case it is refused at once with the unix wording.
+#[cfg(windows)]
+pub fn lock_pid_file(pid_file: &Path) -> anyhow::Result<std::fs::File> {
+ windows::lock_pid_file(pid_file)
+}
+
+/// Write this process's pid into a locked pid file, replacing whatever the
+/// launcher left there.
+#[cfg(windows)]
+pub fn write_pid(file: &mut std::fs::File) -> std::io::Result<()> {
+ use std::io::{Seek, SeekFrom, Write};
+ file.set_len(0)?;
+ file.seek(SeekFrom::Start(0))?;
+ writeln!(file, "{}", std::process::id())?;
+ file.flush()
+}
+
+#[cfg(not(any(unix, windows)))]
pub fn pid_holding(_pid_file: &Path) -> Option<u32> {
None
}
@@ -86,10 +128,13 @@ pub fn socket_answers(path: &Path) -> bool {
/// uses to decide whether it may bind over a socket. That question fails
/// safe towards "someone is there"; this one asks whether *our* server is
/// up and fails safe towards "it is not", as the unix version above does on
-/// every error. Sharing one probe would invert one of them. Moot in
-/// practice: `pid_holding` returns `None` here, so both callers stop before
-/// they reach this.
-#[cfg(not(unix))]
+/// every error. Sharing one probe would invert one of them.
+#[cfg(windows)]
+pub fn socket_answers(path: &Path) -> bool {
+ wezterm_uds::UnixStream::connect(path).is_ok()
+}
+
+#[cfg(not(any(unix, windows)))]
pub fn socket_answers(_path: &Path) -> bool {
false
}
@@ -122,7 +167,244 @@ pub fn stop(pid_file: &Path, socket: &Path, wait: Duration) -> anyhow::Result<St
Ok(StopOutcome::Lingering { pid })
}
-#[cfg(not(unix))]
+/// Stop the server holding `pid_file`: its stop event is the SIGTERM of
+/// this platform (the server flushes its layouts and exits on it), waiting
+/// up to `wait` for its socket to close. Never `TerminateProcess`: a pid
+/// can be recycled between the read and the kill, and every Windows server
+/// that writes a pid file also creates the event, before the pid.
+#[cfg(windows)]
+pub fn stop(pid_file: &Path, socket: &Path, wait: Duration) -> anyhow::Result<StopOutcome> {
+ let Some(pid) = pid_holding(pid_file) else {
+ return Ok(StopOutcome::NotRunning);
+ };
+ windows::signal_stop(pid)?;
+ let started = Instant::now();
+ while started.elapsed() < wait {
+ if !socket_answers(socket) && pid_holding(pid_file).is_none() {
+ return Ok(StopOutcome::Stopped { pid });
+ }
+ std::thread::sleep(Duration::from_millis(50));
+ }
+ Ok(StopOutcome::Lingering { pid })
+}
+
+#[cfg(not(any(unix, windows)))]
pub fn stop(_pid_file: &Path, _socket: &Path, _wait: Duration) -> anyhow::Result<StopOutcome> {
anyhow::bail!("stopping the session server is not supported on this platform")
}
+
+/// The stop event a Windows server waits on, created by the server before
+/// it publishes its pid and set by whoever stops it. Re-exported so the
+/// server binary and the stoppers agree on one name.
+#[cfg(windows)]
+pub use windows::{create_stop_event, StopEvent};
+
+#[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};
+ use winapi::shared::winerror::ERROR_SHARING_VIOLATION;
+ 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::winnt::{
+ EVENT_MODIFY_STATE, FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, HANDLE,
+ PROCESS_QUERY_LIMITED_INFORMATION,
+ };
+
+ const SHARE_EVERYTHING: u32 = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
+ /// The image name a pid must carry to be believed as the server.
+ const SERVER_IMAGE_STEM: &str = "thinkterm-mux-server";
+
+ fn is_sharing_violation(err: &std::io::Error) -> bool {
+ err.raw_os_error() == Some(ERROR_SHARING_VIOLATION as i32)
+ }
+
+ /// Whether some process holds `pid_file` open with write sharing denied.
+ /// A file that does not exist, or any other failure, counts as not held.
+ pub(super) fn pid_file_held(pid_file: &Path) -> bool {
+ match std::fs::OpenOptions::new()
+ .write(true)
+ .share_mode(SHARE_EVERYTHING)
+ .open(pid_file)
+ {
+ Ok(_) => false,
+ Err(err) => is_sharing_violation(&err),
+ }
+ }
+
+ /// Whether `pid` is a live process whose image is the mux server.
+ pub(super) fn is_mux_server_process(pid: u32) -> bool {
+ 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))
+ }
+
+ fn holder_pid(pid_file: &Path) -> Option<u32> {
+ std::fs::read_to_string(pid_file)
+ .ok()?
+ .trim()
+ .parse::<u32>()
+ .ok()
+ .filter(|pid| *pid > 1)
+ }
+
+ pub(super) fn lock_pid_file(pid_file: &Path) -> anyhow::Result<std::fs::File> {
+ let dir = pid_file
+ .parent()
+ .ok_or_else(|| anyhow::anyhow!("{} has no parent?", pid_file.display()))?;
+ std::fs::create_dir_all(dir)
+ .with_context(|| format!("while creating directory structure: {}", dir.display()))?;
+ let deadline = Instant::now() + Duration::from_secs(1);
+ loop {
+ match std::fs::OpenOptions::new()
+ .create(true)
+ .read(true)
+ .write(true)
+ .share_mode(FILE_SHARE_READ)
+ .open(pid_file)
+ {
+ Ok(file) => {
+ file.set_len(0)
+ .with_context(|| format!("truncating pid file {}", pid_file.display()))?;
+ return Ok(file);
+ }
+ Err(err) if is_sharing_violation(&err) => {
+ let holder = holder_pid(pid_file).filter(|pid| is_mux_server_process(*pid));
+ if holder.is_none() && Instant::now() < deadline {
+ // Something other than a server has it open for a
+ // moment; a scanner lets go, a server never does.
+ std::thread::sleep(Duration::from_millis(50));
+ continue;
+ }
+ let holder = holder
+ .map(|pid| format!(" (a mux server with pid {pid} holds it)"))
+ .unwrap_or_default();
+ anyhow::bail!("unable to lock pid file {}{holder}: {err}", pid_file.display());
+ }
+ Err(err) => {
+ return Err(err).with_context(|| format!("opening pid file {}", pid_file.display()));
+ }
+ }
+ }
+ }
+
+ fn stop_event_name(pid: u32) -> Vec<u16> {
+ format!("Local\\ThinkTermMuxServer-{pid}-stop")
+ .encode_utf16()
+ .chain(std::iter::once(0))
+ .collect()
+ }
+
+ /// Set the stop event of the server with `pid`. An event that cannot
+ /// be opened means no server of ours has that pid (it exited, and the
+ /// number may already belong to someone else): an error, never a kill.
+ pub(super) fn signal_stop(pid: u32) -> anyhow::Result<()> {
+ let name = stop_event_name(pid);
+ let handle = unsafe { OpenEventW(EVENT_MODIFY_STATE, 0, name.as_ptr()) };
+ if handle.is_null() {
+ anyhow::bail!(
+ "could not stop the session server (pid {pid}): its stop event is not there: {}",
+ std::io::Error::last_os_error()
+ );
+ }
+ let ok = unsafe { SetEvent(handle) };
+ let err = std::io::Error::last_os_error();
+ unsafe { CloseHandle(handle) };
+ if ok == 0 {
+ anyhow::bail!("could not stop the session server (pid {pid}): {err}");
+ }
+ Ok(())
+ }
+
+ /// The server's end of the stop event: owned for the life of the process.
+ pub struct StopEvent(HANDLE);
+
+ // A HANDLE is a plain kernel object reference; the waiting thread is the
+ // only user after creation.
+ unsafe impl Send for StopEvent {}
+
+ impl StopEvent {
+ /// Block until someone sets the event.
+ pub fn wait(&self) {
+ unsafe { WaitForSingleObject(self.0, INFINITE) };
+ }
+ }
+
+ impl Drop for StopEvent {
+ fn drop(&mut self) {
+ unsafe { CloseHandle(self.0) };
+ }
+ }
+
+ /// Create this process's stop event. Manual reset, so a set that
+ /// arrives before the waiter thread exists is not lost.
+ pub fn create_stop_event() -> anyhow::Result<StopEvent> {
+ let name = stop_event_name(std::process::id());
+ let handle = unsafe { CreateEventW(std::ptr::null_mut(), 1, 0, name.as_ptr()) };
+ if handle.is_null() || handle == INVALID_HANDLE_VALUE {
+ return Err(std::io::Error::last_os_error()).context("creating the stop event");
+ }
+ Ok(StopEvent(handle))
+ }
+
+ #[cfg(test)]
+ mod tests {
+ use super::*;
+
+ /// The sharing probe reports "held" only while a lock handle is open,
+ /// which is what stands in for flock on this platform.
+ #[test]
+ fn a_pid_file_counts_only_while_locked() {
+ let dir = std::env::temp_dir();
+ let path = dir.join(format!("thinkterm-pid-lock-test-{}", std::process::id()));
+ let _ = std::fs::remove_file(&path);
+ assert!(!pid_file_held(&path), "a missing file is not held");
+
+ let mut holder = lock_pid_file(&path).unwrap();
+ super::super::write_pid(&mut holder).unwrap();
+ assert!(pid_file_held(&path), "a locked file is held");
+ assert_eq!(holder_pid(&path), Some(std::process::id()));
+ // The test binary is not the server, so the public probe does not
+ // believe the pid even though the lock is real.
+ assert_eq!(super::super::pid_holding(&path), None);
+ assert!(
+ lock_pid_file(&path).is_err(),
+ "a second lock is refused while the first is held"
+ );
+
+ drop(holder);
+ assert!(!pid_file_held(&path), "dropping the handle releases the lock");
+ assert_eq!(super::super::pid_holding(&path), None);
+ let _ = std::fs::remove_file(&path);
+ }
+
+ #[test]
+ fn a_stop_event_is_found_by_pid_and_wakes_the_waiter() {
+ let event = create_stop_event().unwrap();
+ let waiter = std::thread::spawn(move || {
+ event.wait();
+ });
+ signal_stop(std::process::id()).unwrap();
+ waiter.join().unwrap();
+ // Nothing of ours has this pid.
+ assert!(signal_stop(u32::MAX - 7).is_err());
+ }
+ }
+}
diff --git a/thinkterm-i18n/i18n/de-DE.ftl b/thinkterm-i18n/i18n/de-DE.ftl
index 18f77d05..0a662131 100644
--- a/thinkterm-i18n/i18n/de-DE.ftl
+++ b/thinkterm-i18n/i18n/de-DE.ftl
@@ -112,6 +112,7 @@ settings-remote-update-keep-sessions = Sitzungen beim Update eines Remote-Server
settings-remote-update-keep-sessions-description = Der laufende Server übergibt seine Panes an die neue Version, statt zu stoppen; nichts, was darin läuft, endet.
settings-local-sessions-via-mux = Lokale Terminals in einem Hintergrund-Sitzungsserver halten
settings-local-sessions-via-mux-description = Lokale Terminals laufen in einem Mux-Server auf diesem Rechner und überstehen das Beenden, Abstürzen oder Aktualisieren von ThinkTerm. Wird beim nächsten Start von ThinkTerm wirksam.
+settings-local-sessions-via-mux-description-windows = Lokale Terminals laufen in einem Mux-Server auf diesem Rechner und überstehen das Beenden oder Abstürzen von ThinkTerm. Eine Aktualisierung von ThinkTerm beendet den Server. Wird beim nächsten Start von ThinkTerm wirksam.
settings-terminal-heading = Terminal-Konfiguration
settings-default-shell = Standard-Shell
settings-default-shell-description = Das Programm, das ein neues Terminal startet. Wird beim nächsten Öffnen wirksam.
diff --git a/thinkterm-i18n/i18n/en-US.ftl b/thinkterm-i18n/i18n/en-US.ftl
index e7dc16fb..1d4880b0 100644
--- a/thinkterm-i18n/i18n/en-US.ftl
+++ b/thinkterm-i18n/i18n/en-US.ftl
@@ -112,6 +112,7 @@ settings-remote-update-keep-sessions = Keep sessions when updating a remote serv
settings-remote-update-keep-sessions-description = The running server hands its panes to the new version instead of stopping; nothing running in them ends.
settings-local-sessions-via-mux = Keep local terminals in a background session server
settings-local-sessions-via-mux-description = Local terminals run in a mux server on this machine and survive quitting, crashing or updating ThinkTerm. Takes effect the next time ThinkTerm starts.
+settings-local-sessions-via-mux-description-windows = Local terminals run in a mux server on this machine and survive quitting or crashing ThinkTerm. Updating ThinkTerm stops the server. Takes effect the next time ThinkTerm starts.
settings-terminal-heading = Terminal configuration
settings-default-shell = Default Shell
settings-default-shell-description = The program a new terminal runs. Takes effect the next time you open one.
diff --git a/thinkterm-i18n/i18n/fr-FR.ftl b/thinkterm-i18n/i18n/fr-FR.ftl
index 6513df5f..5493afd6 100644
--- a/thinkterm-i18n/i18n/fr-FR.ftl
+++ b/thinkterm-i18n/i18n/fr-FR.ftl
@@ -112,6 +112,7 @@ settings-remote-update-keep-sessions = Conserver les sessions lors de la mise à
settings-remote-update-keep-sessions-description = Le serveur en cours transmet ses panneaux à la nouvelle version au lieu de s’arrêter ; rien de ce qui y tourne ne s’interrompt.
settings-local-sessions-via-mux = Garder les terminaux locaux dans un serveur de sessions en arrière-plan
settings-local-sessions-via-mux-description = Les terminaux locaux tournent dans un serveur mux sur cette machine et survivent à la fermeture, au plantage ou à la mise à jour de ThinkTerm. Prend effet au prochain lancement.
+settings-local-sessions-via-mux-description-windows = Les terminaux locaux tournent dans un serveur mux sur cette machine et survivent à la fermeture ou au plantage de ThinkTerm. Mettre à jour ThinkTerm arrête le serveur. Prend effet au prochain lancement.
settings-terminal-heading = Configuration du terminal
settings-default-shell = Shell par défaut
settings-default-shell-description = Le programme lancé par un nouveau terminal. Prend effet à la prochaine ouverture.
diff --git a/thinkterm-i18n/i18n/ja-JP.ftl b/thinkterm-i18n/i18n/ja-JP.ftl
index 9724fba7..8369d443 100644
--- a/thinkterm-i18n/i18n/ja-JP.ftl
+++ b/thinkterm-i18n/i18n/ja-JP.ftl
@@ -109,6 +109,7 @@ settings-remote-update-keep-sessions = リモートサーバー更新時にセ
settings-remote-update-keep-sessions-description = 実行中のサーバーは停止せず、ペインを新しいバージョンに引き継ぎます。実行中の処理は中断されません。
settings-local-sessions-via-mux = ローカル端末をバックグラウンドのセッションサーバーに置く
settings-local-sessions-via-mux-description = ローカル端末はこのマシンの mux サーバーで動作し、ThinkTerm の終了・クラッシュ・更新後も残ります。次回起動時に有効になります。
+settings-local-sessions-via-mux-description-windows = ローカル端末はこのマシンの mux サーバーで動作し、ThinkTerm の終了・クラッシュ後も残ります。ThinkTerm を更新するとサーバーは停止します。次回起動時に有効になります。
settings-terminal-heading = ターミナル設定
settings-default-shell = 既定のシェル
settings-default-shell-description = 新しいターミナルで実行するプログラムです。次に開いたときから有効になります。
diff --git a/thinkterm-i18n/i18n/zh-CN.ftl b/thinkterm-i18n/i18n/zh-CN.ftl
index a679efdf..1c59b4e1 100644
--- a/thinkterm-i18n/i18n/zh-CN.ftl
+++ b/thinkterm-i18n/i18n/zh-CN.ftl
@@ -109,6 +109,7 @@ settings-remote-update-keep-sessions = 更新远端 server 时保留会话
settings-remote-update-keep-sessions-description = 运行中的 server 把 pane 交给新版本而不是停掉,里面跑的程序不会中断。
settings-local-sessions-via-mux = 本地终端放在后台会话 server 里
settings-local-sessions-via-mux-description = 本地终端跑在本机的 mux server 中,ThinkTerm 退出、崩溃或更新后会话仍在。下次启动 ThinkTerm 时生效。
+settings-local-sessions-via-mux-description-windows = 本地终端跑在本机的 mux server 中,ThinkTerm 退出或崩溃后会话仍在;更新 ThinkTerm 会停止该 server。下次启动 ThinkTerm 时生效。
settings-terminal-heading = 终端配置
settings-default-shell = 默认 Shell
settings-default-shell-description = 新开终端运行的程序,下次打开时生效。
diff --git a/wezterm-client/Cargo.toml b/wezterm-client/Cargo.toml
index 6020aac3..b229c1ad 100644
--- a/wezterm-client/Cargo.toml
+++ b/wezterm-client/Cargo.toml
@@ -44,5 +44,6 @@ tempfile.workspace = true
[target."cfg(windows)".dependencies]
winapi = { workspace=true, features = [
+ "winbase",
"winuser",
]}
diff --git a/wezterm-client/src/client.rs b/wezterm-client/src/client.rs
index 8b83b5f9..abfc6689 100644
--- a/wezterm-client/src/client.rs
+++ b/wezterm-client/src/client.rs
@@ -1289,6 +1289,14 @@ impl Reconnectable {
}
}
+ // The server is a console-subsystem binary; without this a
+ // console window flashes every time the GUI starts it.
+ #[cfg(windows)]
+ {
+ use std::os::windows::process::CommandExt as _;
+ cmd.creation_flags(winapi::um::winbase::CREATE_NO_WINDOW);
+ }
+
log::warn!("Running: {:?}", cmd);
ui.output_str(&format!("Running: {:?}\n", cmd));
diff --git a/wezterm-client/src/domain.rs b/wezterm-client/src/domain.rs
index 8d988907..783b43e1 100644
--- a/wezterm-client/src/domain.rs
+++ b/wezterm-client/src/domain.rs
@@ -5516,7 +5516,64 @@ impl ClientDomain {
// not something a takeover repairs.
Err(_) => return Err(verified.unwrap_err()),
};
- if needs_takeover {
+ if needs_takeover && !cfg!(unix) {
+ // No handoff on this platform (it passes descriptors).
+ // A server that still speaks our codec keeps serving;
+ // one that does not is stopped, and the reconnect
+ // starts this build's server. Its terminals end, which
+ // is what an update without a handoff means here.
+ match &verified {
+ Ok(info) => log::info!(
+ "the session server runs ThinkTerm {} and this is {}; it keeps \
+ serving, since this platform has no in-place handoff",
+ info.version_string,
+ config::wezterm_version()
+ ),
+ Err(err) => {
+ ui.output_str(&format!(
+ "The running session server cannot be used ({err:#}) and this \
+ platform cannot hand its sessions over; stopping it and \
+ starting this build's server. Its terminals end.\n"
+ ));
+ let pid_file = config::configuration().daemon_options.pid_file();
+ let socket = unix.socket_path();
+ let outcome = spawn_into_new_thread(move || {
+ mux::session_server::stop(
+ &pid_file,
+ &socket,
+ std::time::Duration::from_secs(10),
+ )
+ })
+ .await;
+ match outcome {
+ Ok(mux::session_server::StopOutcome::NotRunning) => {
+ // A server left by a build that wrote no pid
+ // file cannot be found; only a person can
+ // stop that one.
+ ui.output_str(
+ "Nothing holds the session server's pid file, so it \
+ cannot be stopped from here: stop thinkterm-mux-server \
+ by hand, then start ThinkTerm again.\n",
+ );
+ verified?;
+ }
+ Ok(_) => {
+ ui.output_str("Reconnecting to a fresh server\n");
+ *self.early_remote_state.lock().unwrap() =
+ EarlyRemoteState::default();
+ client = connect(config.clone(), ui.clone()).await?;
+ client.verify_version_compat(&ui).await?;
+ }
+ Err(stop_err) => {
+ ui.output_str(&format!(
+ "Could not stop the session server: {stop_err:#}\n"
+ ));
+ verified?;
+ }
+ }
+ }
+ }
+ } else if needs_takeover {
let outcome = {
let unix = unix.clone();
let ui = ui.clone();
diff --git a/wezterm-gui/src/local_sessions.rs b/wezterm-gui/src/local_sessions.rs
index 8f9eaf78..e6dbf965 100644
--- a/wezterm-gui/src/local_sessions.rs
+++ b/wezterm-gui/src/local_sessions.rs
@@ -27,11 +27,13 @@ static HOST: OnceLock<Option<String>> = OnceLock::new();
/// its terminals in process as if the setting were off.
static FELL_BACK: Mutex<bool> = Mutex::new(false);
-/// Whether this build and platform can run local sessions in a server:
-/// the handoff that keeps sessions across an update passes descriptors,
-/// which has no Windows implementation.
+/// Whether this build and platform can run local sessions in a server.
+/// Unix and Windows both can; what Windows lacks is the handoff that keeps
+/// sessions across an update (it passes descriptors), so there the server
+/// simply keeps serving and a newly launched GUI reconnects to it, and an
+/// update stops it.
pub(crate) fn supported() -> bool {
- cfg!(unix)
+ cfg!(any(unix, windows))
}
/// The setting, as it applies to this launch.
@@ -121,7 +123,6 @@ pub(crate) fn note_host_attached() {
/// Its terminals end with it, which is what turning the setting off asks
/// for. Runs once this process is the GUI, never from a launch that hands
/// its command to a GUI already running.
-#[cfg(unix)]
pub(crate) fn stop_background_server_when_off(config: &ConfigHandle) {
if !supported() || wanted() {
return;
@@ -166,9 +167,6 @@ pub(crate) fn stop_background_server_when_off(config: &ConfigHandle) {
}
}
-#[cfg(not(unix))]
-pub(crate) fn stop_background_server_when_off(_config: &ConfigHandle) {}
-
/// The pid file and socket of the session server at the default socket.
fn server_files(config: &ConfigHandle) -> (std::path::PathBuf, std::path::PathBuf) {
(
diff --git a/wezterm-gui/src/settings_window.rs b/wezterm-gui/src/settings_window.rs
index faa4189c..b54ae781 100644
--- a/wezterm-gui/src/settings_window.rs
+++ b/wezterm-gui/src/settings_window.rs
@@ -5638,7 +5638,13 @@ impl SettingsWindow {
row_width,
self.compact_row_step(),
&crate::i18n::tr("settings-local-sessions-via-mux"),
- "settings-local-sessions-via-mux-description",
+ // Windows has no in-place handoff: sessions survive quitting
+ // and crashing there, not updating, and the text says so.
+ if cfg!(windows) {
+ "settings-local-sessions-via-mux-description-windows"
+ } else {
+ "settings-local-sessions-via-mux-description"
+ },
self.native_settings.workspaces.local_sessions_via_mux,
SettingsAction::ToggleLocalSessionsViaMux,
)?;
diff --git a/wezterm-mux-server-impl/src/local.rs b/wezterm-mux-server-impl/src/local.rs
index 7732d4a6..fe76ca8a 100644
--- a/wezterm-mux-server-impl/src/local.rs
+++ b/wezterm-mux-server-impl/src/local.rs
@@ -158,12 +158,17 @@ fn other_server_holding_pid_file(pid_file: &std::path::Path) -> Option<u32> {
(unsafe { libc::kill(pid as libc::pid_t, 0) } == 0).then_some(pid)
}
-/// No answer off unix: the pid file is written by `daemonize`, which is
-/// `#![cfg(unix)]` entire, so on Windows there is nothing holding a lock to
-/// ask about. `someone_listens` carries the whole guard there, which leaves
-/// a server stalled long enough to fill its accept backlog able to be bound
-/// over -- the case this pid file exists to catch on unix.
-#[cfg(not(unix))]
+/// On Windows the daemon holds the pid file open with write sharing denied
+/// (`mux::session_server::lock_pid_file`); the probe there is the same
+/// question flock answers above, and our own lock is excluded by pid too.
+#[cfg(windows)]
+fn other_server_holding_pid_file(pid_file: &std::path::Path) -> Option<u32> {
+ mux::session_server::pid_holding(pid_file).filter(|pid| *pid != std::process::id())
+}
+
+/// No pid file is written on other platforms; `someone_listens` carries the
+/// whole guard there.
+#[cfg(not(any(unix, windows)))]
fn other_server_holding_pid_file(_pid_file: &std::path::Path) -> Option<u32> {
None
}
diff --git a/wezterm-mux-server/Cargo.toml b/wezterm-mux-server/Cargo.toml
index 0ff21d2d..3587f47a 100644
--- a/wezterm-mux-server/Cargo.toml
+++ b/wezterm-mux-server/Cargo.toml
@@ -39,7 +39,15 @@ wezterm-gui-subcommands.workspace = true
wezterm-term.workspace = true
[target."cfg(windows)".dependencies]
-winapi = { workspace=true, features = [ "winuser" ]}
+winapi = { workspace=true, features = [
+ "consoleapi",
+ "handleapi",
+ "minwindef",
+ "winbase",
+ "winerror",
+ "winnt",
+ "winuser",
+]}
[target.'cfg(windows)'.build-dependencies]
embed-resource.workspace = true
diff --git a/wezterm-mux-server/src/main.rs b/wezterm-mux-server/src/main.rs
index 33f3b38d..5f23d0c8 100644
--- a/wezterm-mux-server/src/main.rs
+++ b/wezterm-mux-server/src/main.rs
@@ -76,6 +76,14 @@ struct Opt {
#[arg(long, hide = true)]
takeover_report_fd: Option<i32>,
+ /// The pid file the launching `--daemonize` process locked and made
+ /// inheritable, as a raw handle value; this process writes its pid into
+ /// it and keeps it open for its lifetime. The Windows sibling of
+ /// `--pid-file-fd`.
+ #[cfg(windows)]
+ #[arg(long, hide = true)]
+ pid_file_handle: Option<usize>,
+
/// Instead of executing your shell, run PROG.
/// For example: `thinkterm start -- bash -l` will spawn bash
/// as if it were a login shell.
@@ -116,6 +124,9 @@ fn run() -> anyhow::Result<()> {
}
}
+ #[cfg(windows)]
+ windows_daemon::adopt(opts.pid_file_handle)?;
+
config::common_init(
opts.config_file.as_ref(),
&opts.config_override,
@@ -124,6 +135,9 @@ fn run() -> anyhow::Result<()> {
let config = config::configuration();
+ #[cfg(windows)]
+ windows_daemon::lock_own_pid_file(&config)?;
+
config.update_ulimit()?;
if let Some(value) = &config.default_ssh_auth_sock {
std::env::set_var("SSH_AUTH_SOCK", value);
@@ -200,14 +214,7 @@ fn run() -> anyhow::Result<()> {
#[cfg(windows)]
{
- use std::os::windows::process::CommandExt;
- cmd.stdout(config.daemon_options.open_stdout()?);
- cmd.stderr(config.daemon_options.open_stderr()?);
-
- cmd.creation_flags(winapi::um::winbase::DETACHED_PROCESS);
- let child = cmd.spawn();
- drop(child);
- return Ok(());
+ return windows_daemon::spawn_detached(cmd, &config);
}
#[cfg(unix)]
@@ -619,11 +626,166 @@ fn install_shutdown_signal_handler() -> anyhow::Result<()> {
Ok(())
}
-#[cfg(not(unix))]
+/// The Windows sibling of the SIGTERM thread above: the stop event created
+/// in `windows_daemon::adopt` (before the pid was published, so a stopper
+/// that reads the pid always finds it) and Ctrl+C on a foreground server
+/// both flush the layouts and exit.
+#[cfg(windows)]
+fn install_shutdown_signal_handler() -> anyhow::Result<()> {
+ windows_daemon::install_shutdown_handler()
+}
+
+#[cfg(not(any(unix, windows)))]
fn install_shutdown_signal_handler() -> anyhow::Result<()> {
Ok(())
}
+/// What `daemonize.rs` does on unix, for Windows: the launching process
+/// locks the pid file and hands it to a detached child, the child publishes
+/// its pid and answers a named stop event instead of SIGTERM. There is no
+/// takeover: an in-place update passes descriptors, which this platform
+/// cannot, so a running server keeps serving until it is stopped.
+#[cfg(windows)]
+mod windows_daemon {
+ use anyhow::Context as _;
+ use mux::session_server::StopEvent;
+ use std::os::windows::io::{AsRawHandle as _, FromRawHandle as _, RawHandle};
+ use std::os::windows::process::CommandExt as _;
+ use std::sync::Mutex;
+ use winapi::shared::minwindef::{BOOL, DWORD, TRUE};
+ use winapi::shared::winerror::ERROR_ACCESS_DENIED;
+ use winapi::um::consoleapi::SetConsoleCtrlHandler;
+ use winapi::um::handleapi::SetHandleInformation;
+ use winapi::um::winbase::{
+ CREATE_BREAKAWAY_FROM_JOB, CREATE_NEW_PROCESS_GROUP, DETACHED_PROCESS, HANDLE_FLAG_INHERIT,
+ };
+ use winapi::um::winnt::HANDLE;
+
+ /// Held from `adopt` until `install_shutdown_handler` takes it.
+ static STOP_EVENT: Mutex<Option<StopEvent>> = Mutex::new(None);
+
+ /// Runs first thing after argument parsing, in every server process:
+ /// create the stop event, and when a launcher handed over the locked pid
+ /// file, take it out of inheritance (shells spawned later must not carry
+ /// it, as `set_cloexec` does on unix) and write this pid into it.
+ pub fn adopt(pid_file_handle: Option<usize>) -> anyhow::Result<()> {
+ let event = mux::session_server::create_stop_event()?;
+ *STOP_EVENT.lock().unwrap() = Some(event);
+ if let Some(raw) = pid_file_handle {
+ let mut file = unsafe { std::fs::File::from_raw_handle(raw as RawHandle) };
+ unsafe { SetHandleInformation(raw as HANDLE, HANDLE_FLAG_INHERIT, 0) };
+ match mux::session_server::write_pid(&mut file) {
+ Ok(()) => std::mem::forget(file),
+ Err(err) => {
+ // The handle did not survive the spawn. The launcher is
+ // exiting and lets go of its lock; `lock_own_pid_file`
+ // takes one once the configuration says where it is.
+ log::warn!(
+ "the inherited pid file handle is unusable ({err:#}); \
+ the pid file is locked directly instead"
+ );
+ std::mem::forget(file);
+ NEEDS_OWN_LOCK.store(true, std::sync::atomic::Ordering::SeqCst);
+ }
+ }
+ }
+ Ok(())
+ }
+
+ static NEEDS_OWN_LOCK: std::sync::atomic::AtomicBool =
+ std::sync::atomic::AtomicBool::new(false);
+
+ /// After the configuration is loaded: the fallback lock for a daemon
+ /// whose inherited handle was unusable. The launcher's lock is released
+ /// as it exits, which `lock_pid_file` waits out.
+ pub fn lock_own_pid_file(config: &config::ConfigHandle) -> anyhow::Result<()> {
+ if !NEEDS_OWN_LOCK.swap(false, std::sync::atomic::Ordering::SeqCst) {
+ return Ok(());
+ }
+ let mut own = mux::session_server::lock_pid_file(&config.daemon_options.pid_file())?;
+ mux::session_server::write_pid(&mut own)?;
+ std::mem::forget(own);
+ Ok(())
+ }
+
+ /// The `--daemonize` launcher: lock the pid file (a second launcher
+ /// fails here with the unix wording), then start the server detached,
+ /// with the locked file inherited. Returns once the child is running;
+ /// the client connects to the socket with retries, as on unix.
+ pub fn spawn_detached(
+ mut cmd: std::process::Command,
+ config: &config::ConfigHandle,
+ ) -> anyhow::Result<()> {
+ let pid_file = mux::session_server::lock_pid_file(&config.daemon_options.pid_file())?;
+ let raw = pid_file.as_raw_handle();
+ if unsafe { SetHandleInformation(raw as HANDLE, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT) } == 0
+ {
+ return Err(std::io::Error::last_os_error()).context("making the pid file inheritable");
+ }
+ cmd.arg("--pid-file-handle");
+ cmd.arg((raw as usize).to_string());
+ cmd.stdin(std::process::Stdio::null());
+ cmd.stdout(config.daemon_options.open_stdout()?);
+ cmd.stderr(config.daemon_options.open_stderr()?);
+
+ // Detached from this console and from the launcher's job, so a GUI
+ // started under a kill-on-close job (installers, some launchers)
+ // does not take the server down with it.
+ let flags = DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP;
+ cmd.creation_flags(flags | CREATE_BREAKAWAY_FROM_JOB);
+ let child = match cmd.spawn() {
+ Ok(child) => child,
+ Err(err) if err.raw_os_error() == Some(ERROR_ACCESS_DENIED as i32) => {
+ log::warn!(
+ "the launcher's job does not allow breaking away; the session server stays \
+ in it and ends with the job"
+ );
+ cmd.creation_flags(flags);
+ cmd.spawn().context("spawning the session server")?
+ }
+ Err(err) => return Err(err).context("spawning the session server"),
+ };
+ log::info!("session server started as pid {}", child.id());
+ // The child holds its own copy of the lock; this one closes with us.
+ drop(child);
+ drop(pid_file);
+ Ok(())
+ }
+
+ unsafe extern "system" fn ctrl_handler(_ctrl_type: DWORD) -> BOOL {
+ request_shutdown();
+ TRUE
+ }
+
+ fn request_shutdown() {
+ promise::spawn::spawn_into_main_thread(async move {
+ if let Err(err) = wezterm_mux_server_impl::thinkterm_layout::flush_now() {
+ log::error!("flushing ThinkTerm layouts before shutdown: {err:#}");
+ }
+ std::process::exit(0);
+ })
+ .detach();
+ }
+
+ pub fn install_shutdown_handler() -> anyhow::Result<()> {
+ let event = STOP_EVENT
+ .lock()
+ .unwrap()
+ .take()
+ .ok_or_else(|| anyhow::anyhow!("the stop event was not created"))?;
+ std::thread::Builder::new()
+ .name("stop-event".into())
+ .spawn(move || {
+ event.wait();
+ log::info!("stop requested; flushing and exiting");
+ request_shutdown();
+ })
+ .context("spawning the stop-event thread")?;
+ unsafe { SetConsoleCtrlHandler(Some(ctrl_handler), TRUE) };
+ Ok(())
+ }
+}
+
mod ossl;
mod web;