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.

Fix frontend-lease races and identity leaks across awaits

RoversX3907de0958d0
diff --git a/clippy.toml b/clippy.toml
new file mode 100644
index 00000000..c9704d44
--- /dev/null
+++ b/clippy.toml
@@ -0,0 +1,4 @@
+# `Mux.identity` is a process-global slot; holding its RAII guard across an
+# `.await` publishes the wrong identity to every other main-thread task and
+# breaks the guard's LIFO restore. See `Mux::with_identity` for the full story.
+await-holding-invalid-types = ["mux::IdentityHolder"]
diff --git a/mux/src/lib.rs b/mux/src/lib.rs
index 7a5f6ed3..5d213744 100644
--- a/mux/src/lib.rs
+++ b/mux/src/lib.rs
@@ -3,13 +3,13 @@ use crate::pane::{CachePolicy, Pane, PaneId};
use crate::ssh_agent::AgentProxy;
use crate::tab::{SplitRequest, Tab, TabId};
use crate::window::{Window, WindowId, WindowUiSurfaceId};
-use anyhow::{Context, Error, anyhow};
+use anyhow::{anyhow, Context, Error};
use config::keyassignment::SpawnTabDomain;
-use config::{ExitBehavior, GuiPosition, configuration};
+use config::{configuration, ExitBehavior, GuiPosition};
use domain::{Domain, DomainId, DomainState, SplitSource};
-use filedescriptor::{AsRawSocketDescriptor, FileDescriptor, POLLIN, poll, pollfd, socketpair};
+use filedescriptor::{poll, pollfd, socketpair, AsRawSocketDescriptor, FileDescriptor, POLLIN};
#[cfg(unix)]
-use libc::{SO_RCVBUF, SO_SNDBUF, SOL_SOCKET, c_int};
+use libc::{c_int, SOL_SOCKET, SO_RCVBUF, SO_SNDBUF};
use log::error;
use metrics::histogram;
use parking_lot::{
@@ -34,7 +34,7 @@ use wezterm_term::{
Clipboard, ClipboardSelection, DownloadHandler, TerminalConfiguration, TerminalSize,
};
#[cfg(windows)]
-use winapi::um::winsock2::{SO_RCVBUF, SO_SNDBUF, SOL_SOCKET};
+use winapi::um::winsock2::{SOL_SOCKET, SO_RCVBUF, SO_SNDBUF};
pub mod activity;
pub mod client;
@@ -237,6 +237,29 @@ struct TabFrontendLease {
generation: u64,
}
+/// True when `me` is the only *live* client that has advertised geometry for
+/// any tab. A sole renderer cannot be fighting anyone over the lease, so an
+/// unclaimed lease is effectively its own. Two or more renderers must take it
+/// explicitly — see `unregister_client`, which deliberately elects no
+/// successor.
+///
+/// Handoff's owner is global, so the scan is global: a phone rendering tab B
+/// must still stop the desktop from silently assuming tab A. Filtering by
+/// `live` registrations guards against a viewport left behind by a client
+/// whose transport died without an orderly unregister.
+fn is_sole_live_renderer(
+ tabs: &HashMap<TabId, TabFrontendLease>,
+ live: &HashSet<ClientId>,
+ me: &ClientId,
+) -> bool {
+ !tabs.values().any(|state| {
+ state
+ .viewports
+ .keys()
+ .any(|client| client != me && live.contains(client))
+ })
+}
+
struct FrontendLeaseState {
tabs: HashMap<TabId, TabFrontendLease>,
access_mode: FrontendAccessMode,
@@ -1100,33 +1123,43 @@ impl Mux {
}
pub fn current_identity_owns_frontend_lease(&self, tab_id: TabId) -> bool {
- // An UNCLAIMED lease belongs to whoever is asking. The lease exists to
- // stop two frontends fighting over one tab's geometry; when nobody
- // holds it there is nothing to protect, and answering "not yours"
- // paralyzes the only frontend present: the GUI's local viewport
- // publish can fail its compose validation ("frontend frames do not
- // compose"), the lease then never gets claimed, and every pane-size
- // sync behind `owns_frontend_viewport` is silently skipped -- measured
- // as split-divider drags leaving TUIs at their old PTY size until the
- // drag ends. The identity-less arm below already treated unclaimed as
- // permitted; this makes the identified arm consistent.
- let unclaimed = {
- let lease = self.frontend_lease.lock();
- match lease.access_mode {
- FrontendAccessMode::Handoff => lease.handoff_owner.is_none(),
- FrontendAccessMode::TmuxLatest => lease
+ // Lock order: registrations first, dropped before the lease lock is
+ // taken — the same order `set_registered_client_viewport` uses.
+ let identity = self.active_identity();
+ let live: HashSet<ClientId> = self.client_registrations.read().keys().cloned().collect();
+ let lease = self.frontend_lease.lock();
+ match lease.access_mode {
+ // Per-tab ownership is cheap to re-take and is re-seeded by the
+ // very next passive report (`set_client_viewport` seeds an
+ // ownerless tab unconditionally), so an unclaimed tab belongs to
+ // whoever asks — symmetric with the wire path.
+ FrontendAccessMode::TmuxLatest => {
+ match lease
.tabs
.get(&tab_id)
.and_then(|state| state.owner.as_ref())
- .is_none(),
+ {
+ None => true,
+ Some(owner) => identity.as_deref() == Some(owner),
+ }
}
- };
- if unclaimed {
- return true;
- }
- match self.active_identity() {
- Some(identity) => self.client_owns_frontend_lease(&identity, tab_id),
- None => false,
+ FrontendAccessMode::Handoff => match lease.handoff_owner.as_ref() {
+ Some(owner) => identity.as_deref() == Some(owner),
+ // Bootstrap: nobody has ever rendered, nothing to protect.
+ None if !lease.handoff_ever_owned => true,
+ // Post-revocation. Symmetric with wire clients
+ // (`set_client_viewport` seeds only while
+ // `!handoff_ever_owned`): survivors must claim explicitly.
+ // The one exception is a sole renderer, which recovers on its
+ // own instead of sitting behind a takeover surface with
+ // nobody to take the terminal from — this preserves the fix
+ // for the measured paralysis (split-divider drags leaving
+ // TUIs at their old PTY size) without letting two surviving
+ // frontends fight over the geometry.
+ None => identity
+ .as_deref()
+ .is_some_and(|me| is_sole_live_renderer(&lease.tabs, &live, me)),
+ },
}
}
@@ -1769,6 +1802,24 @@ impl Mux {
.unwrap_or_else(|| self.get_default_workspace())
}
+ /// The workspace a request from `client_id` should file new windows under.
+ ///
+ /// Exactly equivalent to `active_workspace()` evaluated with `client_id`
+ /// installed as the global identity, but without touching that global.
+ /// Server handlers must resolve workspace attribution with this *before*
+ /// they await: an `IdentityHolder` held across a suspension point
+ /// publishes the wrong identity to every other main-thread task, and its
+ /// restore is not LIFO-safe.
+ pub fn active_workspace_for_optional_client(
+ &self,
+ client_id: Option<&Arc<ClientId>>,
+ ) -> String {
+ match client_id {
+ Some(client_id) => self.active_workspace_for_client(client_id),
+ None => self.get_default_workspace(),
+ }
+ }
+
pub fn set_active_workspace_for_client(&self, ident: &Arc<ClientId>, workspace: &str) {
let mut clients = self.clients.write();
if let Some(info) = clients.get_mut(&ident) {
@@ -1813,6 +1864,18 @@ impl Mux {
/// Returns `IdentityHolder` which will restore the prior identity
/// when it is dropped.
/// This can be used to change the identity for the duration of a block.
+ ///
+ /// # This guard must not be held across an `.await`
+ ///
+ /// The identity is a single process-global slot and `IdentityHolder`'s
+ /// restore is not LIFO-safe across interleaved tasks. Suspending with one
+ /// installed publishes the wrong identity to every other main-thread
+ /// task, including GUI mux subscribers (which run synchronously from
+ /// `notify`) and `record_input_for_current_identity`, which in
+ /// `TmuxLatest` mode will *claim* a tab's viewport for whoever happens to
+ /// be installed. Resolve what you need synchronously (e.g.
+ /// [`Mux::active_workspace_for_optional_client`]) and pass it as data.
+ /// `clippy.toml` arms `await_holding_invalid_type` for `IdentityHolder`.
pub fn with_identity(&self, id: Option<Arc<ClientId>>) -> IdentityHolder {
let prior = self.replace_identity(id);
IdentityHolder { prior }
@@ -3099,6 +3162,196 @@ mod tests {
tab.tab_id()
}
+ #[test]
+ fn sole_live_renderer_ignores_itself_and_dead_clients() {
+ let me = client_id(150);
+ let other = client_id(151);
+ let mut live = HashSet::new();
+ live.insert(me.clone());
+ let mut tabs: HashMap<TabId, TabFrontendLease> = HashMap::new();
+
+ // No viewports anywhere: sole.
+ assert!(is_sole_live_renderer(&tabs, &live, &me));
+
+ // Only my own viewport: still sole.
+ tabs.entry(1)
+ .or_default()
+ .viewports
+ .insert(me.clone(), frontend_test_viewport(80, 24));
+ assert!(is_sole_live_renderer(&tabs, &live, &me));
+
+ // Another client's viewport, but that client is dead: still sole.
+ tabs.entry(2)
+ .or_default()
+ .viewports
+ .insert(other.clone(), frontend_test_viewport(60, 20));
+ assert!(is_sole_live_renderer(&tabs, &live, &me));
+
+ // Same viewport once the client is live: no longer sole.
+ live.insert(other.clone());
+ assert!(!is_sole_live_renderer(&tabs, &live, &me));
+
+ // A live client with no viewport anywhere (a `wezterm cli` style
+ // non-rendering client) does not count as a renderer.
+ tabs.get_mut(&2).unwrap().viewports.remove(&other);
+ assert!(is_sole_live_renderer(&tabs, &live, &me));
+ }
+
+ #[test]
+ fn unclaimed_handoff_lease_belongs_to_the_first_renderer() {
+ let mux = Mux::new(None);
+ mux.initialize_frontend_access_mode(FrontendAccessMode::Handoff);
+ let tab_id = frontend_test_tab(&mux);
+
+ // Bootstrap: nobody has ever rendered.
+ assert!(mux.current_identity_owns_frontend_lease(tab_id));
+ mux.replace_identity(Some(Arc::new(client_id(160))));
+ assert!(mux.current_identity_owns_frontend_lease(tab_id));
+ }
+
+ #[test]
+ fn revoked_handoff_lease_stays_unowned_while_two_renderers_are_present() {
+ let mux = Mux::new(None);
+ mux.initialize_frontend_access_mode(FrontendAccessMode::Handoff);
+ let tab_id = frontend_test_tab(&mux);
+ let gui = Arc::new(client_id(161));
+ let tui = Arc::new(client_id(162));
+ mux.register_client(Arc::clone(&gui));
+ mux.register_client(Arc::clone(&tui));
+ {
+ let mut lease = mux.frontend_lease.lock();
+ lease.handoff_owner = None;
+ lease.handoff_ever_owned = true;
+ let state = lease.tabs.entry(tab_id).or_default();
+ state
+ .viewports
+ .insert((*gui).clone(), frontend_test_viewport(120, 40));
+ state
+ .viewports
+ .insert((*tui).clone(), frontend_test_viewport(60, 20));
+ }
+
+ // Symmetry is the point: neither survivor silently owns the lease.
+ mux.replace_identity(Some(Arc::clone(&gui)));
+ assert!(!mux.current_identity_owns_frontend_lease(tab_id));
+ mux.replace_identity(Some(Arc::clone(&tui)));
+ assert!(!mux.current_identity_owns_frontend_lease(tab_id));
+ }
+
+ #[test]
+ fn revoked_handoff_lease_returns_to_the_sole_surviving_renderer() {
+ let mux = Mux::new(None);
+ mux.initialize_frontend_access_mode(FrontendAccessMode::Handoff);
+ let tab_id = frontend_test_tab(&mux);
+ let gui = Arc::new(client_id(163));
+ let tui = Arc::new(client_id(164));
+ mux.register_client(Arc::clone(&gui));
+ let tui_registration = mux.register_client(Arc::clone(&tui));
+ {
+ let mut lease = mux.frontend_lease.lock();
+ lease.handoff_owner = None;
+ lease.handoff_ever_owned = true;
+ let state = lease.tabs.entry(tab_id).or_default();
+ state
+ .viewports
+ .insert((*gui).clone(), frontend_test_viewport(120, 40));
+ state
+ .viewports
+ .insert((*tui).clone(), frontend_test_viewport(60, 20));
+ }
+ mux.replace_identity(Some(Arc::clone(&gui)));
+ assert!(!mux.current_identity_owns_frontend_lease(tab_id));
+
+ mux.unregister_client(&tui, tui_registration);
+ assert!(mux.current_identity_owns_frontend_lease(tab_id));
+
+ // A viewport left behind by a dead client must not block recovery.
+ mux.frontend_lease
+ .lock()
+ .tabs
+ .get_mut(&tab_id)
+ .unwrap()
+ .viewports
+ .insert((*tui).clone(), frontend_test_viewport(60, 20));
+ assert!(mux.current_identity_owns_frontend_lease(tab_id));
+ }
+
+ #[test]
+ fn claimed_handoff_lease_is_not_owned_by_a_non_owner() {
+ let mux = Mux::new(None);
+ mux.initialize_frontend_access_mode(FrontendAccessMode::Handoff);
+ let tab_id = frontend_test_tab(&mux);
+ let owner = Arc::new(client_id(165));
+ let bystander = Arc::new(client_id(166));
+ {
+ let mut lease = mux.frontend_lease.lock();
+ lease.handoff_owner = Some((*owner).clone());
+ lease.handoff_ever_owned = true;
+ }
+
+ mux.replace_identity(Some(Arc::clone(&bystander)));
+ assert!(!mux.current_identity_owns_frontend_lease(tab_id));
+ mux.replace_identity(Some(Arc::clone(&owner)));
+ assert!(mux.current_identity_owns_frontend_lease(tab_id));
+ mux.replace_identity(None);
+ assert!(!mux.current_identity_owns_frontend_lease(tab_id));
+ }
+
+ #[test]
+ fn unclaimed_tmux_latest_tab_is_owned_by_the_asking_renderer() {
+ let mux = Mux::new(None);
+ mux.initialize_frontend_access_mode(FrontendAccessMode::TmuxLatest);
+ let tab_id = frontend_test_tab(&mux);
+ let me = Arc::new(client_id(167));
+ let other = Arc::new(client_id(168));
+ mux.register_client(Arc::clone(&me));
+ mux.register_client(Arc::clone(&other));
+ {
+ let mut lease = mux.frontend_lease.lock();
+ let state = lease.tabs.entry(tab_id).or_default();
+ state
+ .viewports
+ .insert((*me).clone(), frontend_test_viewport(120, 40));
+ state
+ .viewports
+ .insert((*other).clone(), frontend_test_viewport(60, 20));
+ }
+
+ // Per-tab claims are cheap and symmetric: an ownerless tab belongs to
+ // whoever asks, even with another renderer present.
+ mux.replace_identity(Some(Arc::clone(&me)));
+ assert!(mux.current_identity_owns_frontend_lease(tab_id));
+
+ mux.frontend_lease
+ .lock()
+ .tabs
+ .get_mut(&tab_id)
+ .unwrap()
+ .owner = Some((*other).clone());
+ assert!(!mux.current_identity_owns_frontend_lease(tab_id));
+ }
+
+ #[test]
+ fn optional_client_workspace_matches_the_identified_fallback() {
+ config::use_test_configuration();
+ let mux = Mux::new(None);
+ let client = Arc::new(client_id(190));
+ mux.register_client(Arc::clone(&client));
+ mux.set_active_workspace_for_client(&client, "space-2");
+
+ assert_eq!(
+ mux.active_workspace_for_optional_client(Some(&client)),
+ "space-2"
+ );
+ // The None case must resolve to the default workspace — exactly what
+ // `active_workspace()` produced with no identity installed.
+ assert_eq!(
+ mux.active_workspace_for_optional_client(None),
+ mux.active_workspace()
+ );
+ assert_eq!(mux.active_workspace_for_optional_client(None), "default");
+ }
+
#[test]
fn failed_first_handoff_geometry_revokes_the_automatic_owner() {
let mux = Mux::new(None);
@@ -3107,10 +3360,9 @@ mod tests {
let client = client_id(201);
mux.frontend_geometry_failures.lock().push_back(true);
- assert!(
- mux.set_client_viewport(&client, tab_id, frontend_test_viewport(120, 40))
- .is_err()
- );
+ assert!(mux
+ .set_client_viewport(&client, tab_id, frontend_test_viewport(120, 40))
+ .is_err());
let lease = mux.frontend_lease.lock();
assert_eq!(lease.handoff_owner, None);
assert!(lease.handoff_ever_owned);
@@ -3132,10 +3384,9 @@ mod tests {
}
mux.frontend_geometry_failures.lock().push_back(true);
- assert!(
- mux.claim_frontend_viewport(&second, tab_id, frontend_test_viewport(120, 40))
- .is_err()
- );
+ assert!(mux
+ .claim_frontend_viewport(&second, tab_id, frontend_test_viewport(120, 40))
+ .is_err());
let lease = mux.frontend_lease.lock();
assert_eq!(lease.handoff_owner, None);
assert_eq!(lease.tabs[&tab_id].owner, None);
@@ -3155,15 +3406,14 @@ mod tests {
}
mux.frontend_geometry_failures.lock().push_back(true);
- assert!(
- mux.set_frontend_access_mode(
+ assert!(mux
+ .set_frontend_access_mode(
&owner,
FrontendAccessMode::TmuxLatest,
tab_id,
frontend_test_viewport(120, 40),
)
- .is_err()
- );
+ .is_err());
let access = mux.frontend_access_state();
assert_eq!(access.mode, FrontendAccessMode::Handoff);
assert_eq!(access.owner, None);
@@ -3567,16 +3817,15 @@ mod tests {
mux.set_registered_client_viewport(&second, second_registration, tab_id, grid.clone())
.unwrap();
- assert!(
- mux.set_registered_frontend_access_mode(
+ assert!(mux
+ .set_registered_frontend_access_mode(
&second,
second_registration,
FrontendAccessMode::TmuxLatest,
tab_id,
grid.clone(),
)
- .is_err()
- );
+ .is_err());
mux.set_registered_frontend_access_mode(
&first,
first_registration,
@@ -3590,16 +3839,15 @@ mod tests {
// the one allowed to make itself B's global owner.
mux.claim_registered_client_viewport(&second, second_registration, tab_id, grid.clone())
.unwrap();
- assert!(
- mux.set_registered_frontend_access_mode(
+ assert!(mux
+ .set_registered_frontend_access_mode(
&first,
first_registration,
FrontendAccessMode::Handoff,
tab_id,
grid.clone(),
)
- .is_err()
- );
+ .is_err());
let access = mux
.set_registered_frontend_access_mode(
&second,
diff --git a/wezterm-mux-server-impl/src/sessionhandler.rs b/wezterm-mux-server-impl/src/sessionhandler.rs
index 06ba55f2..b4f1913e 100644
--- a/wezterm-mux-server-impl/src/sessionhandler.rs
+++ b/wezterm-mux-server-impl/src/sessionhandler.rs
@@ -1,8 +1,8 @@
use crate::PKI;
-use anyhow::{Context, anyhow};
+use anyhow::{anyhow, Context};
use codec::*;
-use config::TermConfig;
use config::keyassignment::SpawnTabDomain;
+use config::TermConfig;
use mux::client::ClientId;
use mux::domain::SplitSource;
use mux::pane::{CachePolicy, Pane, PaneId};
@@ -19,9 +19,9 @@ use std::sync::{Arc, Mutex};
use std::time::Instant;
use termwiz::surface::SequenceNo;
use url::Url;
-use wezterm_term::StableRowIndex;
use wezterm_term::color::ColorPalette;
use wezterm_term::terminal::Alert;
+use wezterm_term::StableRowIndex;
lazy_static::lazy_static! {
/// Serializes the authoritative tree decision with the live-workspace
@@ -1108,25 +1108,22 @@ impl SessionHandler {
}
Pdu::SpawnV2(spawn) => {
- let client_id = self.client_id.clone();
spawn_into_main_thread(async move {
- schedule_domain_spawn_v2(spawn, send_response, client_id);
+ schedule_domain_spawn_v2(spawn, send_response);
})
.detach();
}
Pdu::SplitPane(split) => {
- let client_id = self.client_id.clone();
spawn_into_main_thread(async move {
- schedule_split_pane(split, send_response, client_id);
+ schedule_split_pane(split, send_response);
})
.detach();
}
Pdu::SpawnPaneInStack(request) => {
- let client_id = self.client_id.clone();
spawn_into_main_thread(async move {
- schedule_spawn_pane_in_stack(request, send_response, client_id);
+ schedule_spawn_pane_in_stack(request, send_response);
})
.detach();
}
@@ -1169,9 +1166,8 @@ impl SessionHandler {
}
Pdu::MovePaneToStack(request) => {
- let client_id = self.client_id.clone();
spawn_into_main_thread(async move {
- schedule_move_pane_to_stack(request, send_response, client_id);
+ schedule_move_pane_to_stack(request, send_response);
})
.detach();
}
@@ -1187,9 +1183,8 @@ impl SessionHandler {
}
Pdu::EnsureThinkTermThread(request) => {
- let client_id = self.client_id.clone();
spawn_into_main_thread(async move {
- schedule_ensure_thinkterm_thread(request, send_response, client_id);
+ schedule_ensure_thinkterm_thread(request, send_response);
})
.detach();
}
@@ -1630,37 +1625,28 @@ impl SessionHandler {
// function below because the compiler thinks that all of its locals then need to be Send.
// We need to shimmy through this helper to break that aspect of the compiler flow
// analysis and allow things to compile.
-fn schedule_domain_spawn_v2<SND>(
- spawn: SpawnV2,
- send_response: SND,
- client_id: Option<Arc<ClientId>>,
-) where
+fn schedule_domain_spawn_v2<SND>(spawn: SpawnV2, send_response: SND)
+where
SND: Fn(anyhow::Result<Pdu>) + 'static,
{
- promise::spawn::spawn(async move { send_response(domain_spawn_v2(spawn, client_id).await) })
- .detach();
+ promise::spawn::spawn(async move { send_response(domain_spawn_v2(spawn).await) }).detach();
}
-fn schedule_ensure_thinkterm_thread<SND>(
- request: EnsureThinkTermThread,
- send_response: SND,
- client_id: Option<Arc<ClientId>>,
-) where
+fn schedule_ensure_thinkterm_thread<SND>(request: EnsureThinkTermThread, send_response: SND)
+where
SND: Fn(anyhow::Result<Pdu>) + 'static,
{
- promise::spawn::spawn(async move {
- send_response(ensure_thinkterm_thread(request, client_id).await)
- })
- .detach();
+ promise::spawn::spawn(async move { send_response(ensure_thinkterm_thread(request).await) })
+ .detach();
}
-async fn ensure_thinkterm_thread(
- request: EnsureThinkTermThread,
- client_id: Option<Arc<ClientId>>,
-) -> anyhow::Result<Pdu> {
+async fn ensure_thinkterm_thread(request: EnsureThinkTermThread) -> anyhow::Result<Pdu> {
let _materialize = THINKTERM_MATERIALIZE.lock().await;
let mux = Mux::get();
- let _identity = mux.with_identity(client_id);
+ // No identity is installed here on purpose: every workspace name on this
+ // path is explicit (`landing.workspace`), and a guard held across the
+ // awaits below would leak the requesting identity to unrelated
+ // main-thread work. See `Mux::with_identity`.
let landing = crate::thinkterm_tree::ensure_landing(request.preferred_thread_id.as_deref())?;
let has_live_pane = mux
@@ -1724,6 +1710,12 @@ async fn ensure_thinkterm_thread(
))
}
+/// NOTE: this runs with *no* identity installed (see `ensure_thinkterm_thread`).
+/// If layout restore or this fallback ever gains a "send a command to the new
+/// shell" step, that write would reach `record_input_for_current_identity`
+/// and, in `TmuxLatest`, claim the tab's viewport for the ambient identity
+/// (the GUI's, in a GUI-hosted mux) — resolve the requesting identity
+/// explicitly at that point instead of re-adding a `with_identity` guard.
async fn spawn_default_thinkterm_thread(
mux: &Mux,
landing: &crate::thinkterm_tree::LandingRecord,
@@ -1748,37 +1740,29 @@ async fn spawn_default_thinkterm_thread(
Ok(())
}
-fn schedule_split_pane<SND>(split: SplitPane, send_response: SND, client_id: Option<Arc<ClientId>>)
+fn schedule_split_pane<SND>(split: SplitPane, send_response: SND)
where
SND: Fn(anyhow::Result<Pdu>) + 'static,
{
- promise::spawn::spawn(async move { send_response(split_pane(split, client_id).await) })
- .detach();
+ promise::spawn::spawn(async move { send_response(split_pane(split).await) }).detach();
}
-fn schedule_spawn_pane_in_stack<SND>(
- request: SpawnPaneInStack,
- send_response: SND,
- client_id: Option<Arc<ClientId>>,
-) where
+fn schedule_spawn_pane_in_stack<SND>(request: SpawnPaneInStack, send_response: SND)
+where
SND: Fn(anyhow::Result<Pdu>) + 'static,
{
- promise::spawn::spawn(
- async move { send_response(spawn_pane_in_stack(request, client_id).await) },
- )
- .detach();
+ promise::spawn::spawn(async move { send_response(spawn_pane_in_stack(request).await) })
+ .detach();
}
-fn schedule_move_pane_to_stack<SND>(
- request: MovePaneToStack,
- send_response: SND,
- client_id: Option<Arc<ClientId>>,
-) where
+fn schedule_move_pane_to_stack<SND>(request: MovePaneToStack, send_response: SND)
+where
SND: Fn(anyhow::Result<Pdu>) + 'static,
{
promise::spawn::spawn(async move {
let mux = Mux::get();
- let _identity = mux.with_identity(client_id);
+ // No identity: `move_pane_to_stack` reads none, and a guard held
+ // across the await would leak the identity to unrelated work.
send_response(
mux.move_pane_to_stack(request.source_pane_id, request.target_pane_id)
.await
@@ -1788,12 +1772,10 @@ fn schedule_move_pane_to_stack<SND>(
.detach();
}
-async fn spawn_pane_in_stack(
- request: SpawnPaneInStack,
- client_id: Option<Arc<ClientId>>,
-) -> anyhow::Result<Pdu> {
+async fn spawn_pane_in_stack(request: SpawnPaneInStack) -> anyhow::Result<Pdu> {
let mux = Mux::get();
- let _identity = mux.with_identity(client_id);
+ // No identity: `spawn_pane_in_stack` reads none, and a guard held across
+ // the await would leak the identity to unrelated main-thread work.
let (_pane_domain_id, window_id, tab_id) = mux
.resolve_pane_id(request.pane_id)
@@ -1831,9 +1813,10 @@ async fn spawn_pane_in_stack(
}))
}
-async fn split_pane(split: SplitPane, client_id: Option<Arc<ClientId>>) -> anyhow::Result<Pdu> {
+async fn split_pane(split: SplitPane) -> anyhow::Result<Pdu> {
let mux = Mux::get();
- let _identity = mux.with_identity(client_id);
+ // No identity: `Mux::split_pane` reads none, and a guard held across the
+ // await would leak the identity to unrelated main-thread work.
let (_pane_domain_id, window_id, tab_id) = mux
.resolve_pane_id(split.pane_id)
@@ -1860,9 +1843,12 @@ async fn split_pane(split: SplitPane, client_id: Option<Arc<ClientId>>) -> anyho
}))
}
-async fn domain_spawn_v2(spawn: SpawnV2, client_id: Option<Arc<ClientId>>) -> anyhow::Result<Pdu> {
+async fn domain_spawn_v2(spawn: SpawnV2) -> anyhow::Result<Pdu> {
let mux = Mux::get();
- let _identity = mux.with_identity(client_id);
+ // No identity: `spawn.workspace` is an explicit non-optional string on
+ // the wire, so `spawn_tab_or_window` never falls back to the ambient
+ // identity's workspace. A guard held across the await would leak the
+ // identity to unrelated main-thread work.
let (tab, pane, window_id) = mux
.spawn_tab_or_window(
@@ -1896,19 +1882,44 @@ fn schedule_move_pane<SND>(
.detach();
}
+/// `Mux::move_pane_to_new_tab` falls back to the *global identity's*
+/// workspace when it has to create a window and nobody named one. Resolve
+/// that name here, synchronously and per-client, so no identity has to
+/// survive the await.
+///
+/// Only the new-window case is filled in: with a `window_id` the workspace
+/// is unused locally, and leaving it `None` keeps the PDU forwarded to a
+/// nested mux byte-identical to before.
+fn workspace_for_moved_pane(
+ mux: &Mux,
+ requested: Option<String>,
+ window_id: Option<mux::window::WindowId>,
+ client_id: Option<&Arc<ClientId>>,
+) -> Option<String> {
+ if requested.is_some() || window_id.is_some() {
+ return requested;
+ }
+ Some(mux.active_workspace_for_optional_client(client_id))
+}
+
async fn move_pane(
request: MovePaneToNewTab,
client_id: Option<Arc<ClientId>>,
) -> anyhow::Result<Pdu> {
let mux = Mux::get();
- let _identity = mux.with_identity(client_id);
+ // No identity is installed here: the one identity-derived value on this
+ // path (the fallback workspace for a new window) is resolved explicitly
+ // below. A guard held across the await would leak the identity to
+ // unrelated main-thread work.
+ let workspace = workspace_for_moved_pane(
+ &mux,
+ request.workspace_for_new_window,
+ request.window_id,
+ client_id.as_ref(),
+ );
let (tab, window_id) = mux
- .move_pane_to_new_tab(
- request.pane_id,
- request.window_id,
- request.workspace_for_new_window,
- )
+ .move_pane_to_new_tab(request.pane_id, request.window_id, workspace)
.await?;
Ok::<Pdu, anyhow::Error>(Pdu::MovePaneToNewTabResponse(MovePaneToNewTabResponse {
@@ -1919,13 +1930,16 @@ async fn move_pane(
#[cfg(test)]
mod tests {
- use super::{PerPane, claim_viewport_for_pane, requires_existing_frontend_access};
+ use super::{
+ claim_viewport_for_pane, requires_existing_frontend_access, workspace_for_moved_pane,
+ PerPane,
+ };
use codec::{EnsureThinkTermThread, Pdu};
- use mux::Mux;
use mux::client::ClientId;
+ use mux::Mux;
use std::sync::Arc;
- use wezterm_term::TerminalSize;
use wezterm_term::color::ColorPalette;
+ use wezterm_term::TerminalSize;
#[test]
fn cold_thread_materialization_does_not_require_an_existing_owner() {
@@ -1960,6 +1974,38 @@ mod tests {
assert!(superseded.contains("superseded client connection"));
}
+ #[test]
+ fn moved_pane_workspace_is_resolved_from_the_requesting_client() {
+ config::use_test_configuration();
+ let mux = Mux::new(None);
+ let client = Arc::new(ClientId::new());
+ mux.register_client(Arc::clone(&client));
+ mux.set_active_workspace_for_client(&client, "space-2");
+
+ // An explicitly requested workspace passes through untouched.
+ assert_eq!(
+ workspace_for_moved_pane(&mux, Some("named".to_string()), None, Some(&client)),
+ Some("named".to_string())
+ );
+ // An existing-window move keeps the field empty: it is unused locally
+ // and the forwarded nested-mux PDU stays byte-identical.
+ assert_eq!(
+ workspace_for_moved_pane(&mux, None, Some(7), Some(&client)),
+ None
+ );
+ // A new window with no name lands in the requesting client's
+ // workspace...
+ assert_eq!(
+ workspace_for_moved_pane(&mux, None, None, Some(&client)),
+ Some("space-2".to_string())
+ );
+ // ...and in the default workspace when the request is anonymous.
+ assert_eq!(
+ workspace_for_moved_pane(&mux, None, None, None),
+ Some("default".to_string())
+ );
+ }
+
#[test]
fn application_palette_delivery_distinguishes_unsent_from_reset() {
let mut state = PerPane::default();
diff --git a/wezterm-mux-server-impl/src/thinkterm_access.rs b/wezterm-mux-server-impl/src/thinkterm_access.rs
index 27461281..f7e226b5 100644
--- a/wezterm-mux-server-impl/src/thinkterm_access.rs
+++ b/wezterm-mux-server-impl/src/thinkterm_access.rs
@@ -4,6 +4,19 @@
//! and must be rebuilt after each mux-server restart. A malformed existing file
//! is never silently overwritten: the server starts safely in Handoff mode but
//! refuses mode mutations until the operator repairs or removes that file.
+//!
+//! # Single writer per file
+//!
+//! `STORE` is a per-process cache read once at startup. Both wezterm-gui
+//! (which also calls `persist_mode` in-process from its own frontend-mode UI)
+//! and wezterm-mux-server cache independently, and neither re-reads on a
+//! schedule: mux mode is initialized exactly once per process
+//! (`initialize_mux`, `Mux::initialize_frontend_access_mode`). Concurrent
+//! writers are therefore last-writer-wins; `persist_mode` re-reads the file
+//! before each write so a concurrent change is *reported* (and the write is
+//! based on the on-disk truth), but modes are not reconciled across live
+//! processes — that would need owner-validated runtime handoff and is out of
+//! scope here.
use anyhow::{Context, Result};
use mux::{FrontendAccessMode, Mux};
@@ -129,17 +142,42 @@ pub fn initialize_mux(mux: &Mux) {
/// Persist before the caller commits the mux state. `StoreState` changes only
/// after the atomic replace succeeds.
pub fn persist_mode(mode: FrontendAccessMode) -> Result<()> {
- let mut store = STORE.lock().unwrap();
+ persist_mode_at(&access_path(), &mut STORE.lock().unwrap(), mode)
+}
+
+fn persist_mode_at(path: &Path, store: &mut StoreState, mode: FrontendAccessMode) -> Result<()> {
if let Some(err) = &store.load_error {
- anyhow::bail!(
- "refusing to overwrite unreadable {}: {err}",
- access_path().display()
- );
+ anyhow::bail!("refusing to overwrite unreadable {}: {err}", path.display());
+ }
+ // Another process (GUI-embedded server vs standalone mux-server) may have
+ // written the file since this process cached it. Decide against the
+ // on-disk truth, not the cache: the stale-cache early return below used
+ // to skip a write the file actually needed.
+ match load_from_path(path) {
+ Ok(on_disk) => {
+ if on_disk != store.mode {
+ log::warn!(
+ "{} was changed out from under this process (on disk {on_disk:?}, \
+ this process last knew {:?}); writing {mode:?} anyway — last \
+ writer wins",
+ path.display(),
+ store.mode
+ );
+ store.mode = on_disk;
+ }
+ }
+ Err(err) => {
+ log::warn!(
+ "refusing to overwrite {}: it became unreadable since startup: {err:#}",
+ path.display()
+ );
+ return Err(err);
+ }
}
if store.mode == mode {
return Ok(());
}
- save_to_path(&access_path(), mode)?;
+ save_to_path(path, mode)?;
store.mode = mode;
Ok(())
}
@@ -171,4 +209,39 @@ mod tests {
assert!(load_from_path(&path).is_err());
assert!(path.exists());
}
+
+ #[test]
+ fn a_concurrent_mode_change_is_reported_and_the_last_writer_wins() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("thinkterm_access.json");
+ // Another process wrote TmuxLatest while this process still believes
+ // its own last write of Handoff is current.
+ save_to_path(&path, FrontendAccessMode::TmuxLatest).unwrap();
+ let mut store = StoreState {
+ mode: FrontendAccessMode::Handoff,
+ load_error: None,
+ };
+
+ // The stale-cache early return used to skip this write entirely,
+ // leaving the file saying TmuxLatest while this process believed
+ // Handoff. Deciding against the on-disk truth fixes that.
+ persist_mode_at(&path, &mut store, FrontendAccessMode::Handoff).unwrap();
+ assert_eq!(load_from_path(&path).unwrap(), FrontendAccessMode::Handoff);
+ assert_eq!(store.mode, FrontendAccessMode::Handoff);
+ }
+
+ #[test]
+ fn an_unreadable_file_is_not_overwritten_even_when_the_cache_looks_clean() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("thinkterm_access.json");
+ std::fs::write(&path, b"not json").unwrap();
+ let mut store = StoreState {
+ mode: FrontendAccessMode::Handoff,
+ load_error: None,
+ };
+
+ assert!(persist_mode_at(&path, &mut store, FrontendAccessMode::TmuxLatest).is_err());
+ assert_eq!(std::fs::read(&path).unwrap(), b"not json");
+ assert_eq!(store.mode, FrontendAccessMode::Handoff);
+ }
}