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-gui: keep local terminals in a background session server (opt-in)

RoversX750b593d31b3
diff --git a/wezterm-gui/i18n/en-US.ftl b/wezterm-gui/i18n/en-US.ftl
index 29d54c45..2ecae8ac 100644
--- a/wezterm-gui/i18n/en-US.ftl
+++ b/wezterm-gui/i18n/en-US.ftl
@@ -110,6 +110,8 @@ settings-notification-sounds = Notification Sounds
settings-notification-sounds-description = Play a short sound when a thread finishes or starts waiting on you.
settings-remote-update-keep-sessions = Keep sessions when updating a remote server
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-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.
@@ -528,6 +530,9 @@ settings-status-notification-sounds-error = Could not save the notification soun
settings-status-remote-update-keep-sessions-on = Remote updates will hand sessions over to the new version.
settings-status-remote-update-keep-sessions-off = Remote updates will ask before stopping the server.
settings-status-remote-update-keep-sessions-error = Could not save the remote update setting: { $error }
+settings-status-local-sessions-via-mux-on = Local terminals will run in a background session server from the next launch.
+settings-status-local-sessions-via-mux-off = Local terminals will run inside ThinkTerm from the next launch.
+settings-status-local-sessions-via-mux-error = Could not save the local sessions setting: { $error }
settings-status-window-restore-off = Main window frame restore disabled for new macOS windows.
settings-status-window-restore-error = Unable to save window restore setting: { $error }
settings-status-renderer = Main window renderer set to { $renderer }; restart ThinkTerm to apply it.
diff --git a/wezterm-gui/i18n/fr-FR.ftl b/wezterm-gui/i18n/fr-FR.ftl
index 6442ec18..095c7181 100644
--- a/wezterm-gui/i18n/fr-FR.ftl
+++ b/wezterm-gui/i18n/fr-FR.ftl
@@ -110,6 +110,8 @@ settings-notification-sounds = Sons de notification
settings-notification-sounds-description = Émettre un son bref lorsqu’une session se termine ou attend une réponse.
settings-remote-update-keep-sessions = Conserver les sessions lors de la mise à jour d’un serveur distant
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-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.
@@ -528,6 +530,9 @@ settings-status-notification-sounds-error = Impossible d’enregistrer le régla
settings-status-remote-update-keep-sessions-on = Les mises à jour distantes transmettront les sessions à la nouvelle version.
settings-status-remote-update-keep-sessions-off = Les mises à jour distantes demanderont avant d’arrêter le serveur.
settings-status-remote-update-keep-sessions-error = Impossible d’enregistrer le réglage de mise à jour distante : { $error }
+settings-status-local-sessions-via-mux-on = Les terminaux locaux tourneront dans un serveur de sessions dès le prochain lancement.
+settings-status-local-sessions-via-mux-off = Les terminaux locaux tourneront dans ThinkTerm dès le prochain lancement.
+settings-status-local-sessions-via-mux-error = Impossible d’enregistrer le réglage des sessions locales : { $error }
settings-status-window-restore-off = Restauration de la taille et position désactivée pour les nouvelles fenêtres macOS.
settings-status-window-restore-error = Impossible d’enregistrer la restauration de fenêtre : { $error }
settings-status-renderer = Moteur de rendu principal défini sur { $renderer } ; redémarrez ThinkTerm pour l’appliquer.
diff --git a/wezterm-gui/i18n/ja-JP.ftl b/wezterm-gui/i18n/ja-JP.ftl
index d700c087..4a37a09f 100644
--- a/wezterm-gui/i18n/ja-JP.ftl
+++ b/wezterm-gui/i18n/ja-JP.ftl
@@ -107,6 +107,8 @@ settings-notification-sounds = 通知音
settings-notification-sounds-description = スレッドが完了したとき、または入力待ちになったときに短い音を鳴らします。
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-terminal-heading = ターミナル設定
settings-default-shell = 既定のシェル
settings-default-shell-description = 新しいターミナルで実行するプログラムです。次に開いたときから有効になります。
@@ -519,6 +521,9 @@ settings-status-notification-sounds-error = 通知音の設定を保存できま
settings-status-remote-update-keep-sessions-on = リモート更新時にセッションを新しいバージョンへ引き継ぎます。
settings-status-remote-update-keep-sessions-off = リモート更新時はサーバーを停止する前に確認します。
settings-status-remote-update-keep-sessions-error = リモート更新の設定を保存できませんでした: { $error }
+settings-status-local-sessions-via-mux-on = 次回起動からローカル端末はバックグラウンドのセッションサーバーで動作します。
+settings-status-local-sessions-via-mux-off = 次回起動からローカル端末は ThinkTerm 内で動作します。
+settings-status-local-sessions-via-mux-error = ローカルセッションの設定を保存できませんでした: { $error }
settings-status-window-restore-off = 新しい macOS ウィンドウで位置とサイズの復元を無効にしました。
settings-status-window-restore-error = ウィンドウ復元設定を保存できません:{ $error }
settings-status-renderer = メインウィンドウのレンダラーを { $renderer } に設定しました。ThinkTerm の再起動後に適用されます。
diff --git a/wezterm-gui/i18n/zh-CN.ftl b/wezterm-gui/i18n/zh-CN.ftl
index 0bf8e09e..59989329 100644
--- a/wezterm-gui/i18n/zh-CN.ftl
+++ b/wezterm-gui/i18n/zh-CN.ftl
@@ -107,6 +107,8 @@ settings-notification-sounds = 提示音
settings-notification-sounds-description = Thread 完成或等待你输入时播放提示音。
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-terminal-heading = 终端配置
settings-default-shell = 默认 Shell
settings-default-shell-description = 新开终端运行的程序,下次打开时生效。
@@ -519,6 +521,9 @@ settings-status-notification-sounds-error = 无法保存提示音设置:{ $err
settings-status-remote-update-keep-sessions-on = 已开启:更新远端时会把会话交给新版本。
settings-status-remote-update-keep-sessions-off = 已关闭:更新远端时会先询问是否停止 server。
settings-status-remote-update-keep-sessions-error = 无法保存远端更新设置:{ $error }
+settings-status-local-sessions-via-mux-on = 已开启:下次启动起本地终端跑在后台会话 server 里。
+settings-status-local-sessions-via-mux-off = 已关闭:下次启动起本地终端跑在 ThinkTerm 进程内。
+settings-status-local-sessions-via-mux-error = 无法保存本地会话设置:{ $error }
settings-status-window-restore-off = 已为新的 macOS 窗口关闭主窗口位置与大小恢复。
settings-status-window-restore-error = 无法保存窗口恢复设置:{ $error }
settings-status-renderer = 主窗口渲染器已设为 { $renderer };重启 ThinkTerm 后生效。
diff --git a/wezterm-gui/src/commands.rs b/wezterm-gui/src/commands.rs
index 5ae38a1a..b3a6bfab 100644
--- a/wezterm-gui/src/commands.rs
+++ b/wezterm-gui/src/commands.rs
@@ -282,7 +282,7 @@ impl CommandDef {
let label = name;
if dom.state() == DomainState::Attached {
- if name == "local" {
+ if name == "local" || !dom.detachable() {
continue;
}
result.push(ExpandedCommand {
diff --git a/wezterm-gui/src/frontend.rs b/wezterm-gui/src/frontend.rs
index 62dc5795..75ffa88f 100644
--- a/wezterm-gui/src/frontend.rs
+++ b/wezterm-gui/src/frontend.rs
@@ -437,7 +437,7 @@ impl GuiFrontEnd {
match mux
.spawn_tab_or_window(
window_id,
- SpawnTabDomain::DomainName("local".to_string()),
+ crate::local_sessions::local_spawn_domain(),
cmd,
cwd,
TerminalSize::default(),
@@ -610,8 +610,12 @@ impl GuiFrontEnd {
let Some(mux_window) = mux.get_window(mux_window_id) else {
continue;
};
+ // A window of the local session host is a local window:
+ // shown like one, restored like one.
(
- mux_window.origin_domain().is_some(),
+ mux_window
+ .origin_domain()
+ .is_some_and(|id| !crate::local_sessions::is_host_domain_id(id)),
mux_window.get_workspace().to_string(),
)
};
@@ -670,7 +674,7 @@ impl GuiFrontEnd {
future
}
- fn spawn_space_window(&self) {
+ pub(crate) fn spawn_space_window(&self) {
// Each Dock "New Window" gets its own Space and its own GUI window, and
// must work regardless of whatever else is in flight. We claim a
// distinct (unoccupied) Space synchronously so rapid repeated clicks
@@ -899,7 +903,20 @@ impl GuiFrontEnd {
fn detach_attached_client_domains(&self) {
let mux = Mux::get();
for domain in mux.iter_domains() {
- if domain.detachable() && domain.state() == mux::domain::DomainState::Attached {
+ if domain.state() != mux::domain::DomainState::Attached {
+ continue;
+ }
+ // The local session host is not detachable by the mux or by an
+ // action, but the last window closing is this connection's
+ // end: its mirrors must go so the mux empties and the process
+ // exits (its terminals live on in the server).
+ if let Some(client) = domain.downcast_ref::<ClientDomain>() {
+ if client.is_local_session_host() {
+ client.perform_detach();
+ continue;
+ }
+ }
+ if domain.detachable() {
if let Err(err) = domain.detach() {
log::error!(
"while detaching domain {} after the last window closed: {err:#}",
diff --git a/wezterm-gui/src/local_sessions.rs b/wezterm-gui/src/local_sessions.rs
new file mode 100644
index 00000000..0a4b65b7
--- /dev/null
+++ b/wezterm-gui/src/local_sessions.rs
@@ -0,0 +1,321 @@
+//! Local terminals kept in a background mux server.
+//!
+//! With the setting on, the GUI is a client of `thinkterm-mux-server` for
+//! this machine too: the default unix domain is marked as the *local
+//! session host* (`UnixDomain::local_session_host`), attached before the
+//! first window, and made the default domain, so every local terminal is
+//! spawned in the server and survives the GUI quitting, crashing or
+//! updating. The in-process `local` domain stays registered as the
+//! fallback and for `--domain local`.
+//!
+//! Everywhere the GUI decides "is this a remote host?" by finding a client
+//! domain, the host is excluded: its threads are the local Space's, closing
+//! its windows kills their panes, a second launch reuses this GUI. Those
+//! decisions live next to the code they gate; this module only knows which
+//! domain the host is.
+
+use config::{ConfigHandle, UnixDomain};
+use mux::domain::Domain;
+use mux::Mux;
+use std::sync::{Arc, Mutex, OnceLock};
+use wezterm_client::domain::{ClientDomain, ClientDomainConfig};
+use window::WindowOps as _;
+
+/// The name of the host domain for this launch, once `install` chose one.
+static HOST: OnceLock<Option<String>> = OnceLock::new();
+/// Set when the host could not be attached at launch: the GUI then runs
+/// 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.
+pub(crate) fn supported() -> bool {
+ cfg!(unix)
+}
+
+/// The setting, as it applies to this launch.
+pub(crate) fn wanted() -> bool {
+ supported() && crate::native_settings::local_sessions_via_mux()
+}
+
+/// The unix domain that is, or would be, the host: the configured one
+/// named `unix` (the default domain every configuration has), else the
+/// first one that connects to a socket rather than through a proxy.
+pub(crate) fn candidate(config: &ConfigHandle) -> Option<UnixDomain> {
+ candidate_in(&config.unix_domains)
+}
+
+fn candidate_in(domains: &[UnixDomain]) -> Option<UnixDomain> {
+ domains
+ .iter()
+ .find(|dom| dom.name == "unix" && dom.proxy_command.is_none())
+ .or_else(|| domains.iter().find(|dom| dom.proxy_command.is_none()))
+ .cloned()
+}
+
+/// Register the host domain with the mux when the setting is on. Runs
+/// before the configured client domains are registered, which skip a name
+/// that already exists, so this marked copy is the one the mux keeps.
+/// Returns the host's name.
+pub(crate) fn install(mux: &Mux, config: &ConfigHandle) -> Option<String> {
+ let name = if wanted() && config.default_domain.is_some() {
+ // A configured default domain is re-applied on every config
+ // reload; it wins, and the setting is left as a documented no-op.
+ log::warn!(
+ "local sessions: the configuration sets default_domain = {:?}, so local terminals \
+ stay there and the session server is not used",
+ config.default_domain.as_deref().unwrap_or_default()
+ );
+ None
+ } else if wanted() {
+ candidate(config).map(|mut unix| {
+ unix.local_session_host = true;
+ unix.connect_automatically = true;
+ // Every pane of the host is one this GUI asked for: no default
+ // shell in a workspace nothing shows.
+ if let Ok(mut serve) = unix.serve_command() {
+ serve.push("--no-initial-pane".into());
+ unix.serve_command =
+ Some(serve.iter().map(|arg| arg.to_string_lossy().into_owned()).collect());
+ }
+ if mux.get_domain_by_name(&unix.name).is_none() {
+ let domain: Arc<dyn Domain> =
+ Arc::new(ClientDomain::new(ClientDomainConfig::Unix(unix.clone())));
+ mux.add_domain(&domain);
+ }
+ unix.name
+ })
+ } else {
+ None
+ };
+ HOST.get_or_init(|| name.clone());
+ name
+}
+
+/// The host's domain name for this launch, if local sessions run in it.
+pub(crate) fn host_domain_name() -> Option<String> {
+ if *FELL_BACK.lock().unwrap() {
+ return None;
+ }
+ HOST.get().cloned().flatten()
+}
+
+/// Whether `name` is the host domain of this launch.
+pub(crate) fn is_host_domain_name(name: &str) -> bool {
+ host_domain_name().as_deref() == Some(name)
+}
+
+/// Whether the domain with `id` is the host domain of this launch.
+pub(crate) fn is_host_domain_id(id: mux::domain::DomainId) -> bool {
+ let Some(host) = host_domain_name() else {
+ return false;
+ };
+ Mux::get()
+ .get_domain(id)
+ .is_some_and(|domain| domain.domain_name() == host)
+}
+
+/// The host could not be attached at launch: run this launch in process.
+/// The domain stays registered but detached; nothing retries it, since a
+/// host attached later would find windows already classified as local.
+pub(crate) fn fall_back_to_in_process(mux: &Mux, why: &anyhow::Error) {
+ let Some(host) = HOST.get().cloned().flatten() else {
+ return;
+ };
+ *FELL_BACK.lock().unwrap() = true;
+ match mux.get_domain_by_name("local") {
+ Some(local) => {
+ mux.set_default_domain(&local);
+ log::error!(
+ "local sessions: could not attach the session server {host} ({why:#}); \
+ this launch runs its terminals in process"
+ );
+ }
+ None => log::error!(
+ "local sessions: could not attach the session server {host} ({why:#}) and \
+ there is no in-process domain to fall back to"
+ ),
+ }
+}
+
+/// The host came back as a different, empty server (it crashed and was
+/// started again): the terminals its mirrors show are gone. Each window
+/// that showed only such mirrors rebuilds its thread from the layout store
+/// into the new server -- the old mux window is moved aside first so the
+/// thread's workspace counts as dead, then killed once the new one is
+/// adopted. An activity guard keeps the GUI from quitting while the mux
+/// is briefly empty.
+pub(crate) fn on_host_replaced(domain_id: mux::domain::DomainId) {
+ promise::spawn::spawn_into_main_thread(async move {
+ let _activity = mux::activity::Activity::new();
+ let mux = Mux::get();
+ let dead_windows: Vec<mux::window::WindowId> = mux
+ .iter_windows()
+ .into_iter()
+ .filter(|window_id| {
+ mux.get_window(*window_id).is_some_and(|window| {
+ let panes: Vec<_> = window
+ .iter()
+ .flat_map(|tab| tab.iter_all_panes())
+ .collect();
+ !panes.is_empty() && panes.iter().all(|pane| pane.domain_id() == domain_id)
+ })
+ })
+ .collect();
+ log::info!(
+ "local sessions: {} windows showed terminals of the replaced server; rebuilding them",
+ dead_windows.len()
+ );
+ let rebuilt_panes: std::collections::HashSet<_> = dead_windows
+ .iter()
+ .filter_map(|window_id| mux.get_window(*window_id))
+ .flat_map(|window| {
+ window
+ .iter()
+ .flat_map(|tab| tab.iter_all_panes())
+ .map(|pane| pane.pane_id())
+ .collect::<Vec<_>>()
+ })
+ .collect();
+ for window_id in dead_windows {
+ let Some(gui) = crate::frontend::front_end().gui_window_for_mux_window(window_id)
+ else {
+ // Nothing shows it: gone, along with its dead mirrors.
+ if let Some(window) = mux.get_window(window_id) {
+ for pane in window.iter().flat_map(|tab| tab.iter_all_panes()) {
+ if let Some(client_pane) =
+ pane.downcast_ref::<wezterm_client::pane::ClientPane>()
+ {
+ client_pane.ignore_next_kill();
+ }
+ }
+ }
+ mux.kill_window(window_id);
+ continue;
+ };
+ // Moved aside quietly (a notified move would be synced into the
+ // thread store and the thread would then "live" there), the
+ // thread's own workspace counts as dead; the activation below
+ // materializes it again from the layout store, adopts the new
+ // window into this GUI window, and kills the old workspace.
+ let Some(old_workspace) = mux
+ .get_window(window_id)
+ .map(|window| window.get_workspace().to_string())
+ else {
+ continue;
+ };
+ let dead_workspace = if old_workspace.starts_with("dead-session:") {
+ old_workspace
+ } else {
+ let dead_workspace = format!("dead-session:{old_workspace}");
+ mux.rename_workspace_quietly(&old_workspace, &dead_workspace);
+ dead_workspace
+ };
+ if let Some(window) = mux.get_window(window_id) {
+ for pane in window.iter().flat_map(|tab| tab.iter_all_panes()) {
+ if let Some(client_pane) =
+ pane.downcast_ref::<wezterm_client::pane::ClientPane>()
+ {
+ client_pane.ignore_next_kill();
+ }
+ }
+ }
+ gui.window.notify(crate::termwindow::TermWindowNotif::Apply(Box::new(
+ move |term_window| {
+ let thread_id = term_window.window.clone().and_then(|window| {
+ crate::workspace_threads::ensure_active_thread_for_space(
+ term_window.active_space_id(),
+ )
+ .map(|thread_id| (thread_id, window))
+ });
+ match thread_id {
+ Some((thread_id, window)) => term_window
+ .activate_workspace_thread_with_cleanup(
+ thread_id,
+ &window,
+ vec![dead_workspace],
+ ),
+ None => {
+ // Nothing to rebuild into: the parked window
+ // must not outlive this.
+ log::warn!("local sessions: no thread to rebuild for the window");
+ Mux::get().kill_window(window_id);
+ }
+ }
+ },
+ )));
+ }
+ // Windows mixing host terminals with others keep the others; only
+ // the dead mirrors go (nothing is sent for them: their ids mean
+ // nothing on the replacement).
+ for pane in mux.iter_panes() {
+ if pane.domain_id() != domain_id || rebuilt_panes.contains(&pane.pane_id()) {
+ continue;
+ }
+ if let Some(client_pane) = pane.downcast_ref::<wezterm_client::pane::ClientPane>() {
+ client_pane.ignore_next_kill();
+ }
+ mux.remove_pane(pane.pane_id());
+ }
+ smol::Timer::after(std::time::Duration::from_secs(3)).await;
+ })
+ .detach();
+}
+
+/// Where a terminal that is asked for "locally" goes: the host while local
+/// sessions run in it, the in-process domain otherwise. For the places that
+/// name `local` explicitly rather than using the default domain.
+pub(crate) fn local_spawn_domain() -> config::keyassignment::SpawnTabDomain {
+ config::keyassignment::SpawnTabDomain::DomainName(
+ host_domain_name().unwrap_or_else(|| "local".to_string()),
+ )
+}
+
+/// A layout records the domain each terminal ran in, and a terminal of the
+/// host is recorded as `local` (it is one). While the setting is on, `local`
+/// restores into the host; off, it restores in process. A unix domain named
+/// in a layout is one the user chose and is left alone either way.
+pub(crate) fn alias_recorded_domain(recorded: &str) -> Option<String> {
+ alias_for(recorded, host_domain_name().as_deref())
+}
+
+fn alias_for(recorded: &str, host: Option<&str>) -> Option<String> {
+ let host = host?;
+ (recorded == "local").then(|| host.to_string())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{alias_for, candidate_in};
+ use config::UnixDomain;
+
+ fn unix(name: &str, proxy: bool) -> UnixDomain {
+ UnixDomain {
+ name: name.into(),
+ proxy_command: proxy.then(|| vec!["wsl".to_string()]),
+ ..Default::default()
+ }
+ }
+
+ #[test]
+ fn the_candidate_prefers_the_default_unix_domain_over_proxies() {
+ let domains = vec![unix("wsl", true), unix("other", false), unix("unix", false)];
+ assert_eq!(candidate_in(&domains).map(|d| d.name), Some("unix".to_string()));
+ let domains = vec![unix("wsl", true), unix("other", false)];
+ assert_eq!(candidate_in(&domains).map(|d| d.name), Some("other".to_string()));
+ assert!(candidate_in(&[unix("wsl", true)]).is_none());
+ }
+
+ #[test]
+ fn recorded_local_terminals_follow_the_setting() {
+ // On: local terminals restore into the host; a unix domain named in
+ // a layout was the user's choice and remote domains are untouched.
+ assert_eq!(alias_for("local", Some("unix")), Some("unix".to_string()));
+ assert_eq!(alias_for("unix", Some("unix")), None);
+ assert_eq!(alias_for("vm", Some("unix")), None);
+ // Off: nothing is rewritten.
+ assert_eq!(alias_for("local", None), None);
+ assert_eq!(alias_for("unix", None), None);
+ }
+}
diff --git a/wezterm-gui/src/main.rs b/wezterm-gui/src/main.rs
index 29d8f7f2..e1dfc66c 100644
--- a/wezterm-gui/src/main.rs
+++ b/wezterm-gui/src/main.rs
@@ -48,6 +48,7 @@ mod i18n;
mod input_diagnostics;
mod inputmap;
mod markdown_editor;
+mod local_sessions;
mod native_paths;
mod native_settings;
mod overlay;
@@ -361,6 +362,27 @@ async fn spawn_tab_in_domain_if_mux_is_empty(
let domain = domain.unwrap_or_else(|| mux.default_domain());
+ // The local session host was attached before this ran, but the local
+ // windows for its remote ones arrive with the topology sync, which can
+ // still be in flight; deciding before it lands spawns a startup tab
+ // into a server that already holds the threads. Sync first.
+ let mut workspace = workspace;
+ if let Some(client) = domain.downcast_ref::<ClientDomain>() {
+ if client.is_local_session_host() && domain.state() == mux::domain::DomainState::Attached {
+ if let Err(err) = client.resync().await {
+ log::warn!("local sessions: syncing the session server at startup: {err:#}");
+ }
+ // Its threads live in thread workspaces, which reconcile leaves
+ // hidden, so "the domain has panes" is not "a window will
+ // open". Judge the startup workspace alone: a startup tab there
+ // gets a window, whose restore then adopts the live thread and
+ // cleans the tab up -- as it does in process.
+ if workspace.is_none() {
+ workspace = Some(mux.active_workspace());
+ }
+ }
+ }
+
if !is_connecting {
if have_panes_in_domain_and_ws(&domain, &workspace) {
return Ok(());
@@ -750,13 +772,29 @@ async fn connect_to_auto_connect_domains() -> anyhow::Result<()> {
continue;
}
// One UI (its own window, since no GUI window exists yet) hosts the
- // first attempt and any background retries for this domain.
- let ui = mux::connui::ConnectionUI::with_params(Default::default());
+ // first attempt and any background retries for this domain. The
+ // local session host connects headless: a unix socket asks nothing,
+ // and the UI's own mux window would be taken for the startup window
+ // by the thread store, which then starts a fresh thread when it
+ // closes.
+ let ui = if client.is_local_session_host() {
+ mux::connui::ConnectionUI::new_headless()
+ } else {
+ mux::connui::ConnectionUI::with_params(Default::default())
+ };
// The first attempt stays synchronous so that, on the happy path,
// auto-connected domains are live before the first GUI window opens
// (their windows adopt/fold correctly instead of racing startup).
match client.attach_with_ui(None, ui.clone()).await {
Ok(()) => {}
+ // The session server of this machine must be there before the
+ // first window spawns into it; without it this launch runs its
+ // terminals in process rather than in a domain that is not
+ // attached.
+ Err(err) if client.is_local_session_host() => {
+ crate::local_sessions::fall_back_to_in_process(&mux, &err);
+ ui.close();
+ }
Err(err) if is_fatal_attach_error(&err) => {
log::error!("auto-connect {}: {err:#}", dom.domain_name());
}
@@ -960,8 +998,12 @@ enum Publish {
impl Publish {
pub fn resolve(mux: &Arc<Mux>, config: &ConfigHandle, always_new_process: bool) -> Self {
- if mux.default_domain().domain_name() != config.default_domain.as_deref().unwrap_or("local")
- {
+ // The local session host is the default domain of an ordinary
+ // launch too: a second launch still hands its command to this GUI.
+ let default_name = mux.default_domain().domain_name().to_string();
+ let default_is_local = default_name == config.default_domain.as_deref().unwrap_or("local")
+ || crate::local_sessions::is_host_domain_name(&default_name);
+ if !default_is_local {
return Self::NoConnectNoPublish;
}
@@ -1166,6 +1208,9 @@ fn setup_mux(
);
mux.set_active_workspace(&default_workspace_name);
crate::update::load_last_release_info();
+ // Before the configured client domains: the host is the configured
+ // unix domain with two flags set, registered under the same name.
+ let session_host = crate::local_sessions::install(&mux, config);
update_mux_domains(config)?;
// Register ThinkTerm's saved SSH hosts as runtime mux domains so that
// reconnecting / restoring remote sessions can resolve them by name.
@@ -1175,8 +1220,12 @@ fn setup_mux(
// Local removal only; the server keeps its copy.
crate::ssh_hosts::forget_spaces_of_deleted_hosts();
- let default_name =
- default_domain_name.unwrap_or(config.default_domain.as_deref().unwrap_or("local"));
+ let default_name = default_domain_name.unwrap_or(
+ session_host
+ .as_deref()
+ .or(config.default_domain.as_deref())
+ .unwrap_or("local"),
+ );
let domain = match mux.get_domain_by_name(default_name) {
Some(domain) => domain,
@@ -1224,6 +1273,9 @@ fn run_terminal_gui(opts: StartCommand, default_domain_name: Option<String>) ->
wezterm_client::remote_update::set_keep_sessions_on_update(
crate::native_settings::remote_update_keeps_sessions(),
);
+ wezterm_client::domain::set_local_session_host_replaced_sink(
+ crate::local_sessions::on_host_replaced,
+ );
let config = config::configuration();
let need_builder = !opts.prog.is_empty() || opts.cwd.is_some();
diff --git a/wezterm-gui/src/native_settings.rs b/wezterm-gui/src/native_settings.rs
index 13b9b212..3892d8ec 100644
--- a/wezterm-gui/src/native_settings.rs
+++ b/wezterm-gui/src/native_settings.rs
@@ -365,6 +365,10 @@ pub(crate) struct NativeWorkspaceSettings {
/// Updating a remote mux server hands its sessions to the new version
/// instead of stopping it; off, the update asks whether to stop it.
pub(crate) remote_update_keeps_sessions: bool,
+ /// Local terminals run in a background mux server (the default unix
+ /// domain) instead of inside the GUI process, so they survive the GUI
+ /// quitting, crashing or updating. Read once at launch.
+ pub(crate) local_sessions_via_mux: bool,
}
impl Default for NativeWorkspaceSettings {
@@ -375,6 +379,7 @@ impl Default for NativeWorkspaceSettings {
remote_drop_destination: String::new(),
notification_sounds_enabled: true,
remote_update_keeps_sessions: true,
+ local_sessions_via_mux: false,
}
}
}
@@ -916,6 +921,10 @@ pub(crate) fn remote_update_keeps_sessions() -> bool {
load().workspaces.remote_update_keeps_sessions
}
+pub(crate) fn local_sessions_via_mux() -> bool {
+ load().workspaces.local_sessions_via_mux
+}
+
pub(crate) fn bottom_quote_interval_minutes(settings: &ThinkTermNativeSettings) -> u32 {
settings
.terminal
diff --git a/wezterm-gui/src/settings_window.rs b/wezterm-gui/src/settings_window.rs
index b113b685..8aba3bb3 100644
--- a/wezterm-gui/src/settings_window.rs
+++ b/wezterm-gui/src/settings_window.rs
@@ -722,6 +722,7 @@ enum SettingsAction {
ToggleMainWindowFrameRestore,
ToggleNotificationSounds,
ToggleRemoteUpdateKeepsSessions,
+ ToggleLocalSessionsViaMux,
/// The ⓘ after a label; hovering it shows the text under this i18n key.
Hint(&'static str),
/// Turn one right-sidebar panel on or off.
@@ -3595,6 +3596,26 @@ impl SettingsWindow {
}
}
}
+ SettingsAction::ToggleLocalSessionsViaMux => {
+ self.ui.open_dropdown = None;
+ let enabled = !self.native_settings.workspaces.local_sessions_via_mux;
+ self.native_settings.workspaces.local_sessions_via_mux = enabled;
+ match crate::native_settings::save(&self.native_settings) {
+ Ok(()) => {
+ self.status = crate::i18n::tr(if enabled {
+ "settings-status-local-sessions-via-mux-on"
+ } else {
+ "settings-status-local-sessions-via-mux-off"
+ });
+ }
+ Err(err) => {
+ self.status = settings_tr(
+ "settings-status-local-sessions-via-mux-error",
+ &[("error", format!("{err:#}"))],
+ );
+ }
+ }
+ }
SettingsAction::ToggleMainRendererMenu => {
self.ui.open_dropdown =
if self.ui.open_dropdown == Some(SettingsDropdown::MainRenderer) {
@@ -5187,9 +5208,18 @@ impl SettingsWindow {
let row_count = 8;
let (card_y, first_row_y) = self.settings_card_geometry(section_y, row_count);
let card_height = self.settings_card_height(row_count);
+ // One more card under the rows, where the platform can run local
+ // sessions in a server.
+ let sessions_card = crate::local_sessions::supported().then(|| {
+ let y = card_y + card_height + self.settings_section_card_gap();
+ (y, self.compact_card_height(1))
+ });
+ let content_bottom = sessions_card
+ .map(|(y, height)| y + height)
+ .unwrap_or(card_y + card_height);
self.ui.content_scroll.set_extents(
self.content_viewport_extent(),
- self.settings_content_extent(card_y + scroll + card_height),
+ self.settings_content_extent(content_bottom + scroll),
);
let source = Self::config_source_summary();
let native_path = Self::native_settings_path();
@@ -5274,6 +5304,20 @@ impl SettingsWindow {
SettingsAction::QuitApplication,
true,
)?;
+ if let Some((sessions_card_y, sessions_card_height)) = sessions_card {
+ self.paint_group_card(layers, card_x, sessions_card_y, max_width, sessions_card_height)?;
+ self.paint_toggle_setting_row_with_hint(
+ layers,
+ row_x,
+ sessions_card_y + self.ui_px(12.0),
+ row_width,
+ self.compact_row_step(),
+ &crate::i18n::tr("settings-local-sessions-via-mux"),
+ "settings-local-sessions-via-mux-description",
+ self.native_settings.workspaces.local_sessions_via_mux,
+ SettingsAction::ToggleLocalSessionsViaMux,
+ )?;
+ }
Ok(())
}
diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rs
index 41dec12b..be120f0d 100644
--- a/wezterm-gui/src/termwindow/mod.rs
+++ b/wezterm-gui/src/termwindow/mod.rs
@@ -2780,15 +2780,22 @@ impl TermWindow {
return false;
};
+ // The local session host is not a remote to preserve: closing one
+ // of its windows ends the terminals in it, as it does in process.
+ let is_remote_client_domain = |domain: &Arc<dyn mux::domain::Domain>| {
+ domain
+ .downcast_ref::<ClientDomain>()
+ .is_some_and(|client| !client.is_local_session_host())
+ };
let origin_client_domain = origin_domain
.and_then(|domain_id| mux.get_domain(domain_id))
- .filter(|domain| domain.downcast_ref::<ClientDomain>().is_some())
+ .filter(is_remote_client_domain)
.map(|domain| domain.domain_id());
let active_space_domain =
crate::workspace_threads::client_domain_for_space(&self.active_space_id)
.and_then(|domain_name| mux.get_domain_by_name(&domain_name))
- .filter(|domain| domain.downcast_ref::<ClientDomain>().is_some())
+ .filter(is_remote_client_domain)
.map(|domain| domain.domain_id());
preserve_mux_window_on_gui_close(
@@ -4786,6 +4793,11 @@ impl TermWindow {
}
}
+ pub(crate) fn active_space_id(&self) -> &str {
+ &self.active_space_id
+ }
+
+
/// The mux window this GUI window displayed is gone (its last pane
/// exited, e.g. `exit` in a thread's only shell). Fall back to another
/// thread of the Space — or a fresh one — instead of dying with it,
@@ -8933,7 +8945,11 @@ impl TermWindow {
}
DetachDomain(domain) => {
let domain = Mux::get().resolve_spawn_tab_domain(Some(pane.pane_id()), domain)?;
- domain.detach()?;
+ if domain.detachable() {
+ domain.detach()?;
+ } else {
+ log::warn!("domain {} cannot be detached", domain.domain_name());
+ }
}
AttachDomain(domain) => {
let window = self.mux_window_id;
diff --git a/wezterm-gui/src/termwindow/mouseevent.rs b/wezterm-gui/src/termwindow/mouseevent.rs
index 6ccb22ba..4b309027 100644
--- a/wezterm-gui/src/termwindow/mouseevent.rs
+++ b/wezterm-gui/src/termwindow/mouseevent.rs
@@ -7638,7 +7638,7 @@ impl super::TermWindow {
if event.kind == WMEK::Press(MousePress::Left) {
self.spawn_command(
&SpawnCommand {
- domain: SpawnTabDomain::DomainName("local".to_string()),
+ domain: crate::local_sessions::local_spawn_domain(),
..SpawnCommand::default()
},
crate::spawn::SpawnWhere::NewTab,
diff --git a/wezterm-gui/src/termwindow/resize.rs b/wezterm-gui/src/termwindow/resize.rs
index 26c0b114..3d212928 100644
--- a/wezterm-gui/src/termwindow/resize.rs
+++ b/wezterm-gui/src/termwindow/resize.rs
@@ -309,7 +309,7 @@ impl super::TermWindow {
Some(Mux::get().current_identity_owns_frontend_lease(tab.tab_id()))
}
- fn tab_owns_frontend_viewport(&self, tab: &Arc<mux::tab::Tab>) -> bool {
+ pub(crate) fn tab_owns_frontend_viewport(&self, tab: &Arc<mux::tab::Tab>) -> bool {
self.tab_frontend_viewport_ownership(tab) == Some(true)
}
@@ -1480,6 +1480,10 @@ impl super::TermWindow {
}
let ownership = self.tab_frontend_viewport_ownership(&tab);
+ // The local session host has one screen, this one. A tab it does
+ // not own yet (a lease left by a previous run of this GUI, or a tab
+ // restored before anything was painted) is claimed the way a click
+ // on the terminal claims it, so the same full sync follows.
let previewing = matches!(
self.frontend_geometry_phases.get(&tab_id),
Some(super::FrontendGeometryPhase::Previewing { .. })
diff --git a/wezterm-gui/src/workspace_threads.rs b/wezterm-gui/src/workspace_threads.rs
index f16581fc..608a28b8 100644
--- a/wezterm-gui/src/workspace_threads.rs
+++ b/wezterm-gui/src/workspace_threads.rs
@@ -2807,9 +2807,10 @@ pub fn snapshot_active_space_thread_layout_with_font_scales<F>(
// the tag says; the tag is still honoured so tmux keeps its behaviour.
let space_is_remote = client_domain_for_space(space_id).is_some();
if space_is_remote
- || Mux::get()
- .get_window(window_id)
- .map_or(false, |w| w.origin_domain().is_some())
+ || Mux::get().get_window(window_id).map_or(false, |w| {
+ w.origin_domain()
+ .is_some_and(|id| !crate::local_sessions::is_host_domain_id(id))
+ })
{
let mut scales: HashMap<PaneId, f64> = HashMap::new();
let mut remote_panes = 0usize;
@@ -2895,8 +2896,11 @@ pub(crate) async fn materialize_thread(
// resync below, the opaque terminal surface can perform the real claim.
if let Some((_project_id, thread_id)) = parse_thread_workspace_name(&workspace_name) {
if let Ok(domain) = mux.resolve_spawn_tab_domain(None, &default_domain) {
- if let Some(client_domain) =
- domain.downcast_ref::<wezterm_client::domain::ClientDomain>()
+ // Not the local session host: its threads are this machine's,
+ // spawned and laid out from the local store below.
+ if let Some(client_domain) = domain
+ .downcast_ref::<wezterm_client::domain::ClientDomain>()
+ .filter(|client| !client.is_local_session_host())
{
let response = client_domain
.ensure_thinkterm_thread(Some(thread_id), size)
@@ -2952,6 +2956,9 @@ pub(crate) async fn materialize_thread(
domain
.downcast_ref::<mux::domain::LocalDomain>()
.is_some_and(mux::domain::LocalDomain::is_plain_local)
+ || domain
+ .downcast_ref::<wezterm_client::domain::ClientDomain>()
+ .is_some_and(|client| client.is_local_session_host())
}))
})
.await
@@ -8029,7 +8036,16 @@ fn collect_terminal_spec<F>(
// would record its name and every later materialize of the Thread
// would fail; leave it unset so restore falls back instead.
.filter(|domain| domain.spawnable())
- .map(|domain| domain.domain_name().to_string());
+ // A terminal in the local session host is a local terminal:
+ // recorded as `local`, it restores wherever local terminals run
+ // when the layout is next used (local_sessions::alias_recorded_domain).
+ .map(|domain| {
+ if crate::local_sessions::is_host_domain_id(domain.domain_id()) {
+ "local".to_string()
+ } else {
+ domain.domain_name().to_string()
+ }
+ });
terminal_specs.push(TerminalSpecEntry {
pane_id: entry.pane_id,
spec: TerminalSpawnSpec {
@@ -8071,10 +8087,12 @@ fn spawn_domain_for_entry(
terminal_specs: &HashMap<PaneId, TerminalSpawnSpec>,
default_if_missing: bool,
) -> SpawnTabDomain {
+ let recorded = terminal_specs
+ .get(&entry.pane_id)
+ .and_then(|spec| spec.domain.as_deref());
+ let aliased = recorded.and_then(crate::local_sessions::alias_recorded_domain);
spawn_domain_for_recorded_name(
- terminal_specs
- .get(&entry.pane_id)
- .and_then(|spec| spec.domain.as_deref()),
+ aliased.as_deref().or(recorded),
|name| {
mux.get_domain_by_name(name)
.map(|domain| domain.spawnable())
@@ -8418,7 +8436,7 @@ pub fn client_domain_for_space(space_id: &str) -> Option<String> {
/// Parse a thread workspace name (`thinkterm:<project-id>:<thread-id>`,
/// optionally with a `:<remote-workspace>` suffix) back into its identity.
/// Thread ids never contain `:`, project ids may (`::space::`).
-fn parse_thread_workspace_name(workspace: &str) -> Option<(String, String)> {
+pub(crate) fn parse_thread_workspace_name(workspace: &str) -> Option<(String, String)> {
let rest = workspace.strip_prefix("thinkterm:")?;
let idx = rest.find(":thread-")?;
let project_id = &rest[..idx];