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.

Harden shared mux domains and remote client state

RoversXbfbcc4f19d3c
diff --git a/mux/src/lib.rs b/mux/src/lib.rs
index 94631253..2e882a2e 100644
--- a/mux/src/lib.rs
+++ b/mux/src/lib.rs
@@ -869,6 +869,22 @@ impl Mux {
}
for domain_id in domains_of_window {
+ // Detach only when NO surviving window still references the
+ // domain. One thread's workspace window going away must not
+ // sever a client connection that other threads in the same
+ // Space are still displaying — that detach ripples out as
+ // "every pane of the domain removed", which empties every
+ // window and takes the whole process down with it.
+ let still_referenced = self.windows.read().values().any(|win| {
+ win.iter().any(|tab| {
+ tab.iter_all_panes()
+ .iter()
+ .any(|pane| pane.domain_id() == domain_id)
+ })
+ });
+ if still_referenced {
+ continue;
+ }
if let Some(domain) = self.get_domain(domain_id) {
if domain.detachable() {
log::info!("detaching domain");
diff --git a/mux/src/tab.rs b/mux/src/tab.rs
index 6cd40970..8de716ba 100644
--- a/mux/src/tab.rs
+++ b/mux/src/tab.rs
@@ -3845,20 +3845,36 @@ mod test {
}
}
- struct MuxTestGuard;
+ struct MuxTestGuard {
+ _serial: parking_lot::MutexGuard<'static, ()>,
+ }
impl Drop for MuxTestGuard {
fn drop(&mut self) {
- // Deliberately keep the global Mux installed: tests run in
- // parallel and share it, so shutting it down here makes
- // Mux::get() panic in whichever test is still mid-flight.
- // Each install_mux() swaps in a fresh instance anyway.
+ // Deliberately keep the global Mux installed rather than calling
+ // Mux::shutdown(): code outside these tests reaches it via
+ // Mux::try_get() (notifications), and a fresh instance is swapped
+ // in by the next install_mux() anyway.
}
}
fn install_mux() -> MuxTestGuard {
+ // Window-level APIs (kill_window et al) schedule follow-up work; give
+ // the promise layer a scheduler so they don't panic. The executor is
+ // never pumped — these tests assert on the synchronous effects only.
+ static SCHEDULER: std::sync::Once = std::sync::Once::new();
+ SCHEDULER.call_once(|| {
+ let _ = promise::spawn::SimpleExecutor::new();
+ });
+ // The Mux is a process-wide singleton, and these tests assert on its
+ // global state (the windows map, domain attach lifecycles). Parallel
+ // test threads would register their windows and panes into whichever
+ // instance is installed at that moment, corrupting each other's
+ // still-referenced scans — so global-Mux tests run one at a time.
+ static SERIAL: parking_lot::Mutex<()> = parking_lot::Mutex::new(());
+ let serial = SERIAL.lock();
Mux::set_mux(&Arc::new(Mux::new(None)));
- MuxTestGuard
+ MuxTestGuard { _serial: serial }
}
#[test]
@@ -4442,4 +4458,114 @@ mod test {
fn tab_is_send_and_sync() {
assert!(is_send_and_sync::<Tab>());
}
+
+ /// Detachable domain double whose only job is to count detach calls.
+ /// domain_id 1 matches what FakePane reports.
+ struct FakeDetachableDomain {
+ detach_count: Arc<std::sync::atomic::AtomicUsize>,
+ }
+
+ #[async_trait::async_trait(?Send)]
+ impl crate::domain::Domain for FakeDetachableDomain {
+ async fn spawn(
+ &self,
+ _size: TerminalSize,
+ _command: Option<portable_pty::CommandBuilder>,
+ _command_dir: Option<String>,
+ _window: WindowId,
+ ) -> anyhow::Result<Arc<Tab>> {
+ unimplemented!()
+ }
+
+ async fn split_pane(
+ &self,
+ _source: crate::domain::SplitSource,
+ _tab: TabId,
+ _pane_id: PaneId,
+ _split_request: SplitRequest,
+ ) -> anyhow::Result<Arc<dyn Pane>> {
+ unimplemented!()
+ }
+
+ async fn spawn_pane(
+ &self,
+ _size: TerminalSize,
+ _command: Option<portable_pty::CommandBuilder>,
+ _command_dir: Option<String>,
+ ) -> anyhow::Result<Arc<dyn Pane>> {
+ unimplemented!()
+ }
+
+ fn detachable(&self) -> bool {
+ true
+ }
+
+ fn domain_id(&self) -> DomainId {
+ 1
+ }
+
+ fn domain_name(&self) -> &str {
+ "fake-detachable"
+ }
+
+ async fn attach(&self, _window_id: Option<WindowId>) -> anyhow::Result<()> {
+ Ok(())
+ }
+
+ fn detach(&self) -> anyhow::Result<()> {
+ self.detach_count
+ .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ Ok(())
+ }
+
+ fn state(&self) -> crate::domain::DomainState {
+ crate::domain::DomainState::Attached
+ }
+ }
+
+ /// Pins the fix for "deleting one thread severed the whole connection":
+ /// removing a mux window must NOT detach a detachable domain while other
+ /// windows still hold panes of it, and MUST still detach it when the last
+ /// referencing window goes away.
+ #[test]
+ fn removing_one_window_keeps_a_shared_domain_attached() {
+ let _guard = install_mux();
+ let mux = Mux::get();
+ let size = test_size();
+ let detach_count = Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let domain: Arc<dyn crate::domain::Domain> = Arc::new(FakeDetachableDomain {
+ detach_count: Arc::clone(&detach_count),
+ });
+ mux.add_domain(&domain);
+
+ let mut window_ids = Vec::new();
+ for pane_id in [20_001, 20_002] {
+ let tab = Arc::new(Tab::new(&size));
+ let pane = FakePane::new(pane_id, size);
+ tab.assign_pane(&pane);
+ mux.add_tab_no_panes(&tab);
+ mux.add_pane(&pane).unwrap();
+ let window_id = *mux.new_empty_window(None, None);
+ mux.add_tab_to_window(&tab, window_id).unwrap();
+ window_ids.push(window_id);
+ }
+
+ mux.kill_window(window_ids[0]);
+ assert_eq!(
+ detach_count.load(std::sync::atomic::Ordering::SeqCst),
+ 0,
+ "a domain still shown by another window must survive"
+ );
+ assert!(
+ mux.get_pane(20_002).is_some(),
+ "the surviving window's pane must still exist"
+ );
+
+ mux.kill_window(window_ids[1]);
+ assert_eq!(
+ detach_count.load(std::sync::atomic::Ordering::SeqCst),
+ 1,
+ "the last referencing window going away must still detach"
+ );
+ }
}
diff --git a/wezterm-client/src/domain.rs b/wezterm-client/src/domain.rs
index 3f6f0b92..c458d477 100644
--- a/wezterm-client/src/domain.rs
+++ b/wezterm-client/src/domain.rs
@@ -641,7 +641,7 @@ impl ClientDomain {
let inner = Self::get_client_inner_for_domain(domain_id)?;
let panes = inner.client.list_panes().await?;
- Self::process_pane_list(inner, panes, None)?;
+ Self::process_pane_list(inner, panes, None, true)?;
ui.close();
Ok(())
@@ -664,7 +664,7 @@ impl ClientDomain {
inner.defer_resync();
return Ok(());
}
- Self::process_pane_list(inner, panes, None)?;
+ Self::process_pane_list(inner, panes, None, false)?;
}
Ok(())
}
@@ -693,6 +693,7 @@ impl ClientDomain {
inner: Arc<ClientInner>,
panes: ListPanesResponse,
mut primary_window_id: Option<WindowId>,
+ resend_palette: bool,
) -> anyhow::Result<()> {
let mux = Mux::get();
// A native/mux window can disappear while an attach or structural RPC
@@ -798,6 +799,16 @@ impl ClientDomain {
Some(pane) => {
if let Some(client_pane) = pane.downcast_ref::<ClientPane>() {
client_pane.set_remote_tab_id(entry.tab_id);
+ if resend_palette {
+ // A reattach can land on a fresh
+ // server process that never received
+ // our palette, and its bare defaults
+ // are what OSC color queries would
+ // otherwise keep answering. Ordinary
+ // structural resyncs do not need the
+ // extra RPC.
+ client_pane.resend_palette_to_server();
+ }
}
pane
}
@@ -994,7 +1005,7 @@ impl ClientDomain {
guard.replace(Arc::clone(&inner));
}
- Self::process_pane_list(inner, panes, primary_window_id)?;
+ Self::process_pane_list(inner, panes, primary_window_id, false)?;
Ok(())
}
diff --git a/wezterm-client/src/pane/clientpane.rs b/wezterm-client/src/pane/clientpane.rs
index 865ffe87..40779fff 100644
--- a/wezterm-client/src/pane/clientpane.rs
+++ b/wezterm-client/src/pane/clientpane.rs
@@ -58,6 +58,77 @@ fn decide_resize(
}
}
+/// Delivery state of the palette advisory RPC.
+///
+/// A single worker task owns all sending for a pane, and it always sends the
+/// LATEST desired palette — that serialization is what makes stale overwrites
+/// impossible (two concurrent send tasks with retries could land an old color
+/// on the server after a newer one). The state transitions live here, off the
+/// network, so the ordering rules are unit-testable.
+#[derive(Default)]
+struct PaletteDelivery {
+ /// The palette we want the server to hold.
+ desired: Option<ColorPalette>,
+ /// The palette the server last confirmed receiving. `None` means
+ /// unknown: never confirmed, failed, or invalidated by a reconnect.
+ delivered: Option<ColorPalette>,
+ /// Whether the sender worker is alive. At most one ever runs.
+ sender_running: bool,
+}
+
+impl PaletteDelivery {
+ /// Adopt a new target. Returns true when the caller must start the
+ /// worker (none is running); an already-running worker will pick the
+ /// new target up on its next loop.
+ fn adopt_target(&mut self, palette: ColorPalette) -> bool {
+ self.desired = Some(palette);
+ if self.sender_running {
+ false
+ } else {
+ self.sender_running = true;
+ true
+ }
+ }
+
+ /// What the worker should send next, or `None` when it is done — in
+ /// which case the worker slot is released.
+ fn next_to_send(&mut self) -> Option<ColorPalette> {
+ match &self.desired {
+ Some(target) if self.delivered.as_ref() != Some(target) => Some(target.clone()),
+ _ => {
+ self.sender_running = false;
+ None
+ }
+ }
+ }
+
+ fn record_success(&mut self, sent: ColorPalette) {
+ self.delivered = Some(sent);
+ }
+
+ /// The worker gave up (repeated RPC failures). `delivered` stays
+ /// whatever it was — importantly NOT the desired value — so the next
+ /// set_config or resync restarts the worker instead of assuming the
+ /// server heard us.
+ fn give_up_if_still_desired(&mut self, attempted: &ColorPalette) -> bool {
+ if self.desired.as_ref() == Some(attempted) {
+ self.sender_running = false;
+ true
+ } else {
+ // A newer target arrived during the final failed RPC. Keep the
+ // worker slot and let it send that target instead of stranding it
+ // until an unrelated config update or resync happens.
+ false
+ }
+ }
+
+ /// A reconnect happened: whatever we previously confirmed, the server
+ /// may be a fresh process that knows nothing.
+ fn invalidate_delivery(&mut self) {
+ self.delivered = None;
+ }
+}
+
pub struct ClientPane {
client: Arc<ClientInner>,
local_pane_id: PaneId,
@@ -65,6 +136,10 @@ pub struct ClientPane {
remote_tab_id: AtomicUsize,
pub renderable: Mutex<RenderableState>,
configured_palette: Mutex<ColorPalette>,
+ /// Delivery state for the palette advisory: what we want the server to
+ /// hold and what it last confirmed. A single worker task drains it; see
+ /// [`PaletteDelivery`].
+ delivered_palette: Arc<Mutex<PaletteDelivery>>,
palette: Mutex<ColorPalette>,
application_palette: Mutex<bool>,
writer: Mutex<PaneWriter>,
@@ -80,6 +155,93 @@ pub struct ClientPane {
}
impl ClientPane {
+ /// Ask the (single) sender worker to bring the server to `palette`.
+ /// Starts the worker when none is running; a running worker picks the
+ /// new target up by itself. Re-sends of identical palettes are
+ /// flicker-free: both the server and the receiving side de-duplicate.
+ fn advise_server_palette(
+ client: Arc<ClientInner>,
+ remote_pane_id: PaneId,
+ palette: ColorPalette,
+ delivery: Arc<Mutex<PaletteDelivery>>,
+ ) {
+ if !delivery.lock().adopt_target(palette) {
+ return;
+ }
+ promise::spawn::spawn(async move {
+ let mut failures = 0u32;
+ let mut failed_target: Option<ColorPalette> = None;
+ loop {
+ let Some(target) = delivery.lock().next_to_send() else {
+ // Delivered everything we wanted; the slot is released.
+ return;
+ };
+ let result = client
+ .client
+ .set_configured_palette_for_pane(SetPalette {
+ pane_id: remote_pane_id,
+ palette: target.clone(),
+ })
+ .await;
+ match result {
+ Ok(_) => {
+ failures = 0;
+ failed_target = None;
+ // Desired may have moved on while this was in
+ // flight; the next loop sends the newer target, so
+ // an old color can never be the last one standing.
+ delivery.lock().record_success(target);
+ }
+ Err(err) => {
+ if failed_target.as_ref() == Some(&target) {
+ failures += 1;
+ } else {
+ // A new desired palette gets its own retry budget;
+ // failures of the superseded value do not count.
+ failed_target = Some(target.clone());
+ failures = 1;
+ }
+ log::warn!(
+ "advising palette for remote pane {remote_pane_id} \
+ (attempt {failures}): {err:#}"
+ );
+ if failures >= 3 {
+ let gave_up = delivery.lock().give_up_if_still_desired(&target);
+ if gave_up {
+ // Leave delivery unconfirmed: the next
+ // set_config or resync restarts the worker
+ // rather than assuming the server heard us.
+ return;
+ }
+ failures = 0;
+ failed_target = None;
+ continue;
+ }
+ smol::Timer::after(std::time::Duration::from_secs(2)).await;
+ }
+ }
+ }
+ })
+ .detach();
+ }
+
+ /// Re-advise the server of the configured palette. Called after a
+ /// resync reattaches this pane: the server may be a fresh process that
+ /// never received the original advisory, and its bare default palette
+ /// is what OSC color queries would keep answering. Previous delivery
+ /// confirmations are meaningless across a reconnect, so they are
+ /// invalidated first.
+ pub fn resend_palette_to_server(&self) {
+ let palette = self.configured_palette.lock().clone();
+ self.delivered_palette.lock().invalidate_delivery();
+ Self::advise_server_palette(
+ Arc::clone(&self.client),
+ self.remote_pane_id,
+ palette,
+ Arc::clone(&self.delivered_palette),
+ );
+ }
+
pub fn new(
client: &Arc<ClientInner>,
remote_tab_id: TabId,
@@ -125,21 +287,18 @@ impl ClientPane {
let config = configuration();
let palette: ColorPalette = config.resolved_palette.clone().into();
- // Advise the server of our palette preference
- promise::spawn::spawn({
- let palette = palette.clone();
- let client = Arc::clone(client);
- async move {
- client
- .client
- .set_configured_palette_for_pane(SetPalette {
- pane_id: remote_pane_id,
- palette,
- })
- .await
- }
- })
- .detach();
+ // Advise the server of our palette preference. Delivery is tracked:
+ // if this send is lost (attach races, transient RPC failure), the
+ // server would otherwise answer OSC color queries from its bare
+ // defaults forever — and an application that queries-then-restores
+ // the foreground would then paint the pane in those defaults.
+ let delivered_palette = Arc::new(Mutex::new(PaletteDelivery::default()));
+ Self::advise_server_palette(
+ Arc::clone(client),
+ remote_pane_id,
+ palette.clone(),
+ Arc::clone(&delivered_palette),
+ );
Self {
client: Arc::clone(client),
@@ -151,6 +310,7 @@ impl ClientPane {
renderable: Mutex::new(render),
writer: Mutex::new(writer),
configured_palette: Mutex::new(palette.clone()),
+ delivered_palette,
palette: Mutex::new(palette),
clipboard: Mutex::new(None),
mouse_grabbed: Mutex::new(false),
@@ -725,13 +885,15 @@ impl Pane for ClientPane {
fn set_config(&self, config: Arc<dyn TerminalConfiguration>) {
let palette = config.color_palette();
- // Only propagate a palette that actually changed. set_config is
- // invoked for every pane on every config generation bump (which
- // can be frequent: any write near a watched config path reloads),
- // and an unconditional send makes the server re-advise the palette
- // to every attached client, which invalidates their entire render
- // surface -- a visible full-window flicker.
- let changed = *self.configured_palette.lock() != palette;
+ // Skip the send only when the SERVER is known to hold this exact
+ // palette. "The value didn't change locally" is not that: the
+ // initial advisory can be lost in attach races, and comparing
+ // against our own memory would then skip the correction forever —
+ // leaving the server answering OSC color queries from its bare
+ // defaults. Identical re-sends stay flicker-free because both the
+ // server and the receiving side de-duplicate them; the skip here
+ // only avoids per-config-bump RPC noise once delivery is confirmed.
+ let send = self.delivered_palette.lock().delivered.as_ref() != Some(&palette);
// If the application running in the pane hasn't changed the
// palette through escape sequences, speculatively adopt the
@@ -741,20 +903,13 @@ impl Pane for ClientPane {
}
*self.configured_palette.lock() = palette.clone();
- if changed {
- // and now send the color palette to the server
- let client = Arc::clone(&self.client);
- let remote_pane_id = self.remote_pane_id;
- promise::spawn::spawn(async move {
- client
- .client
- .set_configured_palette_for_pane(SetPalette {
- pane_id: remote_pane_id,
- palette,
- })
- .await
- })
- .detach();
+ if send {
+ Self::advise_server_palette(
+ Arc::clone(&self.client),
+ self.remote_pane_id,
+ palette,
+ Arc::clone(&self.delivered_palette),
+ );
}
self.config.lock().replace(config);
}
@@ -863,3 +1018,114 @@ mod test {
);
}
}
+
+#[cfg(test)]
+mod palette_delivery_tests {
+ use super::PaletteDelivery;
+ use wezterm_term::color::ColorPalette;
+
+ fn palette(fg: f32) -> ColorPalette {
+ let mut palette = ColorPalette::default();
+ palette.foreground = (fg, fg, fg, 1.0).into();
+ palette
+ }
+
+ #[test]
+ fn a_send_is_confirmed_and_the_worker_stops() {
+ let mut state = PaletteDelivery::default();
+ assert!(
+ state.adopt_target(palette(0.5)),
+ "first adopt starts a worker"
+ );
+ let sent = state.next_to_send().expect("something to send");
+ state.record_success(sent);
+ assert!(state.next_to_send().is_none(), "delivered == desired: done");
+ assert!(!state.sender_running, "the worker slot must be released");
+ }
+
+ /// The bug this design removes: a retry of an OLD palette must never be
+ /// the last thing the server hears. The worker always re-reads the
+ /// latest desired value, so a success for A while B is pending simply
+ /// leads to sending B next.
+ #[test]
+ fn a_stale_color_can_never_be_the_last_one_standing() {
+ let mut state = PaletteDelivery::default();
+ assert!(state.adopt_target(palette(0.1)));
+ let first = state.next_to_send().expect("A to send");
+
+ // B arrives while A's RPC is in flight: same worker, no new task.
+ assert!(!state.adopt_target(palette(0.9)), "worker already running");
+
+ state.record_success(first);
+ let second = state.next_to_send().expect("B still owed to the server");
+ assert_eq!(second, palette(0.9), "the newest target wins");
+ state.record_success(second);
+ assert!(state.next_to_send().is_none());
+ }
+
+ /// The retry path of the same bug: a send FAILS, and while the worker
+ /// waits to retry, a newer palette arrives. The retry must send the
+ /// newer palette — the failed old one is simply abandoned.
+ #[test]
+ fn a_retry_after_failure_sends_the_newest_target() {
+ let mut state = PaletteDelivery::default();
+ assert!(state.adopt_target(palette(0.1)));
+ let _failed = state.next_to_send().expect("A to send");
+ // The RPC for A fails: no record_success. B arrives during the
+ // retry backoff.
+ assert!(!state.adopt_target(palette(0.9)), "worker still running");
+ assert_eq!(
+ state.next_to_send(),
+ Some(palette(0.9)),
+ "the retry must carry the newest target, not replay the old one"
+ );
+ }
+
+ /// Give-up leaves delivery unconfirmed so the next advisory restarts a
+ /// worker rather than assuming the server heard us.
+ #[test]
+ fn giving_up_allows_a_later_restart_with_the_same_value() {
+ let mut state = PaletteDelivery::default();
+ assert!(state.adopt_target(palette(0.5)));
+ let _ = state.next_to_send().expect("initial send");
+ assert!(state.give_up_if_still_desired(&palette(0.5)));
+ assert!(
+ state.adopt_target(palette(0.5)),
+ "same value must restart the worker after a give-up"
+ );
+ assert_eq!(state.next_to_send(), Some(palette(0.5)));
+ }
+
+ /// A newer target arriving during the final failed RPC must keep the
+ /// worker alive; otherwise no caller remains to start delivery for it.
+ #[test]
+ fn giving_up_an_obsolete_target_keeps_the_worker_for_the_newest_value() {
+ let mut state = PaletteDelivery::default();
+ let old = palette(0.1);
+ let new = palette(0.9);
+ assert!(state.adopt_target(old.clone()));
+ assert_eq!(state.next_to_send(), Some(old.clone()));
+ assert!(!state.adopt_target(new.clone()));
+ assert!(!state.give_up_if_still_desired(&old));
+ assert!(state.sender_running);
+ assert_eq!(state.next_to_send(), Some(new));
+ }
+
+ /// A reconnect invalidates old confirmations: the server may be a fresh
+ /// process that never heard the palette we once delivered.
+ #[test]
+ fn a_reconnect_invalidates_the_confirmation() {
+ let mut state = PaletteDelivery::default();
+ assert!(state.adopt_target(palette(0.5)));
+ let sent = state.next_to_send().unwrap();
+ state.record_success(sent);
+ assert!(state.next_to_send().is_none());
+
+ state.invalidate_delivery();
+ assert!(
+ state.adopt_target(palette(0.5)),
+ "resync restarts the worker"
+ );
+ assert_eq!(state.next_to_send(), Some(palette(0.5)));
+ }
+}
diff --git a/wezterm-gui/src/frontend.rs b/wezterm-gui/src/frontend.rs
index e4c91543..61c0932d 100644
--- a/wezterm-gui/src/frontend.rs
+++ b/wezterm-gui/src/frontend.rs
@@ -31,6 +31,13 @@ pub struct GuiFrontEnd {
switching_workspaces: RefCell<usize>,
spawned_mux_window: RefCell<HashSet<MuxWindowId>>,
known_windows: RefCell<BTreeMap<Window, MuxWindowId>>,
+ /// Set when the LAST GUI window closed and we detached whatever client
+ /// domains were attached at that moment. A domain whose attach was still
+ /// in flight shows as Detached then, escapes that sweep, and completes
+ /// later — this flag lets the WindowCreated handler catch that late
+ /// arrival and finish the job instead of leaving an invisible process.
+ /// Cleared as soon as any GUI window exists again.
+ detach_when_windowless: std::cell::Cell<bool>,
client_id: Arc<ClientId>,
config_subscription: RefCell<Option<ConfigSubscription>>,
}
@@ -55,6 +62,7 @@ impl GuiFrontEnd {
switching_workspaces: RefCell::new(0),
spawned_mux_window: RefCell::new(HashSet::new()),
known_windows: RefCell::new(BTreeMap::new()),
+ detach_when_windowless: std::cell::Cell::new(false),
client_id: client_id.clone(),
config_subscription: RefCell::new(None),
});
@@ -78,6 +86,9 @@ impl GuiFrontEnd {
MuxNotification::WindowCreated(window_id) => {
promise::spawn::spawn_into_main_thread(async move {
let fe = crate::frontend::front_end();
+ if fe.reap_windowless_late_attach() {
+ return;
+ }
if fe.spawned_mux_window.borrow().contains(&window_id) {
return;
}
@@ -628,6 +639,8 @@ impl GuiFrontEnd {
}
pub fn record_known_window(&self, window: Window, mux_window_id: MuxWindowId) {
+ // A GUI window exists again: any pending last-window cleanup is moot.
+ self.detach_when_windowless.set(false);
// 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).
@@ -641,12 +654,64 @@ impl GuiFrontEnd {
}
pub fn forget_known_window(&self, window: &Window) {
- self.known_windows.borrow_mut().remove(window);
+ let now_empty = {
+ let mut windows = self.known_windows.borrow_mut();
+ windows.remove(window);
+ windows.is_empty()
+ };
+ // The last GUI window closing is the user's "I'm done": detach any
+ // client domains so their panes drop, the mux empties, and the Empty
+ // notification can actually terminate the process.
+ // Mux::remove_window_internal deliberately no longer detaches while
+ // other windows still reference a domain (deleting one thread must
+ // not sever the connection its siblings are using), so without this
+ // the background workspaces' panes would keep an invisible process
+ // alive after the last window is gone. Gated on the same setting
+ // that governs quitting, so a platform that idles without windows
+ // (macOS) also keeps its connections.
+ if now_empty && config::configuration().quit_when_all_windows_are_closed {
+ self.detach_attached_client_domains();
+ // A domain whose attach is still in flight shows as Detached and
+ // escapes the sweep above; remember to finish the job when its
+ // windows materialize (see the WindowCreated handler).
+ self.detach_when_windowless.set(true);
+ }
if !self.is_switching_workspace() {
self.reconcile_workspace();
}
}
+ fn detach_attached_client_domains(&self) {
+ let mux = Mux::get();
+ for domain in mux.iter_domains() {
+ if domain.detachable() && domain.state() == mux::domain::DomainState::Attached {
+ if let Err(err) = domain.detach() {
+ log::error!(
+ "while detaching domain {} after the last window closed: {err:#}",
+ domain.domain_name()
+ );
+ }
+ }
+ }
+ }
+
+ /// A mux window appeared while no GUI window exists and the last-window
+ /// cleanup already ran: this is a connection that was still attaching
+ /// when the user closed everything. Finish what forget_known_window
+ /// started rather than resurrecting an unwanted session. Returns true
+ /// when the event was consumed this way.
+ pub fn reap_windowless_late_attach(&self) -> bool {
+ if !self.detach_when_windowless.get() {
+ return false;
+ }
+ if !self.known_windows.borrow().is_empty() {
+ self.detach_when_windowless.set(false);
+ return false;
+ }
+ self.detach_attached_client_domains();
+ true
+ }
+
/// Re-point an existing GUI window at a different mux window. Used when a
/// window switches the Space it is showing in place, so that
/// `known_windows` stays accurate without relying on reconcile to rebuild
diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rs
index 20a4534b..657555d3 100644
--- a/wezterm-gui/src/termwindow/mod.rs
+++ b/wezterm-gui/src/termwindow/mod.rs
@@ -634,12 +634,46 @@ pub(crate) enum TabWheelSurface {
#[derive(Clone, Debug)]
struct FileDragState {
- path: PathBuf,
+ payload: FileDragPayload,
start: ::window::Point,
current: ::window::Point,
active: bool,
}
+/// What a Files-panel drag will paste once it lands on the terminal.
+#[derive(Clone, Debug)]
+enum FileDragPayload {
+ Local(PathBuf),
+ /// A remote path only means something together with the source it was
+ /// picked from — `/tmp/a` on host A is not the object `/tmp/a` names on
+ /// host B — so the drop revalidates that source before pasting.
+ Remote {
+ path: remote_files::RemotePath,
+ origin: remote_files::RemoteOperationOrigin,
+ },
+}
+
+impl FileDragPayload {
+ /// What the floating pill under the cursor says: the file's own name,
+ /// falling back to the whole path when there is no name to show.
+ fn label(&self) -> String {
+ match self {
+ Self::Local(path) => path
+ .file_name()
+ .map(|name| name.to_string_lossy().into_owned())
+ .unwrap_or_else(|| path.to_string_lossy().into_owned()),
+ Self::Remote { path, .. } => {
+ let name = path.file_name();
+ if name.is_empty() {
+ path.as_str().to_string()
+ } else {
+ name.to_string()
+ }
+ }
+ }
+ }
+}
+
/// A planned local copy held back until the user says what to do about files
/// that already exist at the destination.
pub(crate) struct PendingLocalCopy {
diff --git a/wezterm-gui/src/termwindow/mouseevent.rs b/wezterm-gui/src/termwindow/mouseevent.rs
index ba2bfcd3..fa9c44bb 100644
--- a/wezterm-gui/src/termwindow/mouseevent.rs
+++ b/wezterm-gui/src/termwindow/mouseevent.rs
@@ -1326,7 +1326,11 @@ impl super::TermWindow {
context.invalidate();
}
if completed_drag.as_ref().is_some_and(|(item, _)| {
- matches!(item.item_type, UIItemType::RightSidebarFileRow(_))
+ matches!(
+ item.item_type,
+ UIItemType::RightSidebarFileRow(_)
+ | UIItemType::RightSidebarRemoteFileRow(_)
+ )
}) {
if let Some(state) = self.right_sidebar_file_drag.take() {
if state.active {
@@ -1340,7 +1344,16 @@ impl super::TermWindow {
// press path did or the preview overlaps the
// terminal.
let previous_width = self.right_sidebar_width();
- self.open_right_sidebar_file_path(state.path);
+ match state.payload {
+ super::FileDragPayload::Local(path) => {
+ self.open_right_sidebar_file_path(path)
+ }
+ super::FileDragPayload::Remote { path, origin } => {
+ if self.remote_operation_origin_matches(&origin) {
+ self.open_right_sidebar_remote_file(path)
+ }
+ }
+ }
self.invalidate_or_reflow_right_sidebar(previous_width, context);
}
}
@@ -1946,10 +1959,12 @@ impl super::TermWindow {
self.drag_right_sidebar_file_row(item, start_event, event, context);
}
}
- UIItemType::RightSidebarRemoteFileRow(ref path)
- if self.is_renaming_sidebar_remote_file(path) =>
- {
- self.drag_right_sidebar_input_selection(item, start_event, event, context);
+ UIItemType::RightSidebarRemoteFileRow(ref path) => {
+ if self.is_renaming_sidebar_remote_file(path) {
+ self.drag_right_sidebar_input_selection(item, start_event, event, context);
+ } else {
+ self.drag_right_sidebar_file_row(item, start_event, event, context);
+ }
}
_ => {
log::error!("drag not implemented for {:?}", item);
@@ -2020,13 +2035,31 @@ impl super::TermWindow {
return;
};
- let mut text = self
- .config
- .quote_dropped_files
- .escape(&state.path.to_string_lossy());
- text.push(' ');
- if let Err(err) = pane.send_paste(&text) {
- log::error!("failed to paste dropped file path: {err:#}");
+ match state.payload {
+ super::FileDragPayload::Local(path) => {
+ let mut text = self
+ .config
+ .quote_dropped_files
+ .escape(&path.to_string_lossy());
+ text.push(' ');
+ if let Err(err) = pane.send_paste(&text) {
+ log::error!("failed to paste dropped file path: {err:#}");
+ }
+ }
+ super::FileDragPayload::Remote { path, origin } => {
+ // The tree this path was picked from has to still be the tree
+ // on screen: the same absolute path on another host names a
+ // different object, and a drag that outlived the switch has no
+ // way to know that. Cancelling silently matches a drop onto
+ // any other piece of chrome.
+ if !self.remote_operation_origin_matches_pane(&origin, pane.pane_id()) {
+ return;
+ }
+ // POSIX-quoted regardless of `quote_dropped_files` — that
+ // setting is about the local shell, and this path is on a
+ // server by construction.
+ self.paste_remote_path_to_pane(pane.pane_id(), &path);
+ }
}
}
@@ -3570,7 +3603,7 @@ impl super::TermWindow {
// If the pointer never crosses the threshold, the release
// handler treats it as a click and opens the file.
self.right_sidebar_file_drag = Some(super::FileDragState {
- path,
+ payload: super::FileDragPayload::Local(path),
start: event.coords,
current: event.coords,
active: false,
@@ -3670,7 +3703,26 @@ impl super::TermWindow {
context.invalidate();
return;
}
- self.open_right_sidebar_remote_file(path.clone());
+ // Don't open yet: arm a potential drag toward the terminal,
+ // exactly like the local rows. The release handler opens the
+ // row when the pointer never crossed the threshold. Without a
+ // source to pin the path to there is nothing safe to drag, so
+ // fall back to opening on press.
+ match self.current_remote_operation_origin() {
+ Some(origin) => {
+ self.right_sidebar_file_drag = Some(super::FileDragState {
+ payload: super::FileDragPayload::Remote {
+ path: path.clone(),
+ origin,
+ },
+ start: event.coords,
+ current: event.coords,
+ active: false,
+ });
+ self.dragging.replace((item.clone(), event));
+ }
+ None => self.open_right_sidebar_remote_file(path.clone()),
+ }
}
UIItemType::RightSidebarRemoteFileBack => {
self.close_right_sidebar_remote_file_preview();
diff --git a/wezterm-gui/src/termwindow/remote_files.rs b/wezterm-gui/src/termwindow/remote_files.rs
index 65e35838..ed3d7291 100644
--- a/wezterm-gui/src/termwindow/remote_files.rs
+++ b/wezterm-gui/src/termwindow/remote_files.rs
@@ -506,18 +506,33 @@ fn sanitized_download_name(file_name: &str) -> &str {
.unwrap_or("download")
}
+/// Where a name's extension begins, for collision numbering. The LAST dot,
+/// not the first: dots inside a stem are ordinary characters (a macOS
+/// screenshot is `… at 12.50.59 PM.png`, and numbering it at the first dot
+/// produced `… at 12 (1).50.59 PM.png` — verified live). Known compound
+/// archive extensions are the exception and stay whole; a leading dot is a
+/// hidden file, not an extension.
+fn extension_split_index(name: &str) -> usize {
+ const COMPOUND: &[&str] = &[".tar.gz", ".tar.bz2", ".tar.xz", ".tar.zst"];
+ let lower = name.to_ascii_lowercase();
+ for suffix in COMPOUND {
+ if lower.ends_with(suffix) && name.len() > suffix.len() {
+ return name.len() - suffix.len();
+ }
+ }
+ match name.rfind('.') {
+ Some(0) | None => name.len(),
+ Some(index) => index,
+ }
+}
+
/// The names a download will try, in order: the file's own name, then
/// ` (1)`, ` (2)`… inserted before the extension the way a browser does.
///
/// Pure, so the naming rule is testable without a filesystem.
pub(crate) fn download_name_candidates(file_name: &str) -> impl Iterator<Item = String> + '_ {
let sanitized = sanitized_download_name(file_name);
- // Split at the *first* dot after the stem so `tar.gz` survives whole; a
- // leading dot is a hidden file, not an extension.
- let (stem, extension) = match sanitized.find('.') {
- Some(0) | None => (sanitized, ""),
- Some(index) => (&sanitized[..index], &sanitized[index..]),
- };
+ let (stem, extension) = sanitized.split_at(extension_split_index(sanitized));
std::iter::once(sanitized.to_string()).chain(
(1..=DOWNLOAD_NAME_ATTEMPTS).map(move |suffix| format!("{stem} ({suffix}){extension}")),
)
@@ -3639,6 +3654,18 @@ mod tests {
let mut names = download_name_candidates(".bashrc");
assert_eq!(names.next().as_deref(), Some(".bashrc"));
assert_eq!(names.next().as_deref(), Some(".bashrc (1)"));
+
+ // Dots inside a stem are ordinary characters: a macOS screenshot must
+ // number before `.png`, not in the middle of its timestamp.
+ let mut names = download_name_candidates("Screenshot 2026-07-31 at 12.50.59 PM.png");
+ names.next();
+ assert_eq!(
+ names.next().as_deref(),
+ Some("Screenshot 2026-07-31 at 12.50.59 PM (1).png")
+ );
+ let mut names = download_name_candidates("no-extension");
+ names.next();
+ assert_eq!(names.next().as_deref(), Some("no-extension (1)"));
}
/// A folder keeps its dots: the file rule would turn `my.folder` into
diff --git a/wezterm-gui/src/termwindow/render/paint.rs b/wezterm-gui/src/termwindow/render/paint.rs
index 3a3b9eb4..69f778c9 100644
--- a/wezterm-gui/src/termwindow/render/paint.rs
+++ b/wezterm-gui/src/termwindow/render/paint.rs
@@ -375,11 +375,7 @@ impl crate::TermWindow {
if !state.active {
return Ok(());
}
- let label = state
- .path
- .file_name()
- .map(|name| name.to_string_lossy().into_owned())
- .unwrap_or_else(|| state.path.to_string_lossy().into_owned());
+ let label = state.payload.label();
let anchor = state.current;
self.paint_drag_ghost_pill(&label, anchor)
}
diff --git a/wezterm-gui/src/termwindow/ui/right_sidebar.rs b/wezterm-gui/src/termwindow/ui/right_sidebar.rs
index d8b70a64..8efa0cc8 100644
--- a/wezterm-gui/src/termwindow/ui/right_sidebar.rs
+++ b/wezterm-gui/src/termwindow/ui/right_sidebar.rs
@@ -10030,6 +10030,16 @@ impl crate::TermWindow {
let Some(pane) = self.get_active_pane_or_overlay() else {
return false;
};
+ // The paste target must live on the SAME host the upload goes to.
+ // The Space being remote is not enough: the active pane can be a
+ // local overlay (the debug pane), or in principle belong to another
+ // domain entirely — pasting host A's path there would name nothing.
+ // Anything that does not match falls back to the local-path paste.
+ // (A mosh thread's pane is a local domain running mosh-client, so
+ // mosh Spaces deliberately keep the old behavior for now.)
+ if !pane_domain_matches_remote_source(pane.domain_id(), &target.source) {
+ return false;
+ }
let pane_id = pane.pane_id();
// Align the panel's state machine with this Space's target (idempotent
// when it already matches): every origin check downstream reads the
@@ -12264,6 +12274,27 @@ impl crate::TermWindow {
)
}
+ /// In addition to the Files panel still showing the same connection,
+ /// require the terminal receiving a dragged remote path to belong to that
+ /// host. A window may contain a local overlay or panes from another
+ /// domain, where the same absolute path would name a different object.
+ pub(crate) fn remote_operation_origin_matches_pane(
+ &self,
+ origin: &RemoteOperationOrigin,
+ pane_id: PaneId,
+ ) -> bool {
+ if !self.remote_operation_origin_matches(origin) {
+ return false;
+ }
+ let Some(target) = self.right_sidebar_remote_files.target.as_ref() else {
+ return false;
+ };
+ let Some(pane) = Mux::get().get_pane(pane_id) else {
+ return false;
+ };
+ pane_domain_matches_remote_source(pane.domain_id(), &target.source)
+ }
+
/// Drop the panel lease only if it is the exact connection that failed.
/// A delayed callback from host A must not disconnect host B, nor a newer
/// replacement connection for A.
@@ -16013,6 +16044,27 @@ fn display_name(path: &Path) -> String {
.unwrap_or_else(|| path.display().to_string())
}
+/// Whether the pane at `domain_id` is a session on the same host that
+/// `source` uploads to — a ClientDomain of the same name, or the SSH domain
+/// registered for the same saved host.
+fn pane_domain_matches_remote_source(
+ domain_id: mux::domain::DomainId,
+ source: &workspace_threads::RemoteFilesSource,
+) -> bool {
+ let Some(domain) = Mux::get().get_domain(domain_id) else {
+ return false;
+ };
+ let name = domain.domain_name();
+ match source {
+ workspace_threads::RemoteFilesSource::ClientDomain(client) => name == client,
+ workspace_threads::RemoteFilesSource::SshHost(host_id) => {
+ crate::ssh_hosts::host_spec(host_id)
+ .map(|spec| crate::ssh_hosts::ssh_domain_name(&spec) == name)
+ .unwrap_or(false)
+ }
+ }
+}
+
/// Where a terminal drop should upload, given the setting and (when the
/// setting asks for it) the pane's reported working directory. Pure, so the
/// fallback rules stay testable: `cwd` without a usable cwd must degrade to