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(ssh): keep a server's Spaces when it is reached under another name

RoversX997266b8f5ae
diff --git a/wezterm-gui/src/frontend.rs b/wezterm-gui/src/frontend.rs
index 558c4cb3..b3b345ba 100644
--- a/wezterm-gui/src/frontend.rs
+++ b/wezterm-gui/src/frontend.rs
@@ -683,7 +683,7 @@ impl GuiFrontEnd {
}
let mux = Mux::get();
- let (is_domain_owned, is_host, window_workspace) = {
+ let (is_domain_owned, is_host, window_workspace, origin_name) = {
let Some(mux_window) = mux.get_window(mux_window_id) else {
continue;
};
@@ -697,6 +697,10 @@ impl GuiFrontEnd {
.origin_domain()
.is_some_and(crate::local_sessions::is_host_domain_id),
mux_window.get_workspace().to_string(),
+ mux_window
+ .origin_domain()
+ .and_then(|id| mux.get_domain(id))
+ .map(|domain| domain.domain_name().to_string()),
)
};
// `get_window` holds a read guard for the mux's complete
@@ -727,6 +731,27 @@ impl GuiFrontEnd {
);
continue;
}
+ // A server's thread window has a Space of its own to show.
+ // Arriving through a second connection to the same server, it
+ // is a copy of one the Space's own connection shows already.
+ let home = match origin_name.as_deref() {
+ Some(name) if is_domain_owned => {
+ crate::workspace_threads::server_thread_window_home(
+ &window_workspace,
+ name,
+ )
+ }
+ _ => crate::workspace_threads::ServerThreadWindowHome::Unknown,
+ };
+ if home == crate::workspace_threads::ServerThreadWindowHome::OtherConnection {
+ log::debug!(
+ "reconcile: leaving window {} in workspace {:?} hidden: its Space \
+ is shown through another connection",
+ mux_window_id,
+ window_workspace,
+ );
+ continue;
+ }
front_end()
.spawned_mux_window
@@ -739,7 +764,29 @@ impl GuiFrontEnd {
// the one the domain just created (killing e.g. the in-window
// ConnectionUI mid-authentication).
let created = if is_domain_owned {
- TermWindow::new_window_without_restore(mux_window_id).await
+ // On the thread's own Space when no window shows it, not
+ // whichever local Space happens to be free.
+ let owner = crate::workspace_threads::next_space_owner_id();
+ match home {
+ crate::workspace_threads::ServerThreadWindowHome::Space(space_id)
+ if crate::workspace_threads::claim_free_space_for_window(
+ owner, &space_id,
+ ) =>
+ {
+ let created = TermWindow::new_window_with_claimed_space(
+ mux_window_id,
+ owner,
+ space_id,
+ None,
+ )
+ .await;
+ if created.is_err() {
+ crate::workspace_threads::release_window_space(owner);
+ }
+ created
+ }
+ _ => TermWindow::new_window_without_restore(mux_window_id).await,
+ }
} else {
TermWindow::new_window(mux_window_id).await
};
diff --git a/wezterm-gui/src/main.rs b/wezterm-gui/src/main.rs
index 01a22814..c180e663 100644
--- a/wezterm-gui/src/main.rs
+++ b/wezterm-gui/src/main.rs
@@ -674,6 +674,9 @@ pub(crate) async fn connect_domain_into_space(
// Already attached in this process: focus one of this domain's windows.
if domain.state() == DomainState::Attached {
+ // The plan above may have added a row here that the server has not
+ // seen; nothing after this point would tell it.
+ workspace_threads::reconcile_remote_subtree(&domain_name);
for window_id in mux.iter_windows() {
let owned = mux
.get_window(window_id)
@@ -716,6 +719,17 @@ pub(crate) async fn connect_domain_into_space(
return Ok(());
}
}
+ // On screen in a window showing none of this connection: it was not
+ // connected, or the host was renamed or moved to the other network
+ // and this is the name it goes by now. Connect it there.
+ if let Some(holder) = workspace_threads::window_owner_for_space(&plan.space_id) {
+ for gui_window in crate::frontend::front_end().gui_windows() {
+ gui_window.window.notify(crate::termwindow::TermWindowNotif::Apply(Box::new(
+ move |tw| tw.open_space_if_held_by(holder),
+ )));
+ }
+ return Ok(());
+ }
anyhow::bail!(
"Space for domain {domain_name} is occupied by another window; \
switch to it instead"
@@ -860,6 +874,7 @@ pub(crate) async fn connect_domain_into_space(
let client = domain
.downcast_ref::<ClientDomain>()
.ok_or_else(|| anyhow!("{domain_name} is not a multiplexing client domain"))?;
+ workspace_threads::put_thread_on_server(&domain_name, &settled.thread_id).await;
crate::frontend::front_end().set_switching_workspaces(true);
let ensured = client
.ensure_thinkterm_thread(Some(settled.thread_id.clone()), size)
@@ -1383,6 +1398,7 @@ fn setup_mux(
// Register ThinkTerm's saved SSH hosts as runtime mux domains so that
// reconnecting / restoring remote sessions can resolve them by name.
crate::ssh_hosts::register_saved_hosts();
+ crate::ssh_hosts::move_spaces_off_record_ids();
// Both sources of domain names are registered by now, so a Space naming
// one that still does not exist belongs to a host that has been deleted.
// Local removal only; the server keeps its copy.
diff --git a/wezterm-gui/src/ssh_hosts.rs b/wezterm-gui/src/ssh_hosts.rs
index 3274d01c..def2ecab 100644
--- a/wezterm-gui/src/ssh_hosts.rs
+++ b/wezterm-gui/src/ssh_hosts.rs
@@ -56,6 +56,11 @@ fn store_version() -> u32 {
lazy_static::lazy_static! {
static ref SSH_HOST_STORE: Mutex<Option<SshHostStore>> = Mutex::new(None);
+ /// Renames saved while connected under the old name, as (old name, new
+ /// name): the host's Spaces stay with that connection while it lasts
+ /// (`connect_name_after_rename`). One entry per host at most, gone once
+ /// its Spaces have moved.
+ static ref RENAMED_WHILE_CONNECTED: Mutex<Vec<(String, String)>> = Mutex::new(vec![]);
}
fn ensure_store_loaded(
@@ -768,53 +773,139 @@ pub fn domain_names_for_host(spec: &SshHostSpec) -> Vec<String> {
/// Whether a mux domain of this name can still be reached: a lua-configured
/// or already-attached domain, or a saved host that is connected under this
-/// name. Not a host's record id, though `connect_domain_from_ssh_host` takes
-/// one: Remote Hosts once connected hosts under their ids, and a Space left
-/// under one is forgotten here so that the host's next connection brings it
-/// back under the host's own name.
+/// name or its record id. Remote Hosts once connected hosts under their ids;
+/// a Space left under one stays, for the host's connection under its own
+/// name to take over (see `ingest_remote_tree`).
fn domain_name_is_reachable(domain_name: &str) -> bool {
if Mux::get().get_domain_by_name(domain_name).is_some() {
return true;
}
list_all_hosts()
.into_iter()
- .any(|entry| connect_domain_name(&entry.spec) == domain_name)
+ .any(|entry| connect_domain_name(&entry.spec) == domain_name || entry.id == domain_name)
}
-/// The names a host could be connected under that an edit takes from it: its
-/// connection name, when it is renamed or moved to the other network.
-fn domain_names_dropped(old: &SshHostSpec, new: &SshHostSpec) -> Vec<String> {
- let kept = domain_names_for_host(new);
- domain_names_for_host(old)
- .into_iter()
- .filter(|name| !kept.contains(name))
- .collect()
+/// The connection name an edit moved a host from, and the one it goes by
+/// now: when it was renamed or moved to the other network, and no other
+/// saved host goes by the old name as well.
+pub fn connect_name_change(old: &SshHostSpec, new: &SshHostSpec) -> Option<(String, String)> {
+ connect_name_change_among(old, new, &list_all_hosts())
}
-/// The names an edit of a host leaves with nothing to connect: those it no
-/// longer answers to that no other saved host answers to either. A domain
-/// registered under one earlier this session does not count, as it would for
-/// `domain_name_is_reachable`: the Mux keeps every domain it was given, and
-/// that one is the host as it was before the edit.
-pub fn domain_names_left_unreachable(old: &SshHostSpec, new: &SshHostSpec) -> Vec<String> {
- names_left_unreachable(old, new, &list_all_hosts())
-}
-
-fn names_left_unreachable(
+fn connect_name_change_among(
old: &SshHostSpec,
new: &SshHostSpec,
hosts: &[SshHostEntry],
-) -> Vec<String> {
- domain_names_dropped(old, new)
- .into_iter()
- .filter(|name| {
- !hosts
- .iter()
- .any(|entry| domain_names_for_host(&entry.spec).contains(name))
- })
+) -> Option<(String, String)> {
+ let before = connect_domain_name(old);
+ let after = connect_domain_name(new);
+ let still_used = hosts
+ .iter()
+ .any(|entry| connect_domain_name(&entry.spec) == before);
+ (before != after && !still_used).then_some((before, after))
+}
+
+/// Take a host's Spaces from the connection name an edit moved it off to
+/// the one it goes by now (see `connect_name_change`). Not while connected
+/// under the old name, even if that connection has dropped and is coming
+/// back: their windows show its terminals, and moved out from under it they
+/// would read as disconnected and be connected a second time beside it.
+/// They stay with it, as its address and password do, until it is gone.
+/// One that is only trying to connect has nothing on screen to keep, and
+/// gives them up at once.
+pub fn move_spaces_after_rename(from: String, to: String) {
+ let moved = rename_moves_now(&mut RENAMED_WHILE_CONNECTED.lock(), from, to, connected_under);
+ if let Some((from, to)) = moved {
+ crate::workspace_threads::move_spaces_to_domain(&from, &to);
+ }
+}
+
+/// The name to connect by for a host that goes by, or went by, `name`.
+/// Renamed while connected the old way, that is the old name as long as the
+/// connection lasts -- connecting lands in the windows already on it -- and
+/// the new one after, the Spaces moved over to it first.
+pub fn connect_name_after_rename(name: &str) -> String {
+ let (name, moved) = rename_settles(&mut RENAMED_WHILE_CONNECTED.lock(), name, connected_under);
+ if let Some((from, to)) = moved {
+ crate::workspace_threads::move_spaces_to_domain(&from, &to);
+ }
+ name
+}
+
+/// Whether a connection under `name` was made and has not been let go:
+/// connected, or reconnecting after a drop.
+fn connected_under(name: &str) -> bool {
+ Mux::get()
+ .get_domain_by_name(name)
+ .is_some_and(|domain| domain.state() == mux::domain::DomainState::Attached)
+}
+
+/// The Spaces a rename from `from` to `to` moves now, as (from, to): none
+/// while `connected` under the old name, the rename waiting in `renamed`
+/// instead.
+fn rename_moves_now(
+ renamed: &mut Vec<(String, String)>,
+ from: String,
+ to: String,
+ connected: impl Fn(&str) -> bool,
+) -> Option<(String, String)> {
+ // Renamed again before the first rename moved anything: one move, from
+ // the name the Spaces are under to the newest.
+ let from = match renamed.iter().position(|(_, new)| *new == from) {
+ Some(index) => renamed.remove(index).0,
+ None => from,
+ };
+ if from == to {
+ return None;
+ }
+ if connected(&from) {
+ renamed.push((from, to));
+ return None;
+ }
+ Some((from, to))
+}
+
+/// The name to connect by for `name` given the renames waiting in
+/// `renamed`, and the Spaces to move before connecting by it.
+fn rename_settles(
+ renamed: &mut Vec<(String, String)>,
+ name: &str,
+ connected: impl Fn(&str) -> bool,
+) -> (String, Option<(String, String)>) {
+ let Some(index) = renamed
+ .iter()
+ .position(|(old, new)| old == name || new == name)
+ else {
+ return (name.to_string(), None);
+ };
+ if connected(&renamed[index].0) {
+ return (renamed[index].0.clone(), None);
+ }
+ let (old, new) = renamed.remove(index);
+ (new.clone(), Some((old, new)))
+}
+
+/// The names saved hosts are connected under as things stand.
+pub fn connect_domain_names() -> std::collections::HashSet<String> {
+ list_all_hosts()
+ .iter()
+ .map(|entry| connect_domain_name(&entry.spec))
.collect()
}
+/// Move the Spaces left under a saved host's record id to the name the host
+/// is connected under. Remote Hosts once connected hosts under their ids, so
+/// a Space made then reconnected under the id and never under the host's
+/// own name. At startup, before anything is connected.
+pub fn move_spaces_off_record_ids() {
+ for entry in list_all_hosts() {
+ crate::workspace_threads::move_spaces_to_domain(
+ &entry.id,
+ &connect_domain_name(&entry.spec),
+ );
+ }
+}
+
/// Drop this device's copy of every Space whose mux server it can no longer
/// name.
///
@@ -1111,44 +1202,101 @@ mod tests {
}
#[test]
- fn a_rename_or_a_move_to_the_other_network_drops_the_name_its_spaces_know() {
+ fn a_rename_or_a_move_to_the_other_network_changes_the_connection_name() {
+ let entry = |spec: &SshHostSpec| SshHostEntry {
+ id: host_id_for_host(spec),
+ source: SshHostSource::ThinkTerm,
+ spec: spec.clone(),
+ };
let mut old = spec_with_options(HashMap::new());
old.label = "server-a".into();
old.host = "100.64.0.2".into();
- let dropped = |new: &SshHostSpec| domain_names_dropped(&old, new);
+ let change = |new: &SshHostSpec| connect_name_change_among(&old, new, &[entry(new)]);
let mut new = old.clone();
new.multiplexing = true;
new.detect_os = false;
- assert!(dropped(&new).is_empty());
+ assert_eq!(change(&new), None);
new.label = "server-b".into();
- assert_eq!(dropped(&new), vec!["server-a".to_string()]);
-
- let mut new = old.clone();
- new.network = SshNetwork::Tailnet;
- assert!(dropped(&new).contains(&"server-a".to_string()));
+ assert_eq!(
+ change(&new),
+ Some(("server-a".to_string(), "server-b".to_string()))
+ );
- // Back again: the tailnet name goes, the label is the name once more.
- let mut back = new.clone();
- back.network = SshNetwork::System;
- let names = domain_names_dropped(&new, &back);
- assert!(names.contains(&connect_domain_name(&new)));
- assert!(!names.contains(&"server-a".to_string()));
+ let mut moved = old.clone();
+ moved.network = SshNetwork::Tailnet;
+ assert_eq!(
+ change(&moved),
+ Some(("server-a".to_string(), connect_domain_name(&moved)))
+ );
- // A name another saved host still goes by is that host's to keep.
- let entry = |spec: &SshHostSpec| SshHostEntry {
- id: host_id_for_host(spec),
- source: SshHostSource::ThinkTerm,
- spec: spec.clone(),
- };
- let mut renamed = old.clone();
- renamed.label = "server-b".into();
+ // A name another saved host still goes by stays that host's.
let mut other = old.clone();
other.host = "192.0.2.10".into();
- let left = |hosts: &[SshHostEntry]| names_left_unreachable(&old, &renamed, hosts);
- assert!(left(&[entry(&renamed)]).contains(&"server-a".to_string()));
- assert!(!left(&[entry(&renamed), entry(&other)]).contains(&"server-a".to_string()));
+ assert_eq!(
+ connect_name_change_among(&old, &new, &[entry(&new), entry(&other)]),
+ None
+ );
+ }
+
+ #[test]
+ fn a_rename_with_nothing_connected_moves_the_spaces_at_once() {
+ let mut renamed = vec![];
+ assert_eq!(
+ rename_moves_now(&mut renamed, "server-a".into(), "server-b".into(), |_| false),
+ Some(("server-a".to_string(), "server-b".to_string()))
+ );
+ assert!(renamed.is_empty());
+ assert_eq!(
+ rename_settles(&mut renamed, "server-b", |_| false),
+ ("server-b".to_string(), None)
+ );
+ }
+
+ #[test]
+ fn a_rename_while_connected_leaves_the_spaces_on_that_connection_until_it_ends() {
+ let mut renamed = vec![];
+ let connected = |name: &str| name == "server-a";
+ assert_eq!(
+ rename_moves_now(&mut renamed, "server-a".into(), "server-b".into(), connected),
+ None
+ );
+ // Connecting by either name lands on the connection still up.
+ assert_eq!(
+ rename_settles(&mut renamed, "server-b", connected),
+ ("server-a".to_string(), None)
+ );
+ assert_eq!(
+ rename_settles(&mut renamed, "server-a", connected),
+ ("server-a".to_string(), None)
+ );
+ // Renamed again meanwhile: still one move, from where the Spaces are.
+ assert_eq!(
+ rename_moves_now(&mut renamed, "server-b".into(), "server-c".into(), connected),
+ None
+ );
+ // Once it is down, connecting moves them over and goes by the new name.
+ assert_eq!(
+ rename_settles(&mut renamed, "server-c", |_| false),
+ (
+ "server-c".to_string(),
+ Some(("server-a".to_string(), "server-c".to_string()))
+ )
+ );
+ assert!(renamed.is_empty());
+ }
+
+ #[test]
+ fn renaming_back_while_connected_leaves_nothing_to_move() {
+ let mut renamed = vec![];
+ let connected = |name: &str| name == "server-a";
+ rename_moves_now(&mut renamed, "server-a".into(), "server-b".into(), connected);
+ assert_eq!(
+ rename_moves_now(&mut renamed, "server-b".into(), "server-a".into(), connected),
+ None
+ );
+ assert!(renamed.is_empty());
}
#[test]
diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rs
index 2d47ad29..05113143 100644
--- a/wezterm-gui/src/termwindow/mod.rs
+++ b/wezterm-gui/src/termwindow/mod.rs
@@ -6403,6 +6403,9 @@ impl TermWindow {
else {
return;
};
+ // Renamed since it connected: the old way while that connection
+ // lasts, then the new one, with the Space moved over to it first.
+ let domain_name = crate::ssh_hosts::connect_name_after_rename(&domain_name);
if !self.space_reconnects_in_flight.insert(domain_name.clone()) {
return;
}
diff --git a/wezterm-gui/src/termwindow/mouseevent.rs b/wezterm-gui/src/termwindow/mouseevent.rs
index adb7b944..010b2e46 100644
--- a/wezterm-gui/src/termwindow/mouseevent.rs
+++ b/wezterm-gui/src/termwindow/mouseevent.rs
@@ -6755,6 +6755,25 @@ impl super::TermWindow {
}
}
+ /// Connecting found the Space it opens on screen already, in the window
+ /// whose Space owner id is `holder`: if that is this one, open the
+ /// Space's thread here, connecting it as switching to the Space does,
+ /// and bring the window forward.
+ pub(crate) fn open_space_if_held_by(&mut self, holder: u64) {
+ if self.space_owner_id != holder {
+ return;
+ }
+ let Some(window) = self.window.clone() else {
+ return;
+ };
+ if let Some(thread_id) =
+ crate::workspace_threads::ensure_active_thread_for_space(&self.active_space_id)
+ {
+ self.activate_workspace_thread(thread_id, &window);
+ }
+ window.focus();
+ }
+
pub(crate) fn open_ssh_host_thread_without_connecting(
&mut self,
host_id: String,
@@ -6769,7 +6788,11 @@ impl super::TermWindow {
// in its dedicated Space — the same flow as `thinkterm connect
// <name>` — rather than opening a direct-ssh remote thread.
if spec.multiplexing && !spec.use_mosh {
- let name = crate::ssh_hosts::connect_domain_name(&spec);
+ // Renamed while connected the old way, the host is still on that
+ // connection; connecting again goes to it.
+ let name = crate::ssh_hosts::connect_name_after_rename(
+ &crate::ssh_hosts::connect_domain_name(&spec),
+ );
// These hosts used to skip OS detection entirely: the branch
// returned before anything read `detect_os`, and both detection
// call sites downcast to `RemoteSshDomain`, which a mux client
diff --git a/wezterm-gui/src/termwindow/ssh_hosts_view.rs b/wezterm-gui/src/termwindow/ssh_hosts_view.rs
index 2fb8eb9e..6852d3a3 100644
--- a/wezterm-gui/src/termwindow/ssh_hosts_view.rs
+++ b/wezterm-gui/src/termwindow/ssh_hosts_view.rs
@@ -723,10 +723,9 @@ impl SshHostsView {
self.form_content_h = 0.0;
}
- /// Validate + create/update. On success returns the project id, with the
- /// Spaces the save left no way to reach (see `release_spaces_then`), and
- /// closes the form; on error records the message and keeps the form open.
- fn persist_form(&mut self) -> Option<(String, Vec<workspace_threads::SpaceId>)> {
+ /// Validate + create/update. On success returns the project id and closes
+ /// the form; on error records the message and keeps the form open.
+ fn persist_form(&mut self) -> Option<String> {
let form = self.form.as_mut()?;
if form.network == SshNetwork::Tailnet && form.use_mosh {
form.error = Some(crate::i18n::tr("ssh-error-tailnet-mosh"));
@@ -831,7 +830,6 @@ impl SshHostsView {
return None;
}
- let mut released = Vec::new();
let project_id = match &form.editing {
Some(id) => {
let before = ssh_hosts::host_spec(id);
@@ -843,15 +841,14 @@ impl SshHostsView {
(before, ssh_hosts::host_spec(&saved_id))
{
// Renamed or moved to the other network, the host
- // no longer answers to the name its Spaces know it
- // by. Let them go now, as the next launch would:
- // the host's next connection brings them back,
- // while kept, a click on one would connect it under
- // a name that Space does not know. References to
- // their threads stay, to resolve again then.
- released = workspace_threads::space_ids_for_domains(
- &ssh_hosts::domain_names_left_unreachable(&before, &after),
- );
+ // is reached under another name from now on, and
+ // its Spaces go with it: left under the old name,
+ // they would reconnect the way it was reached
+ // before, or not at all.
+ if let Some((from, to)) = ssh_hosts::connect_name_change(&before, &after)
+ {
+ ssh_hosts::move_spaces_after_rename(from, to);
+ }
crate::refresh_connect_domain_for_ssh_host(&after);
}
saved_id
@@ -876,7 +873,7 @@ impl SshHostsView {
};
self.close_form();
self.refresh();
- Some((project_id, released))
+ Some(project_id)
}
// ---- input ------------------------------------------------------------
@@ -1185,12 +1182,12 @@ impl SshHostsView {
}
ContentViewResponse::Redraw
}
- SshViewAction::Save => match self.persist_form() {
- Some((_, released)) => release_spaces_then(released, ContentViewResponse::Redraw),
- None => ContentViewResponse::Redraw,
- },
+ SshViewAction::Save => {
+ self.persist_form();
+ ContentViewResponse::Redraw
+ }
SshViewAction::SaveAndConnect => match self.persist_form() {
- Some((id, released)) => release_spaces_then(released, open_thread_response(id)),
+ Some(id) => open_thread_response(id),
None => ContentViewResponse::Redraw,
},
SshViewAction::Cancel => {
@@ -1498,9 +1495,7 @@ impl SshHostsView {
(KeyCode::Enter, _) => {
if in_form {
match self.persist_form() {
- Some((id, released)) => {
- release_spaces_then(released, open_thread_response(id))
- }
+ Some(id) => open_thread_response(id),
None => ContentViewResponse::Redraw,
}
} else if let Some(entry) = self.filtered.get(self.selected) {
@@ -5844,28 +5839,6 @@ fn open_thread_response(project_id: String) -> ContentViewResponse {
}))
}
-/// `then` (a redraw, or a callback such as `open_thread_response`) after
-/// dropping this device's copy of `released`: Spaces a saved host no longer
-/// reaches. Through the window, as `delete_host` drops a deleted host's,
-/// because it may be showing one; the server keeps them, and the host's next
-/// connection brings them back.
-fn release_spaces_then(
- released: Vec<workspace_threads::SpaceId>,
- then: ContentViewResponse,
-) -> ContentViewResponse {
- if released.is_empty() {
- return then;
- }
- ContentViewResponse::Run(Box::new(move |term_window| {
- for space_id in released {
- term_window.start_delete_space(&space_id, workspace_threads::SpaceRemoval::Local, false);
- }
- if let ContentViewResponse::Run(then) = then {
- then(term_window);
- }
- }))
-}
-
impl ContentView for SshHostsView {
fn title(&self) -> String {
crate::i18n::tr("ssh-hosts-title")
diff --git a/wezterm-gui/src/workspace_threads.rs b/wezterm-gui/src/workspace_threads.rs
index ae041f6f..8c22553b 100644
--- a/wezterm-gui/src/workspace_threads.rs
+++ b/wezterm-gui/src/workspace_threads.rs
@@ -1218,6 +1218,70 @@ pub fn release_window_space(owner_id: u64) {
WINDOW_SPACES.lock().remove(&owner_id);
}
+/// Where a window a server opened in one of its thread workspaces goes when
+/// nothing here asked for it (the reconcile shows the active workspace's).
+#[derive(Debug, PartialEq, Eq)]
+pub enum ServerThreadWindowHome {
+ /// The Space the thread is in, held through the connection the window
+ /// came by.
+ Space(SpaceId),
+ /// That Space is held through another connection to the same server,
+ /// whose own copy of the window it shows: a second GUI window would only
+ /// land on some unrelated local Space.
+ OtherConnection,
+ /// Not a thread this device knows to be that server's.
+ Unknown,
+}
+
+pub fn server_thread_window_home(workspace: &str, domain_name: &str) -> ServerThreadWindowHome {
+ THREAD_STORE
+ .lock()
+ .server_thread_window_home(workspace, domain_name)
+}
+
+impl WorkspaceThreadStore {
+ fn server_thread_window_home(&self, workspace: &str, domain_name: &str) -> ServerThreadWindowHome {
+ let Some((project_id, thread_id)) = parse_thread_workspace_name(workspace) else {
+ return ServerThreadWindowHome::Unknown;
+ };
+ let space_id = self
+ .projects
+ .iter()
+ .find(|project| project.threads.iter().any(|thread| thread.id == thread_id))
+ .or_else(|| self.projects.iter().find(|project| project.id == project_id))
+ .map(|project| project.space_id.as_str())
+ .or_else(|| space_id_from_remote_project_id(&project_id));
+ match space_id
+ .and_then(|space_id| self.spaces.iter().find(|space| space.id == space_id))
+ .and_then(|space| Some((space.id.clone(), space.client_domain.as_deref()?)))
+ {
+ Some((space_id, held_by)) if held_by == domain_name => {
+ ServerThreadWindowHome::Space(space_id)
+ }
+ Some(_) => ServerThreadWindowHome::OtherConnection,
+ None => ServerThreadWindowHome::Unknown,
+ }
+ }
+}
+
+/// Claim `space_id` for a window nobody explicitly opened, if no other
+/// window shows it. Unlike [`switch_window_space`] this is not the user
+/// going there, so the last active Space stays as it was.
+pub fn claim_free_space_for_window(owner_id: u64, space_id: &str) -> bool {
+ if !THREAD_STORE.lock().has_space(space_id) {
+ return false;
+ }
+ let mut assignments = WINDOW_SPACES.lock();
+ if assignments
+ .iter()
+ .any(|(owner, active_space)| *owner != owner_id && active_space == space_id)
+ {
+ return false;
+ }
+ assignments.insert(owner_id, space_id.to_string());
+ true
+}
+
fn window_owner_for_space_in(assignments: &HashMap<u64, SpaceId>, space_id: &str) -> Option<u64> {
assignments
.iter()
@@ -3426,6 +3490,7 @@ pub(crate) async fn materialize_thread(
.downcast_ref::<wezterm_client::domain::ClientDomain>()
.filter(|client| !client.is_local_session_host())
{
+ put_thread_on_server(domain.domain_name(), &thread_id).await;
let response = client_domain
.ensure_thinkterm_thread(Some(thread_id), size)
.await
@@ -4693,6 +4758,60 @@ fn tree_domain_for_thread(store: &WorkspaceThreadStore, thread_id: &str) -> Opti
tree_domain_for_project(store, &project_id)
}
+/// Move the Spaces this device holds under the connection name `from` to
+/// `to`: the name their server goes by now that its host was renamed, moved
+/// to the other network, or found under its record id. Done where the
+/// change is known for certain, so the Spaces reconnect the way the host is
+/// reached now rather than the way it was.
+pub fn move_spaces_to_domain(from: &str, to: &str) {
+ if from == to {
+ return;
+ }
+ {
+ let mut hidden = LOCALLY_HIDDEN_SPACES.lock();
+ if let Some(spaces) = hidden.remove(from) {
+ hidden.entry(to.to_string()).or_default().extend(spaces);
+ }
+ }
+ let mut store = THREAD_STORE.lock();
+ if store.move_spaces_to_domain(from, to) {
+ persist_locked(&store);
+ }
+}
+
+impl WorkspaceThreadStore {
+ fn move_spaces_to_domain(&mut self, from: &str, to: &str) -> bool {
+ let mut moved = false;
+ for space in &mut self.spaces {
+ if space.client_domain.as_deref() == Some(from) {
+ space.client_domain = Some(to.to_string());
+ moved = true;
+ }
+ }
+ if let Some(last) = self.last_space_per_domain.remove(from) {
+ self.last_space_per_domain
+ .entry(to.to_string())
+ .or_insert(last);
+ moved = true;
+ }
+ moved
+ }
+}
+
+/// Whether the connection named `domain_name` is up or on its way up. While
+/// it is, the Spaces it mirrors stay its own, even when the same server is
+/// also reached under another name.
+fn remote_domain_is_live(domain_name: &str) -> bool {
+ Mux::try_get()
+ .and_then(|mux| mux.get_domain_by_name(domain_name))
+ .is_some_and(|domain| {
+ domain.state() == mux::domain::DomainState::Attached
+ || domain
+ .downcast_ref::<wezterm_client::domain::ClientDomain>()
+ .is_some_and(|client| client.is_attaching() || client.is_attach_retrying())
+ })
+}
+
fn remote_tree_domain_is_attached(domain_name: &str) -> bool {
// try_get: unit tests and early startup have no Mux; "no mux" must read
// as "not attached" (the conservative answer that keeps refs alive).
@@ -4885,7 +5004,16 @@ pub fn ingest_remote_tree(domain_name: &str, tree: codec::ThinkTermTree) {
};
store.ingest_host_tree(&tree_for_store, known.as_ref())
} else {
- store.ingest_remote_tree(domain_name, &tree_for_store)
+ // Another name keeps its Spaces while it is connected, or while a
+ // saved host still goes by it: two records for one machine each keep
+ // theirs. Only a name nothing goes by any more gives them up.
+ let current = std::cell::OnceCell::new();
+ store.ingest_remote_tree_with(domain_name, &tree_for_store, &|other| {
+ remote_domain_is_live(other)
+ || current
+ .get_or_init(crate::ssh_hosts::connect_domain_names)
+ .contains(other)
+ })
};
// A server can legitimately have no Spaces left — its last one was deleted
// from here or from another device. A device that is connecting to it
@@ -5159,6 +5287,39 @@ pub fn reconcile_remote_subtree(domain_name: &str) {
submit_tree_ops(domain_name.to_string(), ops);
}
+/// Wait until the server behind `domain_name` knows `thread_id`, putting it
+/// there if it is not on its way yet. A thread made here is only sent up in
+/// the background, and asked to open a thread it has not heard of, the
+/// server opens another one instead: the window then waits on a workspace
+/// that never comes. Gives up after a few seconds, or at once when there is
+/// no tree from that server to tell by or no connection to send it over.
+pub async fn put_thread_on_server(domain_name: &str, thread_id: &str) {
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
+ let mut asked = 0;
+ while std::time::Instant::now() < deadline {
+ match LAST_KNOWN_REMOTE_TREES.lock().get(domain_name) {
+ Some(tree) if tree.thread(thread_id).is_some() => return,
+ Some(_) => {}
+ None => return,
+ }
+ // Nothing can be sent while the connection is not up: asking would
+ // only roll this device back to the last tree it heard.
+ if !remote_tree_domain_is_attached(domain_name) {
+ return;
+ }
+ let on_its_way = IN_FLIGHT_TREE_OPS.lock().contains_key(domain_name);
+ if !on_its_way {
+ if asked == 3 {
+ log::warn!("{domain_name} still does not know thread {thread_id}");
+ return;
+ }
+ asked += 1;
+ reconcile_remote_subtree(domain_name);
+ }
+ smol::Timer::after(std::time::Duration::from_millis(30)).await;
+ }
+}
+
/// Push a thread's shared scalar state to its server.
///
/// Activating a thread binds it to a mux workspace, stamps its recency and
@@ -6232,6 +6393,7 @@ impl WorkspaceThreadStore {
}
/// The Spaces currently attributed to `domain_name`.
+ #[cfg(test)]
fn space_ids_for_domain(&self, domain_name: &str) -> std::collections::HashSet<SpaceId> {
self.spaces
.iter()
@@ -7356,9 +7518,23 @@ impl WorkspaceThreadStore {
}
ops.extend(order_ops);
+ // A remote server's tree also carries Spaces this device does not hold
+ // under this name: another device's, one held under the name the
+ // server was reached by before, one the ingest refused. Their rows
+ // are not this connection's to remove -- treating them as deleted
+ // here once wiped a Space off a server reached under a second name.
+ // So only rows inside the Spaces held under this name are removed.
+ let removable = |space_id: &str| match scope {
+ PublishScope::Domain(_) => space_ids.iter().any(|id| id == space_id),
+ PublishScope::Host => true,
+ };
+
// Threads and projects first: deleting their Space would take them
// with it, and we want the narrower removal when only a row went away.
for project in &last_known.projects {
+ if !removable(&project.space_id) {
+ continue;
+ }
for thread in &project.threads {
if !live_threads.contains(thread.id.as_str()) {
ops.push(codec::TreeOp::DeleteThread {
@@ -7372,17 +7548,28 @@ impl WorkspaceThreadStore {
});
}
}
- for space in &last_known.spaces {
- if !space_ids.contains(&space.id) {
- ops.push(codec::TreeOp::DeleteSpace {
- space_id: space.id.clone(),
- });
+ // A remote server's Spaces go only by an explicit delete
+ // (`delete_space_for_window`), never by this diff.
+ if scope == PublishScope::Host {
+ for space in &last_known.spaces {
+ if !space_ids.contains(&space.id) {
+ ops.push(codec::TreeOp::DeleteSpace {
+ space_id: space.id.clone(),
+ });
+ }
}
}
ops
}
+ /// `ingest_remote_tree_with` as connecting does it, short of the saved
+ /// hosts: only a live connection keeps its Spaces.
+ #[cfg(test)]
+ fn ingest_remote_tree(&mut self, domain_name: &str, tree: &codec::ThinkTermTree) -> bool {
+ self.ingest_remote_tree_with(domain_name, tree, &remote_domain_is_live)
+ }
+
/// Rebuild this domain's Spaces/Projects/Threads from the server's tree.
///
/// The server owns what exists, what it is called, its order and its pins.
@@ -7394,18 +7581,52 @@ impl WorkspaceThreadStore {
/// Remote records keep being written to the local JSON file, but purely as
/// a cache: it lets the sidebar draw something before the attach finishes,
/// and this function overwrites it wholesale when the truth arrives.
- fn ingest_remote_tree(&mut self, domain_name: &str, tree: &codec::ThinkTermTree) -> bool {
- // The tree is the server's word and nothing more. A Space whose id
- // is already one of ours from elsewhere (the local default Space,
- // another domain's) would have every local project under that id
- // treated as this domain's and replaced, layouts included; and a
- // project naming a Space the tree does not carry would be re-homed
- // into the local default Space by normalize_after_load and read as
- // local from then on. Neither row is taken.
+ ///
+ /// `keeps_its_spaces` says whether another connection name still holds
+ /// the Spaces it holds: see `taken_over` below.
+ fn ingest_remote_tree_with(
+ &mut self,
+ domain_name: &str,
+ tree: &codec::ThinkTermTree,
+ keeps_its_spaces: &dyn Fn(&str) -> bool,
+ ) -> bool {
+ // A Space this device holds under another name for the same server
+ // -- one nothing goes by any more, such as the name of a host since
+ // deleted and saved again -- is this server's all the same. Its
+ // Spaces come over to this name; left behind, they could neither
+ // connect nor show up here.
+ let taken_over: Vec<(SpaceId, String)> = tree
+ .spaces
+ .iter()
+ .filter_map(|space| self.spaces.iter().find(|local| local.id == space.id))
+ .filter_map(|local| {
+ let other = local.client_domain.as_deref()?;
+ (other != domain_name && !keeps_its_spaces(other))
+ .then(|| (local.id.clone(), other.to_string()))
+ })
+ .collect();
+ for (space_id, other) in &taken_over {
+ log::info!(
+ "{domain_name} takes Space {space_id} over from {other}: the same server, \
+ reached under another name"
+ );
+ }
+ let held = |space: &Space| {
+ space.client_domain.as_deref() == Some(domain_name)
+ || taken_over.iter().any(|(id, _)| *id == space.id)
+ };
+
+ // Otherwise the tree is the server's word and nothing more. A Space
+ // whose id is already one of ours from elsewhere (the local default
+ // Space, a connected domain's) would have every local project under
+ // that id treated as this domain's and replaced, layouts included;
+ // and a project naming a Space the tree does not carry would be
+ // re-homed into the local default Space by normalize_after_load and
+ // read as local from then on. Neither row is taken.
let foreign_space_ids: std::collections::HashSet<&str> = self
.spaces
.iter()
- .filter(|space| space.client_domain.as_deref() != Some(domain_name))
+ .filter(|space| !held(space))
.map(|space| space.id.as_str())
.collect();
let tree_spaces: Vec<&codec::TtSpace> = tree
@@ -7445,7 +7666,7 @@ impl WorkspaceThreadStore {
let owned_space_ids: std::collections::HashSet<SpaceId> = self
.spaces
.iter()
- .filter(|space| space.client_domain.as_deref() == Some(domain_name))
+ .filter(|space| held(space))
.map(|space| space.id.clone())
.chain(tree_spaces.iter().map(|space| space.id.clone()))
.collect();
@@ -7453,7 +7674,7 @@ impl WorkspaceThreadStore {
let mut space_state: HashMap<SpaceId, (Option<ProjectId>, Option<SpaceVaultBinding>)> =
HashMap::new();
for space in &self.spaces {
- if space.client_domain.as_deref() == Some(domain_name) {
+ if held(space) {
space_state.insert(
space.id.clone(),
(space.active_project_id.clone(), space.note_vault.clone()),
@@ -7588,13 +7809,32 @@ impl WorkspaceThreadStore {
// Splice the rebuilt block in where the old one started so that the
// Space menu and sidebar do not reshuffle on every push.
- let spaces = splice_in_place(&self.spaces, new_spaces, |space| {
- space.client_domain.as_deref() == Some(domain_name)
- });
+ let spaces = splice_in_place(&self.spaces, new_spaces, |space| held(space));
let projects = splice_in_place(&self.projects, new_projects, |project| {
owned_space_ids.contains(&project.space_id)
});
+ // Land where this device last was on that server, as under its old
+ // name. What this name remembers so far may be only the stand-in the
+ // connect invented before the server spoke, which is gone now.
+ let remembered = self.last_space_per_domain.get(domain_name).is_some_and(|last| {
+ spaces
+ .iter()
+ .any(|space| space.id == *last && space.client_domain.as_deref() == Some(domain_name))
+ });
+ if !remembered {
+ let last = taken_over.iter().find_map(|(_, other)| {
+ self.last_space_per_domain
+ .get(other)
+ .filter(|space_id| taken_over.iter().any(|(id, _)| id == *space_id))
+ .cloned()
+ });
+ if let Some(last) = last {
+ self.last_space_per_domain
+ .insert(domain_name.to_string(), last);
+ }
+ }
+
if spaces == self.spaces && projects == self.projects {
return false;
}
@@ -9869,10 +10109,10 @@ pub fn adopt_orphan_remote_thread_windows(space_id: &str) -> bool {
return false;
}
- let mux_project_id = remote_project_id_for_space(space_id, &mux_domain_host_id(&domain_name));
let mux_project_name = crate::ssh_hosts::connect_domain_label(&domain_name);
let mut store = THREAD_STORE.lock();
+ let mux_project_id = store.mux_domain_project_id(space_id, &domain_name);
let mut changed = false;
for (project_id, thread_id, workspace, cwd) in candidates {
let workspace_known = store.projects.iter().any(|project| {
@@ -10043,7 +10283,40 @@ pub fn ensure_mux_domain_space(domain_name: &str) -> MuxDomainSpacePlan {
plan
}
+/// Whether `name` has the shape of a saved host's record id
+/// (`ssh-<hash>`, `system-ssh-<hash>`).
+fn is_host_record_id(name: &str) -> bool {
+ name.strip_prefix("system-ssh-")
+ .or_else(|| name.strip_prefix("ssh-"))
+ .is_some_and(|hash| !hash.is_empty() && hash.chars().all(|c| c.is_ascii_hexdigit()))
+}
+
impl WorkspaceThreadStore {
+ /// The project a mux-domain Space keeps for its server's own threads.
+ /// Its id, and the workspaces its threads run in on the server, are built
+ /// from the name the server was reached by when it was made; a Space
+ /// reached under another name since -- its host renamed, or moved to the
+ /// other network -- goes on with that project rather than growing a
+ /// second one beside it whose threads the server has never heard of.
+ fn mux_domain_project_id(&self, space_id: &str, domain_name: &str) -> ProjectId {
+ let own = remote_project_id_for_space(space_id, &mux_domain_host_id(domain_name));
+ if self.projects.iter().any(|project| project.id == own) {
+ return own;
+ }
+ self.projects
+ .iter()
+ .filter(|project| project.space_id == space_id && is_mux_domain_project_id(&project.id))
+ .max_by_key(|project| {
+ project
+ .threads
+ .iter()
+ .map(|thread| thread.last_active_at)
+ .max()
+ })
+ .map(|project| project.id.clone())
+ .unwrap_or(own)
+ }
+
fn ensure_mux_domain_space(&mut self, domain_name: &str) -> MuxDomainSpacePlan {
let store = self;
let label = crate::ssh_hosts::connect_domain_label(domain_name);
@@ -10057,13 +10330,12 @@ impl WorkspaceThreadStore {
store.create_space_record_for_domain(label.clone(), Some(domain_name.to_string()))
});
- let host_id = mux_domain_host_id(domain_name);
- let project_id = remote_project_id_for_space(&space_id, &host_id);
+ let project_id = store.mux_domain_project_id(&space_id, domain_name);
if !store.projects.iter().any(|p| p.id == project_id) {
store.projects.push(Project {
id: project_id.clone(),
space_id: space_id.clone(),
- name: label,
+ name: label.clone(),
path: PathBuf::from(format!("wezterm-mux://{domain_name}")),
threads: vec![],
active_thread_id: None,
@@ -10078,6 +10350,20 @@ impl WorkspaceThreadStore {
.iter_mut()
.find(|p| p.id == project_id)
.expect("mux domain project was just ensured");
+ // One made while Remote Hosts connected hosts under their record ids
+ // is still called by the id: show the host's name. A project named
+ // for any other connection may be another device's, and its name is
+ // shared through the server, so it stays as it is.
+ if let Some(named_for) =
+ remote_host_id_for_project_id(&project_id).strip_prefix(MUX_DOMAIN_HOST_PREFIX)
+ {
+ if named_for != domain_name
+ && project.name == named_for
+ && is_host_record_id(named_for)
+ {
+ project.name = label;
+ }
+ }
// Connecting to the server is an explicit gesture: a hidden project
// must not swallow the attach. The reconcile that follows a connect
// propagates the un-archive to the server.
@@ -13759,6 +14045,235 @@ mod tests {
)));
}
+ #[test]
+ fn a_reconcile_removes_only_rows_in_spaces_held_under_its_own_name() {
+ let mut store = remote_test_store("syd");
+ assert!(store.ingest_remote_tree("syd", &sample_tree()));
+ // The same server also carries a Space this device holds under the
+ // name it reached the server by before, and one it never took.
+ let mut server = sample_tree();
+ for (space, project, thread) in [
+ ("space-renamed", "renamed-p", "renamed-t"),
+ ("space-other", "other-p", "other-t"),
+ ] {
+ server.spaces.push(codec::TtSpace {
+ id: space.to_string(),
+ name: space.to_string(),
+ });
+ server.projects.push(codec::TtProject {
+ id: project.to_string(),
+ space_id: space.to_string(),
+ name: project.to_string(),
+ path: "/home/x".to_string(),
+ threads: vec![tree_thread(thread, project, "main")],
+ archived_at: None,
+ });
+ }
+ store.spaces.push(Space {
+ client_domain: Some("syd-before".to_string()),
+ ..store.spaces[1].clone()
+ });
+ store.spaces.last_mut().unwrap().id = "space-renamed".to_string();
+
+ assert!(store.delete_thread("rt2").is_some());
+ let ops = store.reconcile_ops_for_domain("syd", &server);
+ // A row that went away from this name's own Space still goes.
+ assert!(ops.iter().any(|op| matches!(
+ op,
+ codec::TreeOp::DeleteThread { thread_id } if thread_id == "rt2"
+ )));
+ // Nothing of the other two is touched.
+ assert!(!ops.iter().any(|op| match op {
+ codec::TreeOp::DeleteSpace { space_id } => space_id != "space-remote",
+ codec::TreeOp::RemoveProject { project_id } => project_id != "rp1",
+ codec::TreeOp::DeleteThread { thread_id } => thread_id != "rt2",
+ _ => false,
+ }));
+ }
+
+ #[test]
+ fn a_space_reached_under_another_name_goes_on_with_its_own_project() {
+ let mut store = remote_test_store("syd");
+ // Made when the server was reached as "syd-before": the project id,
+ // and the workspace its thread runs in on the server, carry that name.
+ let before = remote_project_id_for_space("space-remote", &mux_domain_host_id("syd-before"));
+ let mut thread = WorkspaceThread::new(before.clone(), "main".to_string(), None);
+ thread.materialized_workspace_name = Some(workspace_name_for_thread(&before, &thread.id));
+ let thread_id = thread.id.clone();
+ store.projects.push(test_project_in_space(
+ "space-remote",
+ &before,
+ "syd-before",
+ PathBuf::from("wezterm-mux://syd-before"),
+ vec![thread],
+ ));
+
+ let plan = store.ensure_mux_domain_space("syd");
+ assert_eq!(plan.space_id, "space-remote");
+ assert_eq!(plan.project_id, before);
+ assert_eq!(plan.thread_id, thread_id);
+ let projects: Vec<&Project> = store
+ .projects
+ .iter()
+ .filter(|project| project.space_id == "space-remote")
+ .collect();
+ assert_eq!(projects.len(), 1);
+ // Named for another connection, maybe another device's: its name is
+ // shared through the server and stays.
+ assert_eq!(projects[0].name, "syd-before");
+
+ // One still called by a host's record id shows the host's name.
+ let mut store = remote_test_store("syd");
+ let by_id = remote_project_id_for_space("space-remote", &mux_domain_host_id("ssh-0a1b2c"));
+ store.projects.push(test_project_in_space(
+ "space-remote",
+ &by_id,
+ "ssh-0a1b2c",
+ PathBuf::from("wezterm-mux://ssh-0a1b2c"),
+ vec![WorkspaceThread::new(by_id.clone(), "main".to_string(), None)],
+ ));
+ assert_eq!(store.ensure_mux_domain_space("syd").project_id, by_id);
+ let project = store.projects.iter().find(|project| project.id == by_id);
+ assert_eq!(project.unwrap().name, "syd");
+ }
+
+ #[test]
+ fn a_server_reached_under_a_new_name_takes_its_spaces_over() {
+ // Held under the name the server was reached by before.
+ let mut store = remote_test_store("syd-before");
+ assert!(store.ingest_remote_tree("syd-before", &sample_tree()));
+ store
+ .last_space_per_domain
+ .insert("syd-before".to_string(), "space-remote".to_string());
+ let held_by = |store: &WorkspaceThreadStore| {
+ store
+ .spaces
+ .iter()
+ .filter(|space| space.id == "space-remote")
+ .map(|space| space.client_domain.clone())
+ .collect::<Vec<_>>()
+ };
+
+ // While that name is connected, its Spaces stay its own.
+ assert!(!store.ingest_remote_tree_with("syd", &sample_tree(), &|name| {
+ name == "syd-before"
+ }));
+ assert_eq!(held_by(&store), vec![Some("syd-before".to_string())]);
+
+ // Once it is not, they come over, rows and this device's place too --
+ // even when the connect already noted the stand-in Space it made.
+ store
+ .last_space_per_domain
+ .insert("syd".to_string(), "space-stand-in".to_string());
+ assert!(store.ingest_remote_tree_with("syd", &sample_tree(), &|_| false));
+ assert_eq!(held_by(&store), vec![Some("syd".to_string())]);
+ assert!(store
+ .projects
+ .iter()
+ .any(|project| project.id == "rp1" && project.space_id == "space-remote"));
+ assert_eq!(
+ store.last_space_per_domain.get("syd").map(String::as_str),
+ Some("space-remote")
+ );
+
+ // A Space of this device's own is never taken, whatever is said.
+ let local = store.spaces[0].id.clone();
+ let mut tree = sample_tree();
+ tree.spaces.push(codec::TtSpace {
+ id: local.clone(),
+ name: "impostor".to_string(),
+ });
+ store.ingest_remote_tree_with("syd", &tree, &|_| false);
+ let local = store.spaces.iter().find(|space| space.id == local).unwrap();
+ assert!(local.client_domain.is_none());
+ }
+
+ #[test]
+ fn a_host_reached_under_a_new_name_takes_its_spaces_along() {
+ let mut store = remote_test_store("syd-before");
+ store.spaces.push(Space {
+ id: "space-other".to_string(),
+ client_domain: Some("ams".to_string()),
+ ..store.spaces[1].clone()
+ });
+ store
+ .last_space_per_domain
+ .insert("syd-before".to_string(), "space-remote".to_string());
+
+ assert!(store.move_spaces_to_domain("syd-before", "syd"));
+ let held_by = |id: &str| {
+ store
+ .spaces
+ .iter()
+ .find(|space| space.id == id)
+ .and_then(|space| space.client_domain.clone())
+ };
+ assert_eq!(held_by("space-remote").as_deref(), Some("syd"));
+ assert_eq!(held_by("space-other").as_deref(), Some("ams"));
+ assert!(store.spaces[0].client_domain.is_none());
+ assert_eq!(
+ store.last_space_per_domain.get("syd").map(String::as_str),
+ Some("space-remote")
+ );
+ assert!(!store.last_space_per_domain.contains_key("syd-before"));
+ // Nothing left under the old name.
+ assert!(!store.move_spaces_to_domain("syd-before", "syd"));
+ }
+
+ #[test]
+ fn opening_a_thread_waits_only_while_its_server_has_not_heard_of_it() {
+ let domain = "put-thread-on-server";
+ let quickly = |thread_id: &str| {
+ let started = std::time::Instant::now();
+ smol::block_on(put_thread_on_server(domain, thread_id));
+ started.elapsed() < std::time::Duration::from_secs(1)
+ };
+ // No tree from that server yet: nothing to tell by, so no waiting.
+ assert!(quickly("rt1"));
+ // A thread the server already listed opens at once.
+ LAST_KNOWN_REMOTE_TREES
+ .lock()
+ .insert(domain.to_string(), sample_tree());
+ assert!(quickly("rt1"));
+ // One it has not, with no connection up to send it over: nothing to
+ // wait for either.
+ assert!(quickly("rt-new"));
+ LAST_KNOWN_REMOTE_TREES.lock().remove(domain);
+ }
+
+ #[test]
+ fn a_servers_thread_window_goes_to_its_own_space_and_no_other() {
+ let mut store = remote_test_store("syd");
+ let mut tree = sample_tree();
+ tree.projects[0]
+ .threads
+ .push(tree_thread("thread-1", "rp1", "work"));
+ assert!(store.ingest_remote_tree("syd", &tree));
+ let workspace = workspace_name_for_thread("rp1", "thread-1");
+
+ assert_eq!(
+ store.server_thread_window_home(&workspace, "syd"),
+ ServerThreadWindowHome::Space("space-remote".to_string())
+ );
+ // The same window copied in by a second connection to that server.
+ assert_eq!(
+ store.server_thread_window_home(&workspace, "syd-tailnet"),
+ ServerThreadWindowHome::OtherConnection
+ );
+ // Neither a thread nor a Space this device knows.
+ assert_eq!(
+ store.server_thread_window_home(
+ &workspace_name_for_thread("muxdomain-syd::space::space-gone", "thread-gone"),
+ "syd"
+ ),
+ ServerThreadWindowHome::Unknown
+ );
+ assert_eq!(
+ store.server_thread_window_home("default", "syd"),
+ ServerThreadWindowHome::Unknown
+ );
+ }
+
#[test]
fn a_reconcile_emits_moves_when_only_the_order_changed() {
let mut store = remote_test_store("syd");