A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.
Rust agentagent-orchestrationaiai-agentsclaude-codecodexcoding-agentlinuxmacosmultiplayermultiplexerrustterminalterminal-emulatorterminal-multiplexertmuxtuiweztermwindows
wezterm-gui: one window at launch, and a session server that stops with the setting
RoversX96e6fdbdaf75
diff --git a/wezterm-gui/src/frontend.rs b/wezterm-gui/src/frontend.rsindex c0f31174..238808c8 100644--- a/wezterm-gui/src/frontend.rs+++ b/wezterm-gui/src/frontend.rs@@ -12,7 +12,7 @@ use mux::tab::TabId;use mux::window::WindowId as MuxWindowId;use mux::{Mux, MuxNotification};use promise::{Future, Promise};-use std::cell::RefCell;+use std::cell::{Cell, RefCell};use std::collections::{BTreeMap, HashSet};use std::rc::Rc;use std::sync::Arc;@@ -27,14 +27,20 @@ use wezterm_toast_notification::*;/// threads of the local Spaces, opened by their Space window through the/// thread store (making one here would open every live thread of every/// Space), and only a startup window in a plain workspace opens on its own.+/// `no_gui_window_yet`: this process shows nothing so far. A host window+/// outside a thread workspace is the startup tab, whose window restores+/// the thread; once one window is up, further ones there are leftovers+/// the server accumulated (a startup tab whose close never landed, a+/// `cli spawn --new-window`) and stay in the background.fn should_spawn_reconciled_gui_window(is_domain_owned: bool,is_host: bool,workspace: &str,+ no_gui_window_yet: bool,) -> bool {let thread_workspace = crate::workspace_threads::is_thread_workspace_name(workspace);if is_host {- return !thread_workspace;+ return !thread_workspace && no_gui_window_yet;}!is_domain_owned || thread_workspace}@@ -179,6 +185,17 @@ pub struct GuiFrontEnd {switching_workspaces: RefCell<usize>,spawned_mux_window: RefCell<HashSet<MuxWindowId>>,known_windows: RefCell<BTreeMap<Window, MuxWindowId>>,+ /// Whether this process has shown a GUI window yet. AppKit asks a+ /// freshly launched app with no windows to "open an untitled file";+ /// before the first window exists that request is the launch itself,+ /// which startup already answers with a window of its own.+ any_window_recorded: Cell<bool>,+ /// Startup has run its course (the first window is up, or startup+ /// produced none): a new-window request is honoured from here on.+ startup_settled: Cell<bool>,+ /// A new-window request arrived during startup and was held; it is+ /// answered if startup ends with no window at all.+ new_window_request_held: Cell<bool>,/// Stable native-window lookup used across replacement mux runtimes./// Unlike `known_windows`, this is keyed by the frontend-owned slot and/// therefore remains valid while remote WindowIds are being replaced.@@ -219,6 +236,9 @@ impl GuiFrontEnd {switching_workspaces: RefCell::new(0),spawned_mux_window: RefCell::new(HashSet::new()),known_windows: RefCell::new(BTreeMap::new()),+ any_window_recorded: Cell::new(false),+ startup_settled: Cell::new(false),+ new_window_request_held: Cell::new(false),recovery_windows: RefCell::new(BTreeMap::new()),detach_when_windowless: std::cell::Cell::new(false),client_id: client_id.clone(),@@ -507,7 +527,21 @@ impl GuiFrontEnd {Connection::get().unwrap().terminate_message_loop();}KeyAssignment::SpawnWindow => {- front_end().spawn_space_window();+ // macOS sends this at launch for an app that has no+ // window yet. In process the startup window is there+ // before the request arrives; with the local session+ // host it comes after a round trip, and honouring the+ // request opened a second Space window beside it.+ let front_end = front_end();+ if !front_end.any_window_recorded.get() && !front_end.startup_settled.get()+ {+ log::debug!(+ "holding the launch-time new-window request: startup opens the first window"+ );+ front_end.new_window_request_held.set(true);+ return;+ }+ front_end.spawn_space_window();}KeyAssignment::SpawnTab(spawn_where) => {spawn_command(@@ -650,7 +684,14 @@ impl GuiFrontEnd {// giving them a GUI window creates the stray "local Space with// a remote terminal" window and tangles its lifecycle with the// real thread window.- if !should_spawn_reconciled_gui_window(is_domain_owned, is_host, &window_workspace) {+ let no_gui_window_yet = front_end().known_windows.borrow().is_empty()+ && front_end().spawned_mux_window.borrow().is_empty();+ if !should_spawn_reconciled_gui_window(+ is_domain_owned,+ is_host,+ &window_workspace,+ no_gui_window_yet,+ ) {log::debug!("reconcile: leaving background domain window {} in workspace {:?} hidden",mux_window_id,@@ -692,6 +733,25 @@ impl GuiFrontEnd {future}+ /// Startup's spawn has returned; its window, if any, follows within+ /// moments. Once those have passed, a new-window request held during+ /// startup is answered if startup showed nothing, and later requests+ /// are answered as they come.+ pub(crate) fn startup_settled_soon(&self) {+ promise::spawn::spawn(async move {+ smol::Timer::after(std::time::Duration::from_secs(2)).await;+ let front_end = front_end();+ front_end.startup_settled.set(true);+ if front_end.new_window_request_held.replace(false)+ && !front_end.any_window_recorded.get()+ {+ log::info!("startup opened no window; answering the held new-window request");+ front_end.spawn_space_window();+ }+ })+ .detach();+ }+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@@ -834,9 +894,7 @@ impl GuiFrontEnd {}}- mux.iter_windows_in_workspace(&plan.workspace_name)- .into_iter()- .next()+ crate::workspace_threads::window_to_show_in_workspace(&plan.workspace_name).map(|window_id| (window_id, created_mux_window)).ok_or_else(|| anyhow!("Space workspace {} has no mux window", plan.workspace_name))}@@ -872,6 +930,7 @@ impl GuiFrontEnd {) {// A GUI window exists again: any pending last-window cleanup is moot.self.detach_when_windowless.set(false);+ self.any_window_recorded.set(true);// Mark this mux window as having a GUI window so the additive reconcile// never re-creates a window for it (e.g. after the user closes it while// its mux window keeps running in the background).@@ -1117,53 +1176,32 @@ mod tests {#[test]fn reconcile_keeps_local_windows_visible() {- assert!(should_spawn_reconciled_gui_window(false, false, "default"));- assert!(should_spawn_reconciled_gui_window(- false,- false,- "user-created-workspace"- ));+ assert!(should_spawn_reconciled_gui_window(false, false, "default", true));+ assert!(should_spawn_reconciled_gui_window(false, false, "user-created-workspace", true));}#[test]fn reconcile_hides_background_domain_windows() {- assert!(!should_spawn_reconciled_gui_window(true, false, "default"));- assert!(!should_spawn_reconciled_gui_window(- true,- false,- "unmanaged-remote-workspace"- ));- assert!(!should_spawn_reconciled_gui_window(- true,- false,- "thinkterm:not-a-thread-workspace"- ));+ assert!(!should_spawn_reconciled_gui_window(true, false, "default", true));+ assert!(!should_spawn_reconciled_gui_window(true, false, "unmanaged-remote-workspace", true));+ assert!(!should_spawn_reconciled_gui_window(true, false, "thinkterm:not-a-thread-workspace", true));}#[test]fn reconcile_shows_thinkterm_domain_thread_windows() {- assert!(should_spawn_reconciled_gui_window(- true,- false,- "thinkterm:muxdomain-host::space::space-1:thread-2"- ));- assert!(should_spawn_reconciled_gui_window(- true,- false,- "thinkterm:muxdomain-host::space::space-1:thread-2:remote-default"- ));+ assert!(should_spawn_reconciled_gui_window(true, false, "thinkterm:muxdomain-host::space::space-1:thread-2", true));+ assert!(should_spawn_reconciled_gui_window(true, false, "thinkterm:muxdomain-host::space::space-1:thread-2:remote-default", true));}#[test]fn reconcile_opens_only_the_hosts_startup_window() {// The host's thread windows belong to the local Spaces and are// opened through the thread store, never one per live thread.- assert!(should_spawn_reconciled_gui_window(false, true, "default"));- assert!(!should_spawn_reconciled_gui_window(- false,- true,- "thinkterm:project-1:thread-2"- ));+ assert!(should_spawn_reconciled_gui_window(false, true, "default", true));+ // A second host window in the startup workspace stays hidden once+ // a window is up: it is a leftover, not a window to show.+ assert!(!should_spawn_reconciled_gui_window(false, true, "default", false));+ assert!(!should_spawn_reconciled_gui_window(false, true, "thinkterm:project-1:thread-2", true));}#[test]diff --git a/wezterm-gui/src/local_sessions.rs b/wezterm-gui/src/local_sessions.rsindex 0a4b65b7..dad37e6f 100644--- a/wezterm-gui/src/local_sessions.rs+++ b/wezterm-gui/src/local_sessions.rs@@ -93,6 +93,103 @@ pub(crate) fn install(mux: &Mux, config: &ConfigHandle) -> Option<String> {name}+/// The file that says the server at the default socket is the one this+/// setting runs: written when a launch attaches to it as the host, removed+/// when the server is stopped for the setting. A server the user started+/// by hand (`thinkterm-mux-server --daemonize`, `thinkterm connect unix`)+/// never gets it.+fn managed_marker() -> std::path::PathBuf {+ config::RUNTIME_DIR.join(config::runtime_file_name("local-session-host"))+}++/// This launch attached to the session server as the host.+pub(crate) fn note_host_attached() {+ if let Err(err) = std::fs::write(managed_marker(), b"") {+ log::warn!(+ "local sessions: could not record the session server as managed at {}: {err:#}",+ managed_marker().display()+ );+ }+}++/// With the setting off, the session server an earlier launch ran for it+/// is stopped: "off" means no terminals in the background, and a server+/// nothing shows would otherwise live on until the next reboot. Only the+/// server this setting started is stopped (the marker says so), and only+/// while it holds the pid file's lock, so a server the user runs for their+/// own purposes, a stale file or someone else's process is left alone.+/// 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;+ }+ let marker = managed_marker();+ if !marker.exists() {+ return;+ }+ let Some(unix) = candidate(config) else {+ return;+ };+ let socket = unix.socket_path();+ // The pid file is one per profile, the socket path is per domain: a+ // domain on a custom path may not be the server the pid file names.+ if socket != config::RUNTIME_DIR.join(config::runtime_file_name("sock")) {+ return;+ }+ if !wezterm_mux_server_impl::local::someone_listens(&socket) {+ // Gone already; nothing is managed any more.+ std::fs::remove_file(&marker).ok();+ return;+ }+ let pid_file = config.daemon_options.pid_file();+ let Some(pid) = pid_of_server_holding(&pid_file) else {+ log::warn!(+ "local sessions: the setting is off but a server answers at {}; nothing holds {}, \+ so it is left running",+ socket.display(),+ pid_file.display()+ );+ return;+ };+ log::info!(+ "local sessions: the setting is off; stopping the session server (pid {pid}) at {}",+ socket.display()+ );+ if unsafe { libc::kill(pid as libc::pid_t, libc::SIGTERM) } != 0 {+ log::warn!(+ "local sessions: could not stop the session server (pid {pid}): {}",+ std::io::Error::last_os_error()+ );+ return;+ }+ std::fs::remove_file(&marker).ok();+}++#[cfg(not(unix))]+pub(crate) fn stop_background_server_when_off(_config: &ConfigHandle) {}++/// The pid written in `pid_file`, when a running server holds its lock.+#[cfg(unix)]+fn pid_of_server_holding(pid_file: &std::path::Path) -> Option<u32> {+ use std::os::unix::io::AsRawFd as _;+ let file = std::fs::File::open(pid_file).ok()?;+ let locked_by_someone =+ unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } != 0;+ if !locked_by_someone {+ // We hold it now: no server does. The lock goes with the file.+ return None;+ }+ std::fs::read_to_string(pid_file)+ .ok()?+ .trim()+ .parse::<u32>()+ .ok()+ .filter(|pid| *pid > 1)+}+/// 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() {@@ -195,10 +292,12 @@ pub(crate) fn on_host_replaced(domain_id: mux::domain::DomainId) {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.+ // thread store and the thread would then "live" there) into a+ // workspace of its own -- only this window, not the others of+ // its workspace, which may hold live panes of other domains --+ // 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 parked one.let Some(old_workspace) = mux.get_window(window_id).map(|window| window.get_workspace().to_string())@@ -208,8 +307,8 @@ pub(crate) fn on_host_replaced(domain_id: mux::domain::DomainId) {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);+ let dead_workspace = format!("dead-session:{window_id}:{old_workspace}");+ mux.move_window_to_workspace_quietly(window_id, &dead_workspace);dead_workspace};if let Some(window) = mux.get_window(window_id) {@@ -290,6 +389,26 @@ mod tests {use super::{alias_for, candidate_in};use config::UnixDomain;+ /// A pid file is only believed while a process holds its lock.+ #[cfg(unix)]+ #[test]+ fn a_pid_file_counts_only_while_locked() {+ use std::io::Write as _;+ use std::os::unix::io::AsRawFd as _;+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("pid");+ let mut holder = std::fs::File::create(&path).unwrap();+ writeln!(holder, "4242").unwrap();+ assert_eq!(super::pid_of_server_holding(&path), None, "nobody holds the lock");+ assert_eq!(+ unsafe { libc::flock(holder.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },+ 0+ );+ assert_eq!(super::pid_of_server_holding(&path), Some(4242));+ drop(holder);+ assert_eq!(super::pid_of_server_holding(&path), None);+ }+fn unix(name: &str, proxy: bool) -> UnixDomain {UnixDomain {name: name.into(),diff --git a/wezterm-gui/src/main.rs b/wezterm-gui/src/main.rsindex ac7847eb..d22b7ed2 100644--- a/wezterm-gui/src/main.rs+++ b/wezterm-gui/src/main.rs@@ -370,10 +370,11 @@ async fn spawn_tab_in_domain_if_mux_is_empty(// whose restore then adopts the live thread and cleans the tab up -- as// it does in process.let mut workspace = workspace;- if let Some(client) = domain.downcast_ref::<ClientDomain>() {- if client.is_local_session_host() && workspace.is_none() {- workspace = Some(mux.active_workspace());- }+ let is_host = domain+ .downcast_ref::<ClientDomain>()+ .is_some_and(|client| client.is_local_session_host());+ if is_host && workspace.is_none() {+ workspace = Some(mux.active_workspace());}if !is_connecting {@@ -382,21 +383,27 @@ async fn spawn_tab_in_domain_if_mux_is_empty(}}- let window_id = {- // Force the builder to notify the frontend early,- // so that the attach await below doesn't block it.- // This has the consequence of creating the window- // at the initial size instead of populating it- // from the size specified in the remote mux.- // We use the TabAddedToWindow mux notification- // to detect and adjust the size later on.- let position = None;- let builder = mux.new_empty_window_for_domain(- workspace.clone(),- position,- client_domain_origin(&domain),- );- *builder+ let position = None;+ let builder = mux.new_empty_window_for_domain(+ workspace.clone(),+ position,+ client_domain_origin(&domain),+ );+ let window_id = *builder;+ // Dropping the builder tells the frontend about the window. For a domain+ // that still has to attach, that happens now, so the attach await below+ // does not hold the window back (it opens at the initial size and the+ // TabAddedToWindow notification adjusts it later). The host is attached+ // already, and its spawn is a round trip: shown empty, the window is+ // adopted by the thread restore and cleaned up before the shell lands,+ // and the shell then makes a window of its own -- a second one on+ // screen. So the host's window is announced once the tab is in it, the+ // order the in-process spawn has.+ let held_window = if is_host {+ Some(builder)+ } else {+ drop(builder);+ None};let config = config::configuration();@@ -423,14 +430,16 @@ async fn spawn_tab_in_domain_if_mux_is_empty(});let dpi = config.dpi.unwrap_or_else(|| ::window::default_dpi());- let _tab = domain+ let spawned = domain.spawn(config.initial_size(dpi as u32, Some(cell_pixel_dims(&config, dpi)?)),cmd,None,window_id,)- .await?;+ .await;+ drop(held_window);+ spawned?;trigger_and_log_gui_attached(MuxDomain(domain.domain_id())).await;Ok(())}@@ -779,6 +788,13 @@ async fn connect_to_auto_connect_domains() -> anyhow::Result<()> {// 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 {+ // Only a server this process started (or took over) is the+ // setting's to stop later; one the user runs is left alone.+ Ok(()) if client.is_local_session_host()+ && wezterm_client::local_update::local_session_host_started_by_us() =>+ {+ crate::local_sessions::note_host_attached();+ }Ok(()) => {}// The session server of this machine must be there before the// first window spawns into it; without it this launch runs its@@ -893,6 +909,10 @@ async fn async_run_terminal_gui(log::warn!("{:#}", err);}+ // This process is the GUI now (a launch that handed its command to a+ // running GUI returned before this), so a server the setting no longer+ // wants can go.+ crate::local_sessions::stop_background_server_when_off(&config::configuration());if !opts.no_auto_connect {connect_to_auto_connect_domains().await?;}@@ -979,7 +999,10 @@ async fn async_run_terminal_gui(}}}- spawn_tab_in_domain_if_mux_is_empty(cmd, is_connecting, domain, opts.workspace).await+ let started =+ spawn_tab_in_domain_if_mux_is_empty(cmd, is_connecting, domain, opts.workspace).await;+ crate::frontend::front_end().startup_settled_soon();+ started}#[derive(Debug)]diff --git a/wezterm-gui/src/ssh_hosts.rs b/wezterm-gui/src/ssh_hosts.rsindex 24f8ddc4..6722c2ea 100644--- a/wezterm-gui/src/ssh_hosts.rs+++ b/wezterm-gui/src/ssh_hosts.rs@@ -329,7 +329,7 @@ pub fn build_mosh_fallback_spawn(spec: &SshHostSpec) -> SpawnCommand {SpawnCommand {label: Some(format!("mosh {}", spec.label)),args: Some(build_mosh_args(spec)),- domain: SpawnTabDomain::DomainName("local".to_string()),+ domain: crate::local_sessions::local_spawn_domain(),..Default::default()}}@@ -366,7 +366,7 @@ fn build_mosh_client_spawn(label: Some(format!("mosh {}", spec.label)),args: Some(vec!["mosh-client".to_string(), host, port.to_string()]),set_environment_variables: env,- domain: SpawnTabDomain::DomainName("local".to_string()),+ domain: crate::local_sessions::local_spawn_domain(),..Default::default()}}