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
Fix remote pane move synchronization
RoversX51513912326a
diff --git a/mux/src/domain.rs b/mux/src/domain.rsindex 1cdf543e..5200a619 100644--- a/mux/src/domain.rs+++ b/mux/src/domain.rs@@ -84,6 +84,10 @@ pub trait Domain: Downcast + Send + Sync {None => anyhow::bail!("Invalid tab id {}", tab),};+ if let SplitSource::MovePane(src_pane_id) = &source {+ return mux.move_pane_to_split(*src_pane_id, tab.tab_id(), pane_id, split_request);+ }+let pane_index = match tab.pane_index_for_pane(pane_id) {Some(index) => index,None => anyhow::bail!("invalid pane id {}", pane_id),@@ -94,7 +98,6 @@ pub trait Domain: Downcast + Send + Sync {None => anyhow::bail!("invalid pane index {}", pane_index),};- let moved_existing_pane = matches!(&source, SplitSource::MovePane(_));let pane = match source {SplitSource::Spawn {command,@@ -103,47 +106,10 @@ pub trait Domain: Downcast + Send + Sync {self.spawn_pane(split_size.second, command, command_dir).await?}- SplitSource::MovePane(src_pane_id) => {- let (_domain, _window, src_tab) = mux- .resolve_pane_id(src_pane_id)- .ok_or_else(|| anyhow::anyhow!("pane {} not found", src_pane_id))?;- let src_tab = match mux.get_tab(src_tab) {- Some(t) => t,- None => anyhow::bail!("Invalid tab id {}", src_tab),- };-- let pane = src_tab.remove_pane(src_pane_id).ok_or_else(|| {- anyhow::anyhow!("pane {} not found in its containing tab!?", src_pane_id)- })?;-- if src_tab.is_dead() {- mux.remove_tab(src_tab.tab_id());- }-- pane- }- };-- // pane_index may have changed if src_pane was also in the same tab- let final_pane_index = match tab.pane_index_for_pane(pane_id) {- Some(index) => index,- None => {- if moved_existing_pane {- tab.rehome_orphan_pane(&pane);- }- anyhow::bail!("invalid pane id {}", pane_id);- }+ SplitSource::MovePane(_) => unreachable!("MovePane handled above"),};- if let Err(err) = tab.split_and_insert(final_pane_index, split_request, Arc::clone(&pane))- {- // A moved pane was already detached from its tab; never let a- // failed insertion leave it orphaned.- if moved_existing_pane {- tab.rehome_orphan_pane(&pane);- }- return Err(err);- }+ tab.split_and_insert(pane_index, split_request, Arc::clone(&pane))?;Ok(pane)}diff --git a/mux/src/lib.rs b/mux/src/lib.rsindex f0959cba..63598cfb 100644--- a/mux/src/lib.rs+++ b/mux/src/lib.rs@@ -1269,6 +1269,67 @@ impl Mux {})}+ /// Move an already-registered pane into a new split without ever+ /// leaving it detached if the insertion fails.+ pub fn move_pane_to_split(+ &self,+ src_pane_id: PaneId,+ target_tab_id: TabId,+ target_pane_id: PaneId,+ request: SplitRequest,+ ) -> anyhow::Result<Arc<dyn Pane>> {+ if src_pane_id == target_pane_id {+ anyhow::bail!("cannot split pane {src_pane_id} relative to itself");+ }++ let target_tab = self+ .get_tab(target_tab_id)+ .ok_or_else(|| anyhow!("tab_id {target_tab_id} is invalid"))?;+ let target_index = target_tab+ .pane_index_for_pane(target_pane_id)+ .ok_or_else(|| anyhow!("pane_id {target_pane_id} is not in tab {target_tab_id}"))?;+ target_tab+ .validate_split_request(target_index, request)+ .with_context(|| format!("cannot split pane {target_pane_id}"))?;++ // This is a local topology primitive and does not require either tab+ // to be attached to a window yet.+ let src_tab = self+ .tabs+ .read()+ .values()+ .find(|tab| tab.pane_index_for_pane(src_pane_id).is_some())+ .cloned()+ .ok_or_else(|| anyhow!("pane {src_pane_id} not found in any tab"))?;+ let src_tab_id = src_tab.tab_id();+ let pane = src_tab.remove_pane(src_pane_id).ok_or_else(|| {+ anyhow!("pane {src_pane_id} not found in its containing tab {src_tab_id}")+ })?;++ // Removing a pane can renumber the destination leaves when source+ // and target are in the same tab.+ let final_target_index = match target_tab.pane_index_for_pane(target_pane_id) {+ Some(index) => index,+ None => {+ src_tab.rehome_orphan_pane(&pane);+ anyhow::bail!("target pane {target_pane_id} vanished while moving pane");+ }+ };++ if let Err(err) =+ target_tab.split_and_insert(final_target_index, request, Arc::clone(&pane))+ {+ src_tab.rehome_orphan_pane(&pane);+ return Err(err);+ }++ if src_tab.is_dead() {+ self.remove_tab(src_tab_id);+ }++ Ok(pane)+ }+pub async fn split_pane(&self,// TODO: disambiguate with TabId@@ -1311,6 +1372,10 @@ impl Mux {};let pane = domain.split_pane(source, tab_id, pane_id, request).await?;+ // A moved pane is already registered, so PaneAdded cannot advertise+ // the changed tree to mux clients. Always publish the structural+ // mutation; clients coalesce it into an authoritative resync.+ self.notify(MuxNotification::TabResized(tab_id));if let Some(config) = term_config {pane.set_config(config);}diff --git a/mux/src/tab.rs b/mux/src/tab.rsindex a996ac8b..b6062017 100644--- a/mux/src/tab.rs+++ b/mux/src/tab.rs@@ -1130,6 +1130,27 @@ impl Tab {self.inner.lock().compute_split_size(pane_index, request)}+ pub fn validate_split_request(+ &self,+ pane_index: usize,+ request: SplitRequest,+ ) -> anyhow::Result<()> {+ let split = self+ .compute_split_size(pane_index, request)+ .ok_or_else(|| anyhow::anyhow!("invalid pane index {pane_index}"))?;+ let tab_size = self.get_size();+ if split.first.rows == 0+ || split.first.cols == 0+ || split.second.rows == 0+ || split.second.cols == 0+ || split.top_of_second() + split.second.rows > tab_size.rows+ || split.left_of_second() + split.second.cols > tab_size.cols+ {+ anyhow::bail!("no space for split");+ }+ Ok(())+ }+/// Split the pane that has pane_index in the given direction and assign/// the right/bottom pane of the newly created split to the provided Pane/// instance. Returns the resultant index of the newly inserted pane.@@ -4007,6 +4028,111 @@ mod test {assert_eq!(tab.get_active_pane().unwrap().pane_id(), 2);}+ #[test]+ fn mux_move_pane_to_split_reuses_registered_pane() {+ let _guard = install_mux();+ let mux = Mux::get();+ let size = test_size();++ let src_tab = Arc::new(Tab::new(&size));+ let src = FakePane::new(10_001, size);+ src_tab.assign_pane(&src);+ mux.add_tab_no_panes(&src_tab);+ mux.add_pane(&src).unwrap();++ let target_tab = Arc::new(Tab::new(&size));+ let target = FakePane::new(10_002, size);+ target_tab.assign_pane(&target);+ mux.add_tab_no_panes(&target_tab);+ mux.add_pane(&target).unwrap();++ let moved = mux+ .move_pane_to_split(+ src.pane_id(),+ target_tab.tab_id(),+ target.pane_id(),+ SplitRequest::default(),+ )+ .unwrap();++ assert_eq!(moved.pane_id(), src.pane_id());+ let src_dyn: Arc<dyn Pane> = src.clone();+ assert!(Arc::ptr_eq(&moved, &src_dyn));+ assert!(mux.get_tab(src_tab.tab_id()).is_none());+ assert_eq!(target_tab.count_panes(), Some(2));+ assert!(target_tab.pane_index_for_pane(src.pane_id()).is_some());+ assert_eq!(+ mux.get_pane(src.pane_id()).unwrap().pane_id(),+ src.pane_id()+ );+ }++ #[test]+ fn mux_move_pane_to_split_recomputes_same_tab_target() {+ let _guard = install_mux();+ let mux = Mux::get();+ let size = test_size();++ let tab = Arc::new(Tab::new(&size));+ let target = FakePane::new(10_021, size);+ let src = FakePane::new(10_022, size);+ tab.assign_pane(&target);+ tab.add_pane_to_stack(target.pane_id(), Arc::clone(&src))+ .unwrap();+ mux.add_tab_no_panes(&tab);+ mux.add_pane(&target).unwrap();+ mux.add_pane(&src).unwrap();++ let moved = mux+ .move_pane_to_split(+ src.pane_id(),+ tab.tab_id(),+ target.pane_id(),+ SplitRequest::default(),+ )+ .unwrap();++ assert_eq!(moved.pane_id(), src.pane_id());+ assert_eq!(tab.count_panes(), Some(2));+ assert_eq!(tab.iter_panes().len(), 2);+ assert!(tab.pane_index_for_pane(target.pane_id()).is_some());+ assert!(tab.pane_index_for_pane(src.pane_id()).is_some());+ }++ #[test]+ fn mux_move_pane_to_split_preflight_keeps_source_attached() {+ let _guard = install_mux();+ let mux = Mux::get();+ let size = test_size();++ let src_tab = Arc::new(Tab::new(&size));+ let src = FakePane::new(10_011, size);+ src_tab.assign_pane(&src);+ mux.add_tab_no_panes(&src_tab);+ mux.add_pane(&src).unwrap();++ let tiny_size = TerminalSize { cols: 1, ..size };+ let target_tab = Arc::new(Tab::new(&tiny_size));+ let target = FakePane::new(10_012, tiny_size);+ target_tab.assign_pane(&target);+ mux.add_tab_no_panes(&target_tab);+ mux.add_pane(&target).unwrap();++ assert!(mux+ .move_pane_to_split(+ src.pane_id(),+ target_tab.tab_id(),+ target.pane_id(),+ SplitRequest::default(),+ )+ .is_err());++ assert!(mux.get_tab(src_tab.tab_id()).is_some());+ assert!(src_tab.pane_index_for_pane(src.pane_id()).is_some());+ assert_eq!(src_tab.count_panes(), Some(1));+ assert_eq!(target_tab.count_panes(), Some(1));+ }+/// Regression for the same-stack edge drop: dragging the active pane B/// out of a stack [A, B] to a split edge must target A (not B itself),/// and both panes must remain reachable as two splits afterwards.diff --git a/wezterm-client/src/domain.rs b/wezterm-client/src/domain.rsindex b299aeb6..21cce632 100644--- a/wezterm-client/src/domain.rs+++ b/wezterm-client/src/domain.rs@@ -1,6 +1,6 @@use crate::client::Client;use crate::pane::ClientPane;-use anyhow::{anyhow, bail};+use anyhow::{anyhow, bail, Context};use async_trait::async_trait;use codec::{ListPanesResponse, SpawnV2, SplitPane};use config::keyassignment::SpawnTabDomain;@@ -82,6 +82,32 @@ impl Drop for StructureMutationGuard {}}+fn remote_move_pane_id(+ target_local_pane_id: PaneId,+ target_remote_pane_id: PaneId,+ source_local_pane_id: PaneId,+ source_remote_pane_id: PaneId,+ expected_domain_id: DomainId,+ source_domain_id: DomainId,+) -> anyhow::Result<PaneId> {+ if source_local_pane_id == target_local_pane_id {+ bail!("cannot split pane {source_local_pane_id} relative to itself");+ }+ if source_domain_id != expected_domain_id {+ bail!(+ "cannot move pane {source_local_pane_id} from domain {source_domain_id} \+ into domain {expected_domain_id}"+ );+ }+ if source_remote_pane_id == target_remote_pane_id {+ bail!(+ "local panes {source_local_pane_id} and {target_local_pane_id} \+ both refer to remote pane {source_remote_pane_id}"+ );+ }+ Ok(source_remote_pane_id)+}+impl ClientInner {fn remote_to_local_window(&self, remote_window_id: WindowId) -> Option<WindowId> {let map = self.remote_to_local_window.lock().unwrap();@@ -751,7 +777,12 @@ impl ClientDomain {remote_panes_to_forget.remove(&entry.pane_id);if let Some(pane_id) = inner.remote_to_local_pane_id(entry.pane_id) {match mux.get_pane(pane_id) {- Some(pane) => pane,+ Some(pane) => {+ if let Some(client_pane) = pane.downcast_ref::<ClientPane>() {+ client_pane.set_remote_tab_id(entry.tab_id);+ }+ pane+ }None => {// We likely decided that we hit EOF on the tab and// removed it from the mux. Let's add it back, but@@ -938,6 +969,27 @@ impl ClientDomain {}}+#[cfg(test)]+mod tests {+ use super::remote_move_pane_id;++ #[test]+ fn remote_move_uses_the_remote_source_id() {+ assert_eq!(remote_move_pane_id(41, 901, 42, 7, 3, 3).unwrap(), 7);+ }++ #[test]+ fn remote_move_rejects_self_and_cross_domain_moves() {+ assert!(remote_move_pane_id(42, 901, 42, 7, 3, 3).is_err());+ assert!(remote_move_pane_id(41, 901, 42, 7, 3, 4).is_err());+ }++ #[test]+ fn remote_move_rejects_duplicate_local_mirrors() {+ assert!(remote_move_pane_id(41, 7, 42, 7, 3, 3).is_err());+ }+}+#[async_trait(?Send)]impl Domain for ClientDomain {fn domain_id(&self) -> DomainId {@@ -1141,20 +1193,58 @@ impl Domain for ClientDomain {let pane = local_pane.downcast_ref::<ClientPane>().ok_or_else(|| anyhow!("pane_id {} is not a ClientPane", pane_id))?;+ if !pane.belongs_to_client(&inner) {+ bail!("pane_id {pane_id} belongs to a stale client connection");+ }+ let target_remote_pane_id = pane.remote_pane_id();- let (command, command_dir, move_pane_id) = match source {+ let (command, command_dir, move_pane_id, moved_local_pane) = match source {SplitSource::Spawn {command,command_dir,- } => (command, command_dir, None),- SplitSource::MovePane(move_pane_id) => (None, None, Some(move_pane_id)),+ } => (command, command_dir, None, None),+ SplitSource::MovePane(source_local_pane_id) => {+ let source_pane = mux+ .get_pane(source_local_pane_id)+ .ok_or_else(|| anyhow!("source pane_id {source_local_pane_id} is invalid"))?;+ let source_client_pane =+ source_pane.downcast_ref::<ClientPane>().ok_or_else(|| {+ anyhow!("source pane_id {source_local_pane_id} is not a ClientPane")+ })?;+ if !source_client_pane.belongs_to_client(&inner) {+ bail!(+ "source pane_id {source_local_pane_id} belongs to a different client connection"+ );+ }+ let remote_source_pane_id = remote_move_pane_id(+ pane_id,+ target_remote_pane_id,+ source_local_pane_id,+ source_client_pane.remote_pane_id(),+ inner.local_domain_id,+ source_pane.domain_id(),+ )?;++ let target_index = tab+ .pane_index_for_pane(pane_id)+ .ok_or_else(|| anyhow!("pane_id {pane_id} is not in tab {tab_id}"))?;+ tab.validate_split_request(target_index, split_request)+ .context("remote MovePane split preflight failed")?;++ (+ None,+ None,+ Some(remote_source_pane_id),+ Some((source_pane, remote_source_pane_id)),+ )+ }};let result = inner.client.split_pane(SplitPane {domain: SpawnTabDomain::CurrentPaneDomain,- pane_id: pane.remote_pane_id,+ pane_id: target_remote_pane_id,split_request,command,command_dir,@@ -1162,6 +1252,40 @@ impl Domain for ClientDomain {}).await?;+ if let Some((moved_pane, expected_remote_pane_id)) = moved_local_pane {+ // The server must return the identity of the pane that it moved.+ // Treat anything else as a protocol/topology mismatch rather+ // than creating a second local mirror for that remote pane.+ if result.pane_id != expected_remote_pane_id {+ inner.defer_resync();+ bail!(+ "remote MovePane returned pane {}, expected {}",+ result.pane_id,+ expected_remote_pane_id+ );+ }++ let moved_client_pane = moved_pane+ .downcast_ref::<ClientPane>()+ .expect("MovePane source was validated as ClientPane");+ moved_client_pane.set_remote_tab_id(result.tab_id);++ if let Err(err) =+ mux.move_pane_to_split(moved_pane.pane_id(), tab_id, pane_id, split_request)+ {+ // The server has already committed the move. The mux helper+ // guarantees that the local pane remains attached; force an+ // authoritative tree sync to converge on the remote result.+ inner.defer_resync();+ return Err(err).context("mirroring remote MovePane locally");+ }++ // Always converge with the server tree after the optimistic+ // local update, even if its TabResized notification was delayed.+ inner.defer_resync();+ return Ok(moved_pane);+ }+let pane: Arc<dyn Pane> = Arc::new(ClientPane::new(&inner,result.tab_id,@@ -1179,8 +1303,10 @@ impl Domain for ClientDomain {None => anyhow::bail!("invalid pane id {}", pane_id),};- tab.split_and_insert(pane_index, split_request, Arc::clone(&pane))- .ok();+ if let Err(err) = tab.split_and_insert(pane_index, split_request, Arc::clone(&pane)) {+ inner.defer_resync();+ return Err(err).context("mirroring remote split locally");+ }mux.add_pane(&pane)?;diff --git a/wezterm-client/src/pane/clientpane.rs b/wezterm-client/src/pane/clientpane.rsindex 007a72e9..a70b6493 100644--- a/wezterm-client/src/pane/clientpane.rs+++ b/wezterm-client/src/pane/clientpane.rs@@ -20,6 +20,7 @@ use ratelim::RateLimiter;use std::cell::RefCell;use std::collections::{BTreeMap, HashMap};use std::ops::Range;+use std::sync::atomic::{AtomicUsize, Ordering};use std::sync::Arc;use termwiz::input::KeyEvent;use termwiz::surface::SequenceNo;@@ -35,7 +36,7 @@ pub struct ClientPane {client: Arc<ClientInner>,local_pane_id: PaneId,pub remote_pane_id: PaneId,- pub remote_tab_id: TabId,+ remote_tab_id: AtomicUsize,pub renderable: Mutex<RenderableState>,configured_palette: Mutex<ColorPalette>,palette: Mutex<ColorPalette>,@@ -119,7 +120,7 @@ impl ClientPane {mouse,remote_pane_id,local_pane_id,- remote_tab_id,+ remote_tab_id: AtomicUsize::new(remote_tab_id),application_palette: Mutex::new(false),renderable: Mutex::new(render),writer: Mutex::new(writer),@@ -265,10 +266,22 @@ impl ClientPane {Ok(())}- pub fn remote_pane_id(&self) -> TabId {+ pub fn remote_pane_id(&self) -> PaneId {self.remote_pane_id}+ pub fn remote_tab_id(&self) -> TabId {+ self.remote_tab_id.load(Ordering::Relaxed)+ }++ pub(crate) fn set_remote_tab_id(&self, remote_tab_id: TabId) {+ self.remote_tab_id.store(remote_tab_id, Ordering::Relaxed);+ }++ pub(crate) fn belongs_to_client(&self, client: &Arc<ClientInner>) -> bool {+ Arc::ptr_eq(&self.client, client)+ }+/// Ask the server to make this pane the visible (active) pane of the/// stack that contains it, mirroring a local level-2 tab switch. Without/// this, the next resync would flip the local stack back to the server's@@ -419,7 +432,7 @@ impl Pane for ClientPane {let mut inner = render.inner.borrow_mut();let client = Arc::clone(&self.client);let remote_pane_id = self.remote_pane_id;- let remote_tab_id = self.remote_tab_id;+ let remote_tab_id = self.remote_tab_id();// Invalidate any cached rows on a resizeinner.make_all_stale();promise::spawn::spawn(async move {@@ -473,7 +486,7 @@ impl Pane for ClientPane {let client = Arc::clone(&self.client);let remote_pane_id = self.remote_pane_id;- let remote_tab_id = self.remote_tab_id;+ let remote_tab_id = self.remote_tab_id();promise::spawn::spawn(async move {client.clientdiff --git a/wezterm-gui/src/termwindow/mouseevent.rs b/wezterm-gui/src/termwindow/mouseevent.rsindex 66aaf288..f9c2de2f 100644--- a/wezterm-gui/src/termwindow/mouseevent.rs+++ b/wezterm-gui/src/termwindow/mouseevent.rs@@ -26,7 +26,7 @@ use mux::pane::{Pane, WithPaneLines};use mux::ssh::{RemoteSshDomain, SshConnectionStatus};use mux::tab::{PositionedPane, SplitDirection};use mux::window::WindowId as MuxWindowId;-use mux::{Mux, MuxNotification};+use mux::Mux;use mux_lua::MuxPane;use std::convert::TryInto;use std::ops::Sub;@@ -1942,16 +1942,10 @@ impl super::TermWindow {}/// Whether a pane can participate in a drag move/split. Remote mux- /// panes are excluded because the client's SplitPane move path does- /// not translate pane ids yet; tmux panes because the tmux domain- /// ignores SplitSource::MovePane and would spawn instead.+ /// panes are supported by ClientDomain's translated MovePane path;+ /// tmux panes remain excluded because that domain ignores+ /// SplitSource::MovePane and would spawn instead.fn pane_tab_is_movable(pane: &Arc<dyn Pane>) -> bool {- if pane- .downcast_ref::<wezterm_client::pane::ClientPane>()- .is_some()- {- return false;- }if let Some(domain) = Mux::get().get_domain(pane.domain_id()) {if domain.downcast_ref::<mux::tmux::TmuxDomain>().is_some() {return false;@@ -2202,13 +2196,8 @@ impl super::TermWindow {.await{Ok((moved, _size)) => {- // MovePane reuses an already-registered pane, so- // observers get no PaneAdded; tell them the tab's- // structure changed.- Mux::get().notify(MuxNotification::TabResized(dest_tab_id));- window- .window- .notify(TermWindowNotif::Apply(Box::new(move |term_window| {+ window.window.notify(TermWindowNotif::Apply(Box::new(+ move |term_window| {// Look up the destination tab by id: the// window's active tab may have changed// while the split was in flight.@@ -2228,7 +2217,8 @@ impl super::TermWindow {if let Some(window) = term_window.window.as_ref() {window.invalidate();}- })));+ },+ )));}Err(err) => log::error!("pane tab drop split failed: {err:#}"),}