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
feat(gui): auto-claim remote viewport on explicit connect
RoversX54ddeb11bda2
diff --git a/config/src/config.rs b/config/src/config.rsindex 0cff87e8..375aca59 100644--- a/config/src/config.rs+++ b/config/src/config.rs@@ -793,6 +793,12 @@ pub struct Config {#[dynamic(default = "default_true")]pub automatically_reload_config: bool,+ /// Claim the active terminal after an explicit remote mux Connect action,+ /// before showing its initial grid. Background reconnects never auto-claim.+ /// Disable to keep viewing the remote terminal until clicking to take control.+ #[dynamic(default = "default_true")]+ pub remote_mux_auto_claim_on_open: bool,+#[dynamic(default = "default_check_for_updates")]pub check_for_updates: bool,#[dynamic(@@ -2574,6 +2580,19 @@ mod tests {assert!(Config::default().note_remote_images_enabled);}+ #[test]+ fn remote_mux_auto_claim_can_be_disabled_in_config() {+ use wezterm_dynamic::{FromDynamic, Object, Value};+ assert!(Config::default().remote_mux_auto_claim_on_open);+ let mut values = Object::default();+ values.insert(+ Value::String("remote_mux_auto_claim_on_open".to_string()),+ Value::Bool(false),+ );+ let config = Config::from_dynamic(&Value::Object(values), Default::default()).unwrap();+ assert!(!config.remote_mux_auto_claim_on_open);+ }+#[test]fn import_loader_restores_env_and_collects_raw_keys() {let _env_lock = ENV_LOCK.lock().unwrap();diff --git a/wezterm-gui/src/frontend.rs b/wezterm-gui/src/frontend.rsindex c975cf69..42c45170 100644--- a/wezterm-gui/src/frontend.rs+++ b/wezterm-gui/src/frontend.rs@@ -783,6 +783,7 @@ impl GuiFrontEnd {mux_window_id,space_owner_id,active_space_id.clone(),+ None,).await{diff --git a/wezterm-gui/src/main.rs b/wezterm-gui/src/main.rsindex a1ffd8e4..fbf14500 100644--- a/wezterm-gui/src/main.rs+++ b/wezterm-gui/src/main.rs@@ -579,6 +579,36 @@ async fn adopt_materialized_workspace_window(Ok(())}+/// Clear the first-open gate if authentication/materialization fails or the+/// async Connect request is cancelled. Success hands the one-shot intent to+/// the GUI, which waits for the selected remote tab before consuming it.+struct RemoteOpenRequest {+ window: Option<window::Window>,+ domain_id: mux::domain::DomainId,+}++impl RemoteOpenRequest {+ fn finish(mut self) {+ if let Some(window) = self.window.take() {+ let domain_id = self.domain_id;+ window.notify(crate::termwindow::TermWindowNotif::Apply(Box::new(move |tw| {+ tw.finish_remote_open(domain_id);+ })));+ }+ }+}++impl Drop for RemoteOpenRequest {+ fn drop(&mut self) {+ if let Some(window) = self.window.take() {+ let domain_id = self.domain_id;+ window.notify(crate::termwindow::TermWindowNotif::Apply(Box::new(move |tw| {+ tw.cancel_remote_open(domain_id);+ })));+ }+ }+}+pub(crate) async fn connect_domain_into_space(cmd: Option<CommandBuilder>,domain: Arc<dyn Domain>,@@ -601,6 +631,10 @@ pub(crate) async fn connect_domain_into_space(if let Some(gui_window) =crate::frontend::front_end().gui_window_for_mux_window(window_id){+ let domain_id = domain.domain_id();+ gui_window.window.notify(crate::termwindow::TermWindowNotif::Apply(Box::new(+ move |tw| tw.claim_remote_viewport_for_explicit_open(domain_id),+ )));gui_window.window.focus();return Ok(());}@@ -621,6 +655,10 @@ pub(crate) async fn connect_domain_into_space(if let Some(gui_window) =crate::frontend::front_end().gui_window_for_mux_window(window_id){+ let domain_id = domain.domain_id();+ gui_window.window.notify(crate::termwindow::TermWindowNotif::Apply(Box::new(+ move |tw| tw.claim_remote_viewport_for_explicit_open(domain_id),+ )));gui_window.window.focus();return Ok(());}@@ -649,8 +687,21 @@ pub(crate) async fn connect_domain_into_space(id};- TermWindow::new_window_with_claimed_space(window_id, space_owner_id, plan.space_id.clone())- .await?;+ TermWindow::new_window_with_claimed_space(+ window_id,+ space_owner_id,+ plan.space_id.clone(),+ Some(domain.domain_id()),+ )+ .await?;+ // Keep the native handle: adopting the restored workspace can replace+ // its mux-window id while this explicit connection is in progress.+ let remote_open = RemoteOpenRequest {+ window: crate::frontend::front_end()+ .gui_window_for_mux_window(window_id)+ .map(|gui| gui.window),+ domain_id: domain.domain_id(),+ };let config = config::configuration();config.update_ulimit()?;@@ -769,6 +820,7 @@ pub(crate) async fn connect_domain_into_space(let _tab = domain.spawn(size, cmd, None, window_id).await?;}}+ remote_open.finish();drop(connect_activity);trigger_and_log_gui_attached(MuxDomain(domain.domain_id())).await;diff --git a/wezterm-gui/src/termwindow/keyevent.rs b/wezterm-gui/src/termwindow/keyevent.rsindex 3dd1077f..56f310cb 100644--- a/wezterm-gui/src/termwindow/keyevent.rs+++ b/wezterm-gui/src/termwindow/keyevent.rs@@ -655,7 +655,8 @@ impl super::TermWindow {if only_key_bindings == OnlyKeyBindings::No&& matches!(self.frontend_terminal_gate(),- wezterm_client::domain::RemoteFrontendGate::Syncing+ wezterm_client::domain::RemoteFrontendGate::Connecting+ | wezterm_client::domain::RemoteFrontendGate::Syncing){return true;diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rsindex 542013d5..0b3b66f3 100644--- a/wezterm-gui/src/termwindow/mod.rs+++ b/wezterm-gui/src/termwindow/mod.rs@@ -2081,6 +2081,12 @@ pub(crate) enum FrontendGeometryPhase {TakeoverSyncing { epoch: u64, show_overlay: bool },}+#[derive(Debug, Clone, Copy)]+pub(crate) struct RemoteOpenIntent {+ domain_id: DomainId,+ ready: bool,+}+impl FrontendGeometryPhase {pub(crate) fn epoch(self) -> u64 {match self {@@ -2207,6 +2213,8 @@ pub struct TermWindow {/// remain visible; only a real takeover or unknown initial owner obscures/// the terminal until the matching epoch is acknowledged.frontend_geometry_phases: HashMap<TabId, FrontendGeometryPhase>,+ /// One explicit Connect request, not a policy applied on every attach.+ remote_open_intent: Option<RemoteOpenIntent>,/// A takeover RPC acknowledges PTY resize before the remote application/// redraw has reached this renderer. Keep its expected pane snapshots here/// and reveal only after every visible row has been refreshed and stable.@@ -3629,7 +3637,7 @@ impl TermWindow {impl TermWindow {pub async fn new_window(mux_window_id: MuxWindowId) -> anyhow::Result<()> {- Self::new_window_impl(mux_window_id, None, true).await+ Self::new_window_impl(mux_window_id, None, true, None).await}/// For domain-owned mux windows (remote mux windows arriving via a@@ -3637,18 +3645,20 @@ impl TermWindow {/// 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+ Self::new_window_impl(mux_window_id, None, false, None).await}pub async fn new_window_with_claimed_space(mux_window_id: MuxWindowId,space_owner_id: u64,active_space_id: String,+ remote_open_domain: Option<DomainId>,) -> anyhow::Result<()> {Self::new_window_impl(mux_window_id,Some((space_owner_id, active_space_id)),false,+ remote_open_domain,).await}@@ -3657,6 +3667,7 @@ impl TermWindow {mux_window_id: MuxWindowId,claimed_space: Option<(u64, String)>,restore_saved_thread: bool,+ remote_open_domain: Option<DomainId>,) -> anyhow::Result<()> {let config = configuration();let native_settings = crate::native_settings::load();@@ -3816,6 +3827,12 @@ impl TermWindow {let myself = Self {frontend_geometry_phases: HashMap::new(),+ remote_open_intent: remote_open_domain+ .filter(|_| config.remote_mux_auto_claim_on_open)+ .map(|domain_id| RemoteOpenIntent {+ domain_id,+ ready: false,+ }),frontend_geometry_confirmations: HashMap::new(),frontend_geometry_resized: std::collections::HashSet::new(),frontend_recovery_geometry: HashMap::new(),@@ -5897,6 +5914,8 @@ impl TermWindow {preferred_thread: Option<String>,window: &Window,) -> bool {+ // Navigating elsewhere cancels the earlier window-opening intent.+ self.remote_open_intent = None;if self.workspace_sidebar_swipe.pending_switch_target() != Some(space_id.as_str()) {self.workspace_sidebar_swipe.cancel_immediately();self.clear_workspace_space_swipe_frame_transition();@@ -8032,6 +8051,7 @@ impl TermWindow {}fn activate_tab(&mut self, tab_idx: isize) -> anyhow::Result<()> {+ self.remote_open_intent = None;let mux = Mux::get();let mut window = mux.get_window_mut(self.mux_window_id)@@ -9185,7 +9205,8 @@ impl TermWindow {if matches!(assignment, PasteFrom(_) | SendString(_) | SendKey(_))&& matches!(self.frontend_terminal_gate(),- wezterm_client::domain::RemoteFrontendGate::Syncing+ wezterm_client::domain::RemoteFrontendGate::Connecting+ | wezterm_client::domain::RemoteFrontendGate::Syncing){return Ok(PerformAssignmentResult::Handled);diff --git a/wezterm-gui/src/termwindow/mouseevent.rs b/wezterm-gui/src/termwindow/mouseevent.rsindex fd1edee2..f9d8100b 100644--- a/wezterm-gui/src/termwindow/mouseevent.rs+++ b/wezterm-gui/src/termwindow/mouseevent.rs@@ -6104,6 +6104,7 @@ impl super::TermWindow {}pub(crate) fn activate_workspace_thread(&mut self, thread_id: String, context: &dyn WindowOps) {+ self.remote_open_intent = None;self.activate_workspace_thread_impl(thread_id, context, None, Vec::new());}diff --git a/wezterm-gui/src/termwindow/render/paint.rs b/wezterm-gui/src/termwindow/render/paint.rsindex 73ef947b..ae70da12 100644--- a/wezterm-gui/src/termwindow/render/paint.rs+++ b/wezterm-gui/src/termwindow/render/paint.rs@@ -3901,6 +3901,7 @@ impl crate::TermWindow {(!content_view_active && !fading_content_view) || recording_flight;if !content_view_active {+ self.advance_remote_open();// Poll and hydrate the post-resize screen before sampling the// gate. Explicit takeovers may show the grid during this wait;// connection recovery still uses the opaque surface.diff --git a/wezterm-gui/src/termwindow/resize.rs b/wezterm-gui/src/termwindow/resize.rsindex 4e263f0f..52eda542 100644--- a/wezterm-gui/src/termwindow/resize.rs+++ b/wezterm-gui/src/termwindow/resize.rs@@ -51,6 +51,33 @@ fn frontend_gate_with_geometry(}}+fn take_ready_remote_open(+ pending: &mut Option<super::RemoteOpenIntent>,+ enabled: bool,+ domain_id: mux::domain::DomainId,+ gate: &RemoteFrontendGate,+ geometry_in_flight: bool,+) -> bool {+ if !enabled {+ *pending = None;+ return false;+ }+ if pending.is_some_and(|intent| intent.ready && intent.domain_id == domain_id)+ && !geometry_in_flight+ && matches!(+ gate,+ RemoteFrontendGate::Visible | RemoteFrontendGate::Claimable { .. }+ )+ {+ // Consume before starting the RPC: output, repaints and reconnects+ // must never turn the same navigation into another ownership claim.+ *pending = None;+ true+ } else {+ false+ }+}+fn frontend_geometry_action(ownership: Option<bool>,collaborative: bool,@@ -294,6 +321,20 @@ impl super::TermWindow {RemoteFrontendGate::Claimable { owner: state.owner }}};+ if self.config.remote_mux_auto_claim_on_open+ && self.remote_open_intent+ .is_some_and(|intent| intent.domain_id == pane.domain_id())+ && matches!(+ gate,+ RemoteFrontendGate::Visible+ | RemoteFrontendGate::Claimable { .. }+ | RemoteFrontendGate::Syncing+ )+ {+ // The explicit connection has not selected and prepared its final+ // landing tab yet. Do not reveal the old renderer's grid first.+ return RemoteFrontendGate::Connecting;+ }frontend_gate_with_geometry(gate,self.frontend_geometry_phases.get(&tab.tab_id()).copied(),@@ -1174,6 +1215,78 @@ impl super::TermWindow {/// the overwhelmingly common case, so an ordinary click costs one/// comparison.pub(crate) fn claim_frontend_viewport_for_interaction(&mut self) {+ self.claim_frontend_viewport(false);+ }++ /// Reopening an already visible remote window is an explicit takeover,+ /// but does not need the first-open loading surface again.+ pub(crate) fn claim_remote_viewport_for_explicit_open(+ &mut self,+ domain_id: mux::domain::DomainId,+ ) {+ let still_showing_domain = Mux::get()+ .get_active_tab_for_window(self.mux_window_id)+ .and_then(|tab| tab.get_active_pane())+ .is_some_and(|pane| {+ pane.domain_id() == domain_id && pane.downcast_ref::<ClientPane>().is_some()+ });+ if self.config.remote_mux_auto_claim_on_open && still_showing_domain {+ self.claim_frontend_viewport_for_interaction();+ }+ }++ pub(crate) fn finish_remote_open(&mut self, domain_id: mux::domain::DomainId) {+ if let Some(intent) = self.remote_open_intent.as_mut() {+ if intent.domain_id == domain_id {+ intent.ready = true;+ self.advance_remote_open();+ self.invalidate_window();+ }+ }+ }++ pub(crate) fn cancel_remote_open(&mut self, domain_id: mux::domain::DomainId) {+ if self.remote_open_intent+ .is_some_and(|intent| intent.domain_id == domain_id)+ {+ self.remote_open_intent = None;+ self.invalidate_window();+ }+ }++ pub(crate) fn advance_remote_open(&mut self) {+ if !self.config.remote_mux_auto_claim_on_open {+ self.remote_open_intent = None;+ return;+ }+ if !self.remote_open_intent.is_some_and(|intent| intent.ready) {+ return;+ }+ let Some(tab) = Mux::get().get_active_tab_for_window(self.mux_window_id) else {+ return;+ };+ let Some(pane) = tab.get_active_pane() else {+ return;+ };+ let Some(client) = pane.downcast_ref::<ClientPane>() else {+ return;+ };+ let in_flight = self+ .frontend_geometry_phases+ .get(&tab.tab_id())+ .is_some_and(|phase| phase.is_in_flight());+ if take_ready_remote_open(+ &mut self.remote_open_intent,+ self.config.remote_mux_auto_claim_on_open,+ client.domain_id(),+ &client.remote_frontend_gate(),+ in_flight,+ ) {+ self.claim_frontend_viewport(true);+ }+ }++ fn claim_frontend_viewport(&mut self, initial_open: bool) {if !matches!(self.frontend_terminal_gate(),RemoteFrontendGate::Visible | RemoteFrontendGate::Claimable { .. }@@ -1190,7 +1303,7 @@ impl super::TermWindow {.get(&tab_id).copied().is_some_and(super::FrontendGeometryPhase::is_in_flight)- || self.owns_frontend_viewport()+ || (!initial_open && self.owns_frontend_viewport()){return;}@@ -1217,8 +1330,9 @@ impl super::TermWindow {// An explicit user takeover re-arms the remote publish path too.self.forget_rejected_local_viewport(tab_id);let confirm = self.remote_takeover_needs_confirmation(&tab);- // Keep the existing picture while confirming the new grid.- let Some(epoch) = self.begin_frontend_geometry_epoch(tab_id, confirm, false) else {+ // A click keeps its existing picture. A new connection waits to reveal+ // the terminal until its first usable local-sized grid is ready.+ let Some(epoch) = self.begin_frontend_geometry_epoch(tab_id, confirm, initial_open) else {return;};let Some((domain, viewport, adopted)) = self.prepare_client_frontend_geometry(&tab) else {@@ -1603,6 +1717,21 @@ impl super::TermWindow {return;};+ // Manual Connect will submit the chosen landing layout once attach+ // and materialization finish. Do not race it with a passive publish.+ if self.config.remote_mux_auto_claim_on_open+ && self.remote_open_intent+ .is_some_and(|intent| intent.domain_id == active_pane.domain_id())+ && active_pane.downcast_ref::<ClientPane>().is_some_and(|client| {+ matches!(+ client.remote_frontend_gate(),+ RemoteFrontendGate::Visible | RemoteFrontendGate::Claimable { .. }+ )+ })+ {+ return;+ }+if active_pane.downcast_ref::<ClientPane>().is_none() {tab.resize(self.terminal_size);self.reapply_collapsed_panes_for_tab(tab_id);@@ -3025,17 +3154,70 @@ mod frontend_geometry_tests {use super::{client_viewport_publish_is_worthwhile, frontend_gate_with_geometry, frontend_geometry_action,geometry_confirmation_settled, local_viewport_publish_is_worthwhile,- remote_divider_can_pump, remote_divider_target_is_owed,+ remote_divider_can_pump, remote_divider_target_is_owed, take_ready_remote_open,visible_geometry_targets,FrontendGeometryAction, LocalTabShape, RejectedClientViewport, RejectedLocalViewport,FRONTEND_GEOMETRY_SETTLE, REJECTED_CLIENT_VIEWPORT_HOLD,};- use crate::termwindow::{FrontendGeometryPhase, RemoteDividerResizeStrategy};+ use crate::termwindow::{FrontendGeometryPhase, RemoteDividerResizeStrategy, RemoteOpenIntent};use std::collections::HashSet;use std::time::{Duration, Instant};use wezterm_client::domain::RemoteFrontendGate;use wezterm_term::TerminalSize;+ #[test]+ fn explicit_remote_open_is_consumed_once_after_the_landing_tab_is_ready() {+ let mut pending = Some(RemoteOpenIntent {+ domain_id: 7,+ ready: false,+ });+ let gate = RemoteFrontendGate::Claimable { owner: None };+ assert!(!take_ready_remote_open(&mut pending, true, 7, &gate, false));+ pending.as_mut().unwrap().ready = true;+ assert!(!take_ready_remote_open(&mut pending, true, 8, &gate, false));+ assert!(!take_ready_remote_open(&mut pending, true, 7, &gate, true));+ assert!(take_ready_remote_open(&mut pending, true, 7, &gate, false));+ assert!(pending.is_none());+ // Neither repainting nor returning from a later disconnect may claim again.+ for gate in [+ RemoteFrontendGate::Reconnecting,+ gate,+ RemoteFrontendGate::Visible,+ ] {+ assert!(!take_ready_remote_open(&mut pending, true, 7, &gate, false));+ }+ }++ #[test]+ fn disabling_auto_claim_drops_the_pending_intent_and_keeps_manual_takeover() {+ let mut pending = Some(RemoteOpenIntent {+ domain_id: 7,+ ready: true,+ });+ let gate = RemoteFrontendGate::Claimable { owner: None };+ assert!(!take_ready_remote_open(&mut pending, false, 7, &gate, false));+ assert!(pending.is_none());+ assert!(!take_ready_remote_open(&mut pending, true, 7, &gate, false));+ assert!(frontend_gate_with_geometry(gate, None, true).is_claimable());+ }++ #[test]+ fn pending_remote_open_does_not_claim_during_transport_recovery() {+ let mut pending = Some(RemoteOpenIntent {+ domain_id: 7,+ ready: true,+ });+ for gate in [+ RemoteFrontendGate::Connecting,+ RemoteFrontendGate::Syncing,+ RemoteFrontendGate::Reconnecting,+ RemoteFrontendGate::Offline,+ ] {+ assert!(!take_ready_remote_open(&mut pending, true, 7, &gate, false));+ assert!(pending.is_some());+ }+ }+fn test_size(cols: usize, rows: usize) -> TerminalSize {TerminalSize {cols,