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.

Route `wezterm connect` through the Space system; fix reconcile hijack

RoversX8373eeba5b18
diff --git a/mux/src/lib.rs b/mux/src/lib.rs
index f3bf4a1a..138b20cb 100644
--- a/mux/src/lib.rs
+++ b/mux/src/lib.rs
@@ -989,7 +989,20 @@ impl Mux {
workspace: Option<String>,
position: Option<GuiPosition>,
) -> MuxWindowBuilder {
- let window = Window::new(workspace, position);
+ self.new_empty_window_for_domain(workspace, position, None)
+ }
+
+ /// Like `new_empty_window`, but tags the window with the domain that is
+ /// creating it. The tag is set before the window becomes observable via
+ /// mux notifications, so the GUI can reliably distinguish domain-owned
+ /// windows (remote mux windows, tmux) from user-initiated ones.
+ pub fn new_empty_window_for_domain(
+ &self,
+ workspace: Option<String>,
+ position: Option<GuiPosition>,
+ origin_domain: Option<DomainId>,
+ ) -> MuxWindowBuilder {
+ let window = Window::new(workspace, position, origin_domain);
let window_id = window.window_id();
self.windows.write().insert(window_id, window);
MuxWindowBuilder {
diff --git a/mux/src/tmux.rs b/mux/src/tmux.rs
index 1894553b..7e221080 100644
--- a/mux/src/tmux.rs
+++ b/mux/src/tmux.rs
@@ -283,9 +283,10 @@ impl TmuxDomainState {
notified: false,
}
} else {
- mux.new_empty_window(
+ mux.new_empty_window_for_domain(
None, /* TODO: pass session here */
None, /* position */
+ Some(self.domain_id),
)
};
diff --git a/mux/src/window.rs b/mux/src/window.rs
index 54a4a3a0..141b8536 100644
--- a/mux/src/window.rs
+++ b/mux/src/window.rs
@@ -1,3 +1,4 @@
+use crate::domain::DomainId;
use crate::pane::CloseReason;
use crate::{Mux, MuxNotification, Tab, TabId};
use config::GuiPosition;
@@ -17,10 +18,19 @@ pub struct Window {
workspace: String,
title: String,
initial_position: Option<GuiPosition>,
+ /// The domain that created this window on its own initiative (e.g. a
+ /// ClientDomain materializing a remote mux window, or tmux). Such windows
+ /// are owned by their domain: the GUI must not adopt them into saved
+ /// workspace threads or snapshot their layout locally.
+ origin_domain: Option<DomainId>,
}
impl Window {
- pub fn new(workspace: Option<String>, initial_position: Option<GuiPosition>) -> Self {
+ pub fn new(
+ workspace: Option<String>,
+ initial_position: Option<GuiPosition>,
+ origin_domain: Option<DomainId>,
+ ) -> Self {
Self {
id: WIN_ID.fetch_add(1, ::std::sync::atomic::Ordering::Relaxed),
tabs: vec![],
@@ -30,9 +40,14 @@ impl Window {
title: String::new(),
workspace: workspace.unwrap_or_else(|| Mux::get().active_workspace()),
initial_position,
+ origin_domain,
}
}
+ pub fn origin_domain(&self) -> Option<DomainId> {
+ self.origin_domain
+ }
+
pub fn get_initial_position(&self) -> &Option<GuiPosition> {
&self.initial_position
}
diff --git a/wezterm-client/src/domain.rs b/wezterm-client/src/domain.rs
index 835baaa5..3a847d9d 100644
--- a/wezterm-client/src/domain.rs
+++ b/wezterm-client/src/domain.rs
@@ -663,7 +663,11 @@ impl ClientDomain {
workspace
);
let position = None;
- let local_window_id = mux.new_empty_window(workspace.take(), position);
+ let local_window_id = mux.new_empty_window_for_domain(
+ workspace.take(),
+ position,
+ Some(inner.local_domain_id),
+ );
inner.record_remote_to_local_window_mapping(remote_window_id, *local_window_id);
mux.add_tab_to_window(&tab, *local_window_id)?;
}
diff --git a/wezterm-gui/src/frontend.rs b/wezterm-gui/src/frontend.rs
index 5afc928b..209db0e7 100644
--- a/wezterm-gui/src/frontend.rs
+++ b/wezterm-gui/src/frontend.rs
@@ -435,7 +435,20 @@ impl GuiFrontEnd {
.borrow_mut()
.insert(mux_window_id);
log::trace!("Creating TermWindow for mux_window_id={}", mux_window_id);
- if let Err(err) = TermWindow::new_window(mux_window_id).await {
+ // Domain-owned windows (remote mux windows, tmux) must not be
+ // adopted into a saved workspace thread: the restore would
+ // re-point the GUI window at a different mux window and orphan
+ // the one the domain just created (killing e.g. the in-window
+ // ConnectionUI mid-authentication).
+ let is_domain_owned = Mux::get()
+ .get_window(mux_window_id)
+ .map_or(false, |w| w.origin_domain().is_some());
+ let created = if is_domain_owned {
+ TermWindow::new_window_without_restore(mux_window_id).await
+ } else {
+ TermWindow::new_window(mux_window_id).await
+ };
+ if let Err(err) = created {
log::error!("Failed to create window: {:#}", err);
let mux = Mux::get();
mux.kill_window(mux_window_id);
@@ -557,6 +570,13 @@ impl GuiFrontEnd {
false
}
+ /// Pre-claim a mux window that the caller is about to create a GUI window
+ /// for explicitly (e.g. the `wezterm connect` flow), so that neither the
+ /// WindowCreated handler nor the additive reconcile spawns a duplicate.
+ pub fn claim_spawned_mux_window(&self, mux_window_id: MuxWindowId) {
+ self.spawned_mux_window.borrow_mut().insert(mux_window_id);
+ }
+
pub fn switch_workspace(&self, workspace: &str) {
let mux = Mux::get();
mux.set_active_workspace_for_client(&self.client_id, workspace);
diff --git a/wezterm-gui/src/main.rs b/wezterm-gui/src/main.rs
index dfee0ec7..fc8ff726 100644
--- a/wezterm-gui/src/main.rs
+++ b/wezterm-gui/src/main.rs
@@ -292,6 +292,15 @@ fn have_panes_in_domain_and_ws(domain: &Arc<dyn Domain>, workspace: &Option<Stri
}
}
+/// Returns the domain id to tag domain-owned mux windows with, when the
+/// domain is a ClientDomain (remote mux). Tagged windows are exempt from
+/// the frontend's saved-thread restore/adoption and local layout snapshots.
+fn client_domain_origin(domain: &Arc<dyn Domain>) -> Option<mux::domain::DomainId> {
+ domain
+ .downcast_ref::<ClientDomain>()
+ .map(|_| domain.domain_id())
+}
+
async fn spawn_tab_in_domain_if_mux_is_empty(
cmd: Option<CommandBuilder>,
is_connecting: bool,
@@ -317,7 +326,11 @@ async fn spawn_tab_in_domain_if_mux_is_empty(
// We use the TabAddedToWindow mux notification
// to detect and adjust the size later on.
let position = None;
- let builder = mux.new_empty_window(workspace.clone(), position);
+ let builder = mux.new_empty_window_for_domain(
+ workspace.clone(),
+ position,
+ client_domain_origin(&domain),
+ );
*builder
};
@@ -354,6 +367,132 @@ async fn spawn_tab_in_domain_if_mux_is_empty(
Ok(())
}
+/// `wezterm connect <domain>` routed through the ThinkTerm Space system:
+/// find-or-create the domain's dedicated Space; if already connected in this
+/// process, focus an existing window instead of duplicating; otherwise create
+/// the connect window with an explicit Space claim so the frontend's
+/// reconcile/restore can never hijack it away from the in-window ConnectionUI.
+async fn connect_domain_into_space(
+ cmd: Option<CommandBuilder>,
+ domain: Arc<dyn Domain>,
+) -> anyhow::Result<()> {
+ use mux::domain::DomainState;
+
+ let mux = Mux::get();
+ let domain_name = domain.domain_name().to_string();
+ let plan = workspace_threads::ensure_mux_domain_space(&domain_name);
+
+ // Already attached in this process: focus one of this domain's windows.
+ if domain.state() == DomainState::Attached {
+ for window_id in mux.iter_windows() {
+ let owned = mux
+ .get_window(window_id)
+ .map_or(false, |w| w.origin_domain() == Some(domain.domain_id()));
+ if !owned {
+ continue;
+ }
+ if let Some(gui_window) =
+ crate::frontend::front_end().gui_window_for_mux_window(window_id)
+ {
+ gui_window.window.focus();
+ return Ok(());
+ }
+ }
+ }
+
+ // Claim the Space for the window we are about to create. If another
+ // in-process window already occupies it, focus that window instead.
+ let space_owner_id = workspace_threads::next_space_owner_id();
+ if !workspace_threads::switch_window_space(space_owner_id, &plan.space_id) {
+ for window_id in mux.iter_windows_in_workspace(&plan.workspace_name) {
+ if let Some(gui_window) =
+ crate::frontend::front_end().gui_window_for_mux_window(window_id)
+ {
+ gui_window.window.focus();
+ return Ok(());
+ }
+ }
+ anyhow::bail!(
+ "Space for domain {domain_name} is occupied by another window; \
+ switch to it instead"
+ );
+ }
+
+ // Create the connect mux window in the default workspace (the remote's
+ // primary window folds into it only when workspace names match), and
+ // claim it before the builder drops so the WindowCreated notification
+ // can never race a reconcile-spawned duplicate.
+ let window_id = {
+ let builder = mux.new_empty_window_for_domain(None, None, Some(domain.domain_id()));
+ let id = *builder;
+ crate::frontend::front_end().claim_spawned_mux_window(id);
+ id
+ };
+
+ // Transiently bind the thread to the window's current workspace so the
+ // sidebar's workspace->project sync resolves to the mux project instead
+ // of manufacturing a spurious local Home project.
+ let initial_workspace = mux
+ .get_window(window_id)
+ .map(|w| w.get_workspace().to_string());
+ workspace_threads::bind_mux_domain_thread_workspace(&plan.thread_id, initial_workspace);
+
+ TermWindow::new_window_with_claimed_space(window_id, space_owner_id, plan.space_id.clone())
+ .await?;
+
+ let config = config::configuration();
+ config.update_ulimit()?;
+
+ // The ConnectionUI (auth prompts) appears as a tab inside this window.
+ if let Err(err) = domain.attach(Some(window_id)).await {
+ workspace_threads::bind_mux_domain_thread_workspace(&plan.thread_id, None);
+ return Err(err);
+ }
+
+ // Mirror spawn_tab_in_domain_if_mux_is_empty's empty-server handling.
+ let no_workspace_filter = None;
+ if !have_panes_in_domain_and_ws(&domain, &no_workspace_filter) {
+ let _config_subscription = config::subscribe_to_config_reload(move || {
+ promise::spawn::spawn_into_main_thread(async move {
+ if let Err(err) = update_mux_domains(&config::configuration()) {
+ log::error!("Error updating mux domains: {:#}", err);
+ }
+ })
+ .detach();
+ true
+ });
+
+ let dpi = config.dpi.unwrap_or_else(|| ::window::default_dpi());
+ let _tab = domain
+ .spawn(
+ config.initial_size(dpi as u32, Some(cell_pixel_dims(&config, dpi)?)),
+ cmd,
+ None,
+ window_id,
+ )
+ .await?;
+ }
+ trigger_and_log_gui_attached(MuxDomain(domain.domain_id())).await;
+
+ // Rename the window into the Space's canonical workspace. Order matters:
+ // bind the thread first so the WindowWorkspaceChanged-driven sync finds
+ // the binding and activates the mux project in the sidebar.
+ if mux.get_window(window_id).is_some() {
+ workspace_threads::bind_mux_domain_thread_workspace(
+ &plan.thread_id,
+ Some(plan.workspace_name.clone()),
+ );
+ if let Some(mut window) = mux.get_window_mut(window_id) {
+ window.set_workspace(&plan.workspace_name);
+ }
+ } else {
+ // The window died before we could populate it (e.g. empty server and
+ // the connui closed first); domain windows may still exist elsewhere.
+ workspace_threads::bind_mux_domain_thread_workspace(&plan.thread_id, None);
+ }
+ Ok(())
+}
+
async fn connect_to_auto_connect_domains() -> anyhow::Result<()> {
let mux = Mux::get();
let domains = mux.iter_domains();
@@ -479,7 +618,11 @@ async fn async_run_terminal_gui(
// so that the attach await below doesn't block it.
let workspace = None;
let position = None;
- let builder = mux.new_empty_window(workspace, position);
+ let builder = mux.new_empty_window_for_domain(
+ workspace,
+ position,
+ client_domain_origin(domain),
+ );
*builder
};
@@ -503,6 +646,15 @@ async fn async_run_terminal_gui(
trigger_and_log_gui_attached(MuxDomain(domain.domain_id())).await;
}
}
+ // `wezterm connect` to a mux client domain goes through the Space system:
+ // dedicated find-or-create Space, explicit window claim, no restore.
+ if is_connecting {
+ if let Some(domain) = &domain {
+ if domain.downcast_ref::<ClientDomain>().is_some() {
+ return connect_domain_into_space(cmd, Arc::clone(domain)).await;
+ }
+ }
+ }
spawn_tab_in_domain_if_mux_is_empty(cmd, is_connecting, domain, opts.workspace).await
}
diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rs
index b76410fe..8112baca 100644
--- a/wezterm-gui/src/termwindow/mod.rs
+++ b/wezterm-gui/src/termwindow/mod.rs
@@ -1309,6 +1309,14 @@ impl TermWindow {
Self::new_window_impl(mux_window_id, None, true).await
}
+ /// For domain-owned mux windows (remote mux windows arriving via a
+ /// ClientDomain, tmux): create the GUI window as-is, without restoring
+ /// a saved workspace thread. Restoring would adopt this window onto a
+ /// different mux window, orphaning/killing the one the domain created.
+ pub async fn new_window_without_restore(mux_window_id: MuxWindowId) -> anyhow::Result<()> {
+ Self::new_window_impl(mux_window_id, None, false).await
+ }
+
pub async fn new_window_with_claimed_space(
mux_window_id: MuxWindowId,
space_owner_id: u64,
diff --git a/wezterm-gui/src/termwindow/mouseevent.rs b/wezterm-gui/src/termwindow/mouseevent.rs
index 823507a6..b3e98284 100644
--- a/wezterm-gui/src/termwindow/mouseevent.rs
+++ b/wezterm-gui/src/termwindow/mouseevent.rs
@@ -3358,6 +3358,23 @@ impl super::TermWindow {
return;
}
+ // Mux-client-domain threads (`wezterm connect` Spaces) cannot be
+ // materialized locally: their content lives on the remote mux server.
+ // The live case was handled by the adopt branch above; when the
+ // workspace isn't live, spawning a local shell here would fight the
+ // remote's ownership, so refuse.
+ if let Some(domain_name) =
+ crate::workspace_threads::client_domain_name_for_project_id(&plan.project_id)
+ {
+ log::info!(
+ "thread {:?} belongs to mux domain {domain_name:?}; \
+ use `wezterm connect {domain_name}` to attach it",
+ plan.thread_id
+ );
+ context.invalidate();
+ return;
+ }
+
let workspace_name = plan.workspace_name.clone();
let remote_host_id =
crate::workspace_threads::remote_host_id_for_project_id(&plan.project_id).to_string();
diff --git a/wezterm-gui/src/workspace_threads.rs b/wezterm-gui/src/workspace_threads.rs
index 0fdd5801..1486c80d 100644
--- a/wezterm-gui/src/workspace_threads.rs
+++ b/wezterm-gui/src/workspace_threads.rs
@@ -49,6 +49,12 @@ pub struct Space {
pub active_project_id: Option<ProjectId>,
#[serde(default)]
pub is_default: bool,
+ /// When set, this Space is dedicated to a wezterm mux client domain
+ /// (`wezterm connect <name>`). Such Spaces are found-or-created by domain
+ /// name, are never claimed by startup/Dock windows, and never persist
+ /// layout locally (the remote mux server owns the layout truth).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub client_domain: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
@@ -986,6 +992,16 @@ pub fn snapshot_active_space_thread_layout_with_font_scales<F>(
return;
}
+ // Domain-owned windows (remote mux windows, tmux) must never be
+ // snapshotted locally: the remote mux server owns the layout truth,
+ // and a local snapshot would fight it on restore.
+ if Mux::get()
+ .get_window(window_id)
+ .map_or(false, |w| w.origin_domain().is_some())
+ {
+ return;
+ }
+
let Some(snapshot) = snapshot_window_layout(window_id, &pane_font_scale) else {
return;
};
@@ -1296,6 +1312,7 @@ impl WorkspaceThreadStore {
name: DEFAULT_SPACE_NAME.to_string(),
active_project_id: self.active_project_id.clone(),
is_default: true,
+ client_domain: None,
});
changed = true;
}
@@ -1379,12 +1396,21 @@ impl WorkspaceThreadStore {
}
fn create_space_record(&mut self, name: String) -> SpaceId {
+ self.create_space_record_for_domain(name, None)
+ }
+
+ fn create_space_record_for_domain(
+ &mut self,
+ name: String,
+ client_domain: Option<String>,
+ ) -> SpaceId {
let id = new_id("space");
self.spaces.push(Space {
id: id.clone(),
name,
active_project_id: None,
is_default: false,
+ client_domain,
});
id
}
@@ -1393,13 +1419,20 @@ impl WorkspaceThreadStore {
&mut self,
occupied: &std::collections::HashSet<SpaceId>,
) -> SpaceId {
+ // Mux-domain Spaces belong to `wezterm connect`; startup and Dock
+ // "New Window" must never claim them (they would materialize a local
+ // shell into a remote-owned workspace).
self.last_active_space_id
.clone()
- .filter(|space_id| self.has_space(space_id) && !occupied.contains(space_id))
+ .filter(|space_id| {
+ self.has_space(space_id)
+ && !occupied.contains(space_id)
+ && !self.is_client_domain_space(space_id)
+ })
.or_else(|| {
self.spaces
.iter()
- .find(|space| !occupied.contains(&space.id))
+ .find(|space| !occupied.contains(&space.id) && space.client_domain.is_none())
.map(|space| space.id.clone())
})
.unwrap_or_else(|| {
@@ -1408,6 +1441,12 @@ impl WorkspaceThreadStore {
})
}
+ fn is_client_domain_space(&self, space_id: &str) -> bool {
+ self.spaces
+ .iter()
+ .any(|space| space.id == space_id && space.client_domain.is_some())
+ }
+
fn rename_space(&mut self, space_id: &str, name: String) -> bool {
let name = name.trim();
if name.is_empty() {
@@ -2079,6 +2118,12 @@ impl WorkspaceThreadStore {
let Some(project_id) = self.active_project_id_for_space(space_id) else {
return false;
};
+ // Never write a local layout for mux-domain threads; the remote mux
+ // server owns the layout truth (second layer under the window-origin
+ // tag guard in snapshot_active_space_thread_layout_with_font_scales).
+ if is_mux_domain_project_id(&project_id) {
+ return false;
+ }
let Some(project) = self
.projects
.iter_mut()
@@ -3158,6 +3203,11 @@ fn is_remote_project(project: &Project) -> bool {
}
fn thread_has_restorable_workspace(thread: &WorkspaceThread) -> bool {
+ // Mux-domain threads have no local layout to restore: their content lives
+ // on the remote mux server and only materializes through `wezterm connect`.
+ if is_mux_domain_project_id(&thread.project_id) {
+ return false;
+ }
thread.layout.is_some() || thread.materialized_workspace_name.is_some()
}
@@ -3235,6 +3285,124 @@ pub fn remote_project_id_for_space(space_id: &str, host_id: &str) -> ProjectId {
format!("{host_id}{REMOTE_PROJECT_SPACE_SEPARATOR}{space_id}")
}
+/// Prefix distinguishing mux-client-domain pseudo host ids from the ssh_hosts
+/// store's `ssh-`/`system-ssh-` ids, so none of the sidebar SSH machinery
+/// fires on them.
+const MUX_DOMAIN_HOST_PREFIX: &str = "muxdomain-";
+
+pub fn mux_domain_host_id(domain_name: &str) -> String {
+ format!("{MUX_DOMAIN_HOST_PREFIX}{domain_name}")
+}
+
+pub fn is_mux_domain_project_id(project_id: &str) -> bool {
+ remote_host_id_for_project_id(project_id).starts_with(MUX_DOMAIN_HOST_PREFIX)
+}
+
+pub fn client_domain_name_for_project_id(project_id: &str) -> Option<&str> {
+ remote_host_id_for_project_id(project_id).strip_prefix(MUX_DOMAIN_HOST_PREFIX)
+}
+
+/// Everything `wezterm connect` needs to route a client-domain attach into
+/// its dedicated Space.
+#[derive(Debug, Clone)]
+pub struct MuxDomainSpacePlan {
+ pub space_id: SpaceId,
+ pub project_id: ProjectId,
+ pub thread_id: WorkspaceThreadId,
+ /// Deterministic canonical workspace name for the thread; the connect
+ /// window is renamed into this workspace once attach has completed.
+ pub workspace_name: String,
+}
+
+/// Find-or-create the dedicated Space for a mux client domain, along with its
+/// single project and "main" thread. Idempotent: reconnecting converges on the
+/// same records.
+pub fn ensure_mux_domain_space(domain_name: &str) -> MuxDomainSpacePlan {
+ let mut store = THREAD_STORE.lock();
+
+ let space_id = store
+ .spaces
+ .iter()
+ .find(|space| space.client_domain.as_deref() == Some(domain_name))
+ .map(|space| space.id.clone())
+ .unwrap_or_else(|| {
+ store.create_space_record_for_domain(
+ domain_name.to_string(),
+ Some(domain_name.to_string()),
+ )
+ });
+
+ let host_id = mux_domain_host_id(domain_name);
+ let project_id = remote_project_id_for_space(&space_id, &host_id);
+ if !store.projects.iter().any(|p| p.id == project_id) {
+ store.projects.push(Project {
+ id: project_id.clone(),
+ space_id: space_id.clone(),
+ name: domain_name.to_string(),
+ path: PathBuf::from(format!("wezterm-mux://{domain_name}")),
+ threads: vec![],
+ active_thread_id: None,
+ threads_collapsed: false,
+ });
+ }
+
+ let project = store
+ .projects
+ .iter_mut()
+ .find(|p| p.id == project_id)
+ .expect("mux domain project was just ensured");
+ if project.threads.is_empty() {
+ project
+ .threads
+ .push(WorkspaceThread::new(project_id.clone(), "main".to_string(), None));
+ }
+ let thread_id = project
+ .active_thread_id
+ .clone()
+ .filter(|id| project.threads.iter().any(|t| &t.id == id))
+ .unwrap_or_else(|| project.threads[0].id.clone());
+ project.active_thread_id = Some(thread_id.clone());
+
+ if let Some(space) = store.spaces.iter_mut().find(|space| space.id == space_id) {
+ space.active_project_id = Some(project_id.clone());
+ }
+
+ let workspace_name = workspace_name_for_thread(&project_id, &thread_id);
+ persist_locked(&store);
+
+ MuxDomainSpacePlan {
+ space_id,
+ project_id,
+ thread_id,
+ workspace_name,
+ }
+}
+
+/// Point a mux-domain thread at the mux workspace it is currently
+/// materialized in (or clear it with `None` when the connect fails).
+/// Only applies to mux-domain threads; returns whether a change was made.
+pub fn bind_mux_domain_thread_workspace(thread_id: &str, workspace: Option<String>) -> bool {
+ let mut store = THREAD_STORE.lock();
+ let mut changed = false;
+ for project in store.projects.iter_mut() {
+ if !is_mux_domain_project_id(&project.id) {
+ continue;
+ }
+ if let Some(thread) = project.threads.iter_mut().find(|t| t.id == thread_id) {
+ if thread.materialized_workspace_name != workspace {
+ thread.materialized_workspace_name = workspace;
+ thread.last_active_at = now_ts();
+ changed = true;
+ }
+ break;
+ }
+ }
+ if changed {
+ persist_locked(&store);
+ }
+ changed
+}
+
pub fn remote_host_id_for_project_id(project_id: &str) -> &str {
project_id
.split_once(REMOTE_PROJECT_SPACE_SEPARATOR)