A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.
Rust agentagent-orchestrationaiai-agentsclaude-codecodexcoding-agentlinuxmacosmultiplayermultiplexerrustterminalterminal-emulatorterminal-multiplexertmuxtuiweztermwindows
feat(gui): show servers one row each or as folders in the Space menu
RoversX91916ba2db94
diff --git a/thinkterm-i18n/i18n/de-DE.ftl b/thinkterm-i18n/i18n/de-DE.ftlindex e9c11b6d..a767a477 100644--- a/thinkterm-i18n/i18n/de-DE.ftl+++ b/thinkterm-i18n/i18n/de-DE.ftl@@ -153,6 +153,12 @@ settings-window-tabs = Obere Tab-Leistesettings-window-tabs-description = Automatisch ausblenden: Sie erscheint, wenn der Zeiger am oberen Rand ruht, und schiebt das Terminal nach unten, ohne seine Größe zu ändern; die Stecknadel hält sie fest.settings-window-tabs-show = Anzeigensettings-window-tabs-auto-hide = Automatisch+settings-appearance-servers-heading = Server+settings-server-placement = Verbundene Server+settings-server-placement-description = Wie das Space-Menü Server zeigt: jeden Space jedes Servers ausgeschrieben, eine Zeile je Server, oder jeden Server als Ordner in den Spaces dieses Computers, sodass das Menü nur deine zeigt.+settings-server-placement-expanded = Ausgeklappt+settings-server-placement-one-row = Eine Zeile je Server+settings-server-placement-folders = Ordnersettings-terminal-shade = Farbe des Terminalssettings-terminal-shade-description = Wie dunkel der Hintergrund des Terminals ist, in einem durchscheinenden Fenster.settings-area-shade-dark = Dunkel@@ -397,6 +403,7 @@ menu-space-server-group-connecting = { $name } (verbindet…)menu-space-server-group-reconnecting = { $name } (verbindet erneut…)remote-tree-mutation-offline = { $name } ist getrennt. Verbinden Sie sich erneut und versuchen Sie es noch einmal.menu-new-space-here = Neuer Space hier+menu-new-space-on-server = Neuer Space auf Servermenu-add-remote-host = Remote-Host hinzufügen…menu-add-to-space = Zu Space hinzufügenmenu-add-to-space-named = Zu „{ $name }“ hinzufügendiff --git a/thinkterm-i18n/i18n/en-US.ftl b/thinkterm-i18n/i18n/en-US.ftlindex f678edd8..b181b85e 100644--- a/thinkterm-i18n/i18n/en-US.ftl+++ b/thinkterm-i18n/i18n/en-US.ftl@@ -153,6 +153,12 @@ settings-window-tabs = Top tab barsettings-window-tabs-description = Auto-hide brings it down while the pointer rests at the top edge, pushing the terminal down without resizing it; its pin keeps it out.settings-window-tabs-show = Showsettings-window-tabs-auto-hide = Auto-hide+settings-appearance-servers-heading = Servers+settings-server-placement = Connected servers+settings-server-placement-description = How the Space menu lists servers: every Space of each server spelled out, one row per server, or each server as folders in this computer's Spaces so the menu lists only yours.+settings-server-placement-expanded = Expanded+settings-server-placement-one-row = One Row Each+settings-server-placement-folders = Folderssettings-terminal-shade = Terminal colorsettings-terminal-shade-description = How dark the terminal's background is, in a see-through window.settings-area-shade-dark = Dark@@ -397,6 +403,7 @@ menu-space-server-group-connecting = { $name } (connecting…)menu-space-server-group-reconnecting = { $name } (reconnecting…)remote-tree-mutation-offline = { $name } is disconnected. Reconnect and try again.menu-new-space-here = New Space Here+menu-new-space-on-server = New Space on Servermenu-add-remote-host = Add Remote Host…menu-add-to-space = Add to Spacemenu-add-to-space-named = Add to “{ $name }”diff --git a/thinkterm-i18n/i18n/fr-FR.ftl b/thinkterm-i18n/i18n/fr-FR.ftlindex a63ee245..d6f730ef 100644--- a/thinkterm-i18n/i18n/fr-FR.ftl+++ b/thinkterm-i18n/i18n/fr-FR.ftl@@ -153,6 +153,12 @@ settings-window-tabs = Barre d’onglets du hautsettings-window-tabs-description = Masquage automatique : elle descend quand le pointeur s’arrête en haut de la fenêtre et pousse le terminal vers le bas sans le redimensionner ; l’épingle la garde affichée.settings-window-tabs-show = Affichersettings-window-tabs-auto-hide = Automatique+settings-appearance-servers-heading = Serveurs+settings-server-placement = Serveurs connectés+settings-server-placement-description = Comment le menu des espaces présente les serveurs : chaque espace de chaque serveur détaillé, une ligne par serveur, ou chaque serveur en dossiers dans les espaces de cet ordinateur, et le menu ne liste que les vôtres.+settings-server-placement-expanded = Tout déplié+settings-server-placement-one-row = Une ligne par serveur+settings-server-placement-folders = Dossierssettings-terminal-shade = Couleur du terminalsettings-terminal-shade-description = Le ton du fond du terminal, dans une fenêtre transparente.settings-area-shade-dark = Sombre@@ -397,6 +403,7 @@ menu-space-server-group-connecting = { $name } (connexion…)menu-space-server-group-reconnecting = { $name } (reconnexion…)remote-tree-mutation-offline = { $name } est déconnecté. Reconnectez-vous et réessayez.menu-new-space-here = Nouvel espace ici+menu-new-space-on-server = Nouvel espace sur un serveurmenu-add-remote-host = Ajouter un hôte distant…menu-add-to-space = Ajouter à l’espacemenu-add-to-space-named = Ajouter à « { $name } »diff --git a/thinkterm-i18n/i18n/ja-JP.ftl b/thinkterm-i18n/i18n/ja-JP.ftlindex 0fe32fe6..4e684a57 100644--- a/thinkterm-i18n/i18n/ja-JP.ftl+++ b/thinkterm-i18n/i18n/ja-JP.ftl@@ -150,6 +150,12 @@ settings-window-tabs = 上段のタブバーsettings-window-tabs-description = 自動的に隠す:ポインターをウインドウの上端に置くと現れ、ターミナルをサイズを変えずに下へ押し下げます。右端のピンで固定できます。settings-window-tabs-show = 表示settings-window-tabs-auto-hide = 自動的に隠す+settings-appearance-servers-heading = サーバー+settings-server-placement = 接続中のサーバー+settings-server-placement-description = スペースメニューでのサーバーの並べ方:サーバーごとにスペースをすべて展開、サーバー 1 台につき 1 行、またはサーバーをこのコンピューターのスペース内のフォルダにして、メニューには自分のスペースだけを並べます。+settings-server-placement-expanded = すべて展開+settings-server-placement-one-row = 1 台 1 行+settings-server-placement-folders = フォルダsettings-terminal-shade = ターミナルの色settings-terminal-shade-description = ターミナルの背景の濃さ。ウインドウが透けているときに効きます。settings-area-shade-dark = 濃い@@ -388,6 +394,7 @@ menu-space-server-group-connecting = { $name }(接続中…)menu-space-server-group-reconnecting = { $name }(再接続中…)remote-tree-mutation-offline = { $name } は切断されています。再接続してからもう一度お試しください。menu-new-space-here = このサーバーに新しいスペース+menu-new-space-on-server = サーバーに新しいスペースmenu-add-remote-host = リモートホストを追加…menu-add-to-space = スペースに追加menu-add-to-space-named = “{ $name }”に追加diff --git a/thinkterm-i18n/i18n/zh-CN.ftl b/thinkterm-i18n/i18n/zh-CN.ftlindex 06d58492..d92b2851 100644--- a/thinkterm-i18n/i18n/zh-CN.ftl+++ b/thinkterm-i18n/i18n/zh-CN.ftl@@ -150,6 +150,12 @@ settings-window-tabs = 一级标签栏settings-window-tabs-description = 自动隐藏:鼠标停在窗口顶部边缘时滑出来,把终端整体往下推、不改变大小;点右边的图钉可以固定住。settings-window-tabs-show = 显示settings-window-tabs-auto-hide = 自动隐藏+settings-appearance-servers-heading = 服务器+settings-server-placement = 连上的服务器+settings-server-placement-description = 空间菜单里怎么放服务器:每台的空间全部展开、每台服务器只占一行,或者作为文件夹放进这台电脑的空间里,菜单只列你自己的。+settings-server-placement-expanded = 全部展开+settings-server-placement-one-row = 每台一行+settings-server-placement-folders = 文件夹settings-terminal-shade = 终端颜色settings-terminal-shade-description = 终端底色的深浅,窗口透明时生效。settings-area-shade-dark = 深@@ -388,6 +394,7 @@ menu-space-server-group-connecting = { $name }(连接中…)menu-space-server-group-reconnecting = { $name }(重连中…)remote-tree-mutation-offline = { $name } 已断开。请重新连接后再试。menu-new-space-here = 在此服务器新建空间+menu-new-space-on-server = 在服务器上新建空间menu-add-remote-host = 添加远程主机…menu-add-to-space = 添加到空间menu-add-to-space-named = 添加到“{ $name }”diff --git a/wezterm-gui/src/frontend.rs b/wezterm-gui/src/frontend.rsindex f9fd0a20..2d311bf3 100644--- a/wezterm-gui/src/frontend.rs+++ b/wezterm-gui/src/frontend.rs@@ -657,10 +657,12 @@ impl GuiFrontEnd {// window (updating known_windows via rebind) or closes itself.let known_windows = std::mem::take(&mut *self.known_windows.borrow_mut());let mut windows = BTreeMap::new();+ let mut recovering = false;for (window, window_id) in known_windows.into_iter() {if mux.get_window(window_id).is_some() {windows.insert(window, window_id);} else {+ recovering = true;self.spawned_mux_window.borrow_mut().remove(&window_id);window.notify(TermWindowNotif::Apply(Box::new(|term_window| {term_window.recover_from_dead_mux_window();@@ -750,6 +752,28 @@ impl GuiFrontEnd {);continue;}+ // A server holding two windows for one thread (left by an+ // earlier mirror rebuild or a second materialization) shows+ // the thread once, as the session host's leftovers do: the+ // other window stays in the background instead of opening+ // a window of its own on top. While a window that lost its+ // mux window recovers, it is the one to show a thread's+ // remaining window, in place.+ if is_domain_owned+ && (front_end().thread_window_is_duplicate(mux_window_id, &window_workspace)+ || (recovering+ && crate::workspace_threads::is_thread_workspace_name(+ &window_workspace,+ )))+ {+ log::debug!(+ "reconcile: leaving window {} in workspace {:?} hidden: the thread \+ is shown by another of its windows",+ mux_window_id,+ window_workspace,+ );+ 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.@@ -1011,6 +1035,28 @@ impl GuiFrontEnd {false}+ /// `mux_window_id` is one of several windows of a thread workspace, and+ /// the thread is on screen through another of them already, or about to+ /// be.+ fn thread_window_is_duplicate(&self, mux_window_id: MuxWindowId, workspace: &str) -> bool {+ if !crate::workspace_threads::is_thread_workspace_name(workspace) {+ return false;+ }+ let mux = Mux::get();+ let in_workspace = |id: MuxWindowId| {+ id != mux_window_id+ && mux+ .get_window(id)+ .is_some_and(|window| window.get_workspace() == workspace)+ };+ self.known_windows.borrow().values().any(|id| in_workspace(*id))+ || self+ .spawned_mux_window+ .borrow()+ .iter()+ .any(|id| in_workspace(*id))+ }+/// Pre-claim a mux window that the caller is about to create a GUI window/// for explicitly (e.g. the `thinkterm connect` flow), so that neither the/// WindowCreated handler nor the additive reconcile spawns a duplicate.diff --git a/wezterm-gui/src/native_settings.rs b/wezterm-gui/src/native_settings.rsindex b6838394..85931b3c 100644--- a/wezterm-gui/src/native_settings.rs+++ b/wezterm-gui/src/native_settings.rs@@ -486,6 +486,28 @@ impl NativeWindowTabs {pub(crate) const ALL: [Self; 2] = [Self::Show, Self::AutoHide];}+/// Where a connected server's threads show, and how the Space menu lists+/// servers.+///+/// `OwnSpace` is the default and what servers have always done: each one+/// has Spaces of its own, every one of them spelled out in the Space menu+/// under its server. `OneRowEach` keeps those Spaces and folds each server+/// into one row of the menu. `Folders` keeps the Space menu to this device's+/// Spaces and shows every server as folders in one of them instead.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Deserialize, Serialize)]+#[serde(rename_all = "snake_case")]+pub(crate) enum NativeServerPlacement {+ #[default]+ OwnSpace,+ OneRowEach,+ Folders,+}++impl NativeServerPlacement {+ /// Every choice, in the order the settings window offers them.+ pub(crate) const ALL: [Self; 3] = [Self::OwnSpace, Self::OneRowEach, Self::Folders];+}+#[derive(Debug, Clone, Default, Deserialize, Serialize)]#[serde(default)]pub(crate) struct NativeAppearanceSettings {@@ -530,6 +552,9 @@ pub(crate) struct NativeAppearanceSettings {/// Under `AutoHide`, the row's pin is in: it stays out and takes its/// height in the layout, as under `Show`.pub(crate) window_tabs_pinned: bool,+ /// See [`NativeServerPlacement`].+ #[serde(deserialize_with = "choice_or_default")]+ pub(crate) server_placement: NativeServerPlacement,}/// How a sidebar thread row draws the programs its panes run. All but@@ -1119,6 +1144,19 @@ pub(crate) fn save_window_tabs_pinned(pinned: bool) -> anyhow::Result<()> {})}+/// Whether servers show as folders in this device's Spaces rather than in+/// Spaces of their own. Through the shared handle: the sidebar asks each+/// time it builds its rows.+pub(crate) fn servers_as_folders() -> bool {+ load_shared().appearance.server_placement == NativeServerPlacement::Folders+}++/// Whether the Space menu folds each server into one row. Asked as the+/// menu opens.+pub(crate) fn space_menu_one_row_per_server() -> bool {+ load_shared().appearance.server_placement == NativeServerPlacement::OneRowEach+}+/// Read once per painted pane, through the shared handle.pub(crate) fn overlay_scrollbar() -> bool {load_shared().terminal.overlay_scrollbar@@ -3755,6 +3793,31 @@ mod tests {assert!(out.contains("\"window_tabs\":\"auto_hide\""), "{out}");}+ /// Servers keep their own Spaces unless a file says otherwise, and a+ /// choice this build does not know falls back to that too.+ #[test]+ fn a_server_placement_choice_round_trips_and_defaults_to_own_spaces() {+ let json = r#"{ "version": 1, "appearance": { "theme_mode": "system" } }"#;+ let settings: ThinkTermNativeSettings =+ serde_json::from_str(json).expect("the file has to survive");+ assert_eq!(+ settings.appearance.server_placement,+ NativeServerPlacement::OwnSpace+ );++ for (written, expected) in [+ ("own_space", NativeServerPlacement::OwnSpace),+ ("one_row_each", NativeServerPlacement::OneRowEach),+ ("folders", NativeServerPlacement::Folders),+ ("someday", NativeServerPlacement::OwnSpace),+ ] {+ let json = format!(r#"{{"appearance": {{"server_placement": "{written}"}}}}"#);+ let settings: ThinkTermNativeSettings =+ serde_json::from_str(&json).expect("the file has to survive");+ assert_eq!(settings.appearance.server_placement, expected, "{written}");+ }+ }+#[test]fn a_cursor_shape_choice_round_trips_through_the_file() {for (written, expected) in [diff --git a/wezterm-gui/src/settings_window.rs b/wezterm-gui/src/settings_window.rsindex a5e71908..91a4ff34 100644--- a/wezterm-gui/src/settings_window.rs+++ b/wezterm-gui/src/settings_window.rs@@ -1866,6 +1866,17 @@ fn localized_window_tabs_label(mode: crate::native_settings::NativeWindowTabs) -})}+fn localized_server_placement_label(+ placement: crate::native_settings::NativeServerPlacement,+) -> String {+ use crate::native_settings::NativeServerPlacement;+ crate::i18n::tr(match placement {+ NativeServerPlacement::OwnSpace => "settings-server-placement-expanded",+ NativeServerPlacement::OneRowEach => "settings-server-placement-one-row",+ NativeServerPlacement::Folders => "settings-server-placement-folders",+ })+}+fn localized_cursor_shape_label(shape: crate::native_settings::NativeCursorShape) -> String {use crate::native_settings::NativeCursorShape;crate::i18n::tr(match shape {@@ -2234,6 +2245,7 @@ enum SettingsAction {SetSidebarShade(crate::native_settings::NativeShade),SetTabBarShade(crate::native_settings::NativeShade),SetWindowTabs(crate::native_settings::NativeWindowTabs),+ SetServerPlacement(crate::native_settings::NativeServerPlacement),SetTerminalShade(crate::native_settings::NativeShade),SetThreadIcons(crate::native_settings::NativeThreadIcons),SetThreadStatus(crate::native_settings::NativeThreadStatus),@@ -6648,6 +6660,9 @@ impl SettingsWindow {|appearance| appearance.tab_bar_shade = shade,),SettingsAction::SetWindowTabs(mode) => self.apply_window_tabs(mode),+ SettingsAction::SetServerPlacement(placement) => {+ self.apply_server_placement(placement)+ }SettingsAction::SetTerminalShade(shade) => self.apply_window_areas("settings-terminal-shade",localized_shade_label(shade),@@ -9451,6 +9466,53 @@ impl SettingsWindow {Ok(rows.bottom)})?;+ let card_y = self.paint_card_heading(+ layers,+ x,+ bottom,+ max_width,+ &crate::i18n::tr("settings-appearance-servers-heading"),+ )?;+ let bottom = self.paint_card(layers, x, card_y, max_width, |this, layers, top| {+ use crate::native_settings::NativeServerPlacement;+ let mut rows = RowCursor::new(top, this);+ let options: Vec<(String, SettingsAction)> = NativeServerPlacement::ALL+ .iter()+ .map(|placement| {+ (+ localized_server_placement_label(*placement),+ SettingsAction::SetServerPlacement(*placement),+ )+ })+ .collect();+ let selected = NativeServerPlacement::ALL+ .iter()+ .position(|placement| {+ *placement == this.native_settings.appearance.server_placement+ })+ .unwrap_or(0);+ let (tx, tw) = this.paint_row_tile(+ layers,+ row_x,+ rows.y,+ row_width,+ SvgIcon::Server,+ TileColor::Teal,+ )?;+ rows.add(this.paint_segmented_setting_row(+ layers,+ tx,+ rows.y,+ tw,+ &crate::i18n::tr("settings-server-placement"),+ &crate::i18n::tr("settings-server-placement-description"),+ &options,+ selected,+ rows.rule(),+ )?);+ Ok(rows.bottom)+ })?;+self.ui.content_scroll.set_extents(self.content_viewport_extent(),self.settings_content_extent(bottom + scroll),@@ -20051,6 +20113,52 @@ impl SettingsWindow {}}+ /// Give servers Spaces of their own or show them as folders in this+ /// device's Spaces. The sidebars read the choice as they paint, the+ /// Space menu and the palette as they open; what it owes the windows is+ /// a repaint, and letting go of a server thread whose folder is gone.+ fn apply_server_placement(+ &mut self,+ placement: crate::native_settings::NativeServerPlacement,+ ) {+ self.ui.open_dropdown = None;+ if crate::native_settings::load_shared().appearance.server_placement == placement {+ return;+ }+ let mut merged = crate::native_settings::load();+ merged.appearance.server_placement = placement;+ self.set_native_settings(merged);+ let setting = crate::i18n::tr("settings-server-placement");+ match crate::native_settings::save(&self.native_settings) {+ Ok(()) => {+ // A server thread on screen through a folder that is gone+ // now is let go of.+ for gui_window in crate::frontend::front_end().gui_windows() {+ gui_window+ .window+ .notify(crate::termwindow::TermWindowNotif::Apply(Box::new(+ |term_window| term_window.leave_server_folder_content_if_hidden(),+ )));+ }+ crate::frontend::front_end().invalidate_all_windows();+ self.status = settings_tr(+ "settings-status-value-now",+ &[+ ("setting", setting),+ ("value", localized_server_placement_label(placement)),+ ],+ );+ }+ Err(err) => {+ self.set_native_settings(crate::native_settings::load());+ self.status = settings_tr(+ "settings-status-save-error",+ &[("setting", setting), ("error", format!("{err:#}"))],+ );+ }+ }+ }+/// What a see-through window shows behind it on macOS, in every window/// at once, as the window opacity is.fn apply_mac_glass(&mut self, glass: crate::native_settings::NativeMacGlass) {diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rsindex 3c44114b..51bb196d 100644--- a/wezterm-gui/src/termwindow/mod.rs+++ b/wezterm-gui/src/termwindow/mod.rs@@ -265,6 +265,34 @@ pub(crate) struct LocalThreadActivationState {pub workspace_name: String,}+/// The connection page of a mux-domain Space reached on demand: a mux+/// window of its own, shown in place of the thread the window was on, so+/// the page never lands among that thread's tabs. Leaving it (another+/// thread, another Space) gives the connection up.+pub(crate) struct SpaceConnectionPage {+ pub mux_window_id: MuxWindowId,+ pub domain_name: String,+ /// What to open once the server answers.+ pub thread_id: String,+ pub orphan_candidate_window_id: Option<MuxWindowId>,+ pub workspaces_to_kill_after_adopt: Vec<String>,+ /// Where to go back to when the page closes without a connection.+ pub return_space_id: String,+ /// The thread the page took the place of, when it opened in place in+ /// that Space (a reference or server folder row): the one to go back+ /// to, rather than whichever thread the Space would pick.+ pub return_thread_id: Option<String>,+ /// The attach behind the page ended without a connection. The page+ /// stays up to show why; opening the Space again starts over.+ pub gave_up: bool,+}++fn domain_is_attached(domain_name: &str) -> bool {+ Mux::get()+ .get_domain_by_name(domain_name)+ .is_some_and(|domain| domain.state() == mux::domain::DomainState::Attached)+}+use crate::spawn::SpawnWhere;use prevcursor::PrevCursorPos;@@ -3207,12 +3235,20 @@ pub struct TermWindow {next_mosh_connect_generation: u64,local_thread_activation: Option<LocalThreadActivationState>,next_local_thread_activation_generation: u64,+ space_connection_page: Option<SpaceConnectionPage>,+ /// The Space this window showed before `active_space_id`: where a remote+ /// Space that loses its server sends the window back to.+ previous_space_id: Option<String>,space_owner_id: u64,active_space_id: String,/// True for windows the user did not explicitly open (domain-owned/// windows spawned by the reconcile, e.g. reconnect/auth prompts): they/// close when their mux window dies instead of falling back to a thread.dies_with_mux_window: bool,+ /// Opened for a server's connection (Connect, `thinkterm connect`) that+ /// has not got through yet: if it fails or is turned down, the window+ /// goes, as it came for nothing else.+ opened_to_connect: bool,/// Domains with a user-requested reconnect currently in flight (the/// sidebar Reconnect button); suppresses double-clicks and drives the/// row's "Connecting…" label.@@ -5144,9 +5180,12 @@ impl TermWindow {next_mosh_connect_generation: 1,local_thread_activation: None,next_local_thread_activation_generation: 1,+ space_connection_page: None,+ previous_space_id: None,space_owner_id,active_space_id,dies_with_mux_window,+ opened_to_connect: remote_open_domain.is_some(),space_reconnects_in_flight: HashSet::new(),watched_space_connection_state: None,workspace_layout_structure_fingerprint,@@ -6594,6 +6633,7 @@ impl TermWindow {return;}+ let left_connection_page = self.take_left_space_connection_page(mux_window_id);self.cancel_remote_divider_resizes_except(None);self.mux_window_id = mux_window_id;*self.mux_window_id_for_subscriptions.lock().unwrap() = mux_window_id;@@ -6662,6 +6702,12 @@ impl TermWindow {if let Some(window) = self.window.as_ref() {window.invalidate();}++ // Only now that the subscription names the adopted window, so the+ // page window's WindowRemoved cannot be taken for ours.+ if let Some(page) = left_connection_page {+ Mux::get().kill_window(page.mux_window_id);+ }}pub(crate) fn active_space_id(&self) -> &str {@@ -6697,8 +6743,11 @@ impl TermWindow {/// exited, e.g. `exit` in a thread's only shell). Fall back to another/// thread of the Space — or a fresh one — instead of dying with it,/// which used to take the whole app down when this was the last window.- /// Incidental windows (reconnect/auth prompts) and remote mux Spaces- /// keep the close-with-the-mux-window behavior.+ /// A remote mux Space moves to another of its threads while its server+ /// is connected; one with no other thread, no server, or a connection+ /// page that closed unconnected sends the window back to the Space it+ /// came from. Only incidental windows (reconnect/auth prompts) close+ /// with their mux window.pub(crate) fn recover_from_dead_mux_window(&mut self) {let mux = Mux::get();if mux.get_window(self.mux_window_id).is_some() {@@ -6719,10 +6768,65 @@ impl TermWindow {return;}}- let recovery_thread = if self.dies_with_mux_window- || crate::workspace_threads::client_domain_for_space(&self.active_space_id).is_some()+ if self+ .space_connection_page+ .as_ref()+ .is_some_and(|page| page.mux_window_id == self.mux_window_id){+ if let Some(page) = self.space_connection_page.take() {+ self.recover_from_closed_connection_page(page, &window);+ }+ return;+ }+ // The thread has another window left (a server holding two for+ // it): show that one here rather than leaving the thread.+ if !self.dies_with_mux_window {+ if let Some(thread_id) =+ crate::workspace_threads::recorded_active_thread_for_space(&self.active_space_id)+ {+ let live_workspaces = Mux::get().iter_workspaces();+ if crate::workspace_threads::activation_plan_for_thread(+ &thread_id,+ &live_workspaces,+ )+ .is_some_and(|plan| !plan.needs_materialize)+ {+ self.activate_workspace_thread(thread_id, &window);+ return;+ }+ }+ }+ let recovery_thread = if self.dies_with_mux_window {None+ } else if let Some(domain_name) =+ crate::workspace_threads::client_domain_for_space(&self.active_space_id)+ {+ // Another of the Space's threads while its server is there; no+ // fresh one, which the server would not know yet.+ let other_thread = domain_is_attached(&domain_name)+ .then(|| {+ crate::workspace_threads::existing_thread_to_recover_after_window_death(+ &self.active_space_id,+ )+ })+ .flatten();+ if other_thread.is_none() {+ // Opened for this connection alone, which never got through:+ // it goes. Not as the last window, whose closing would end+ // every other connection.+ if self.opened_to_connect && front_end().gui_windows().len() > 1 {+ window.close();+ front_end().forget_known_window(&window);+ return;+ }+ let return_space_id = self+ .previous_space_id+ .clone()+ .unwrap_or_else(crate::workspace_threads::default_space_id);+ self.return_from_unreachable_space(return_space_id, None, &window);+ return;+ }+ other_thread} else {crate::workspace_threads::thread_to_recover_after_window_death(&self.active_space_id)};@@ -6739,6 +6843,294 @@ impl TermWindow {self.activate_workspace_thread(thread_id, &window);}+ /// Put the connection page of `domain_name`'s Space on screen: a mux+ /// window of its own in place of what this window showed, so the page+ /// is never filed among the tabs of the thread being left. Returns the+ /// window for the connection UI, or None when this Space's page is up+ /// and still connecting; that page then opens `thread_id` instead of the+ /// earlier pick. A page that gave up makes way for a fresh attempt.+ pub(crate) fn show_space_connection_page(+ &mut self,+ domain_name: &str,+ thread_id: String,+ orphan_candidate_window_id: Option<MuxWindowId>,+ workspaces_to_kill_after_adopt: Vec<String>,+ ) -> Option<MuxWindowId> {+ let shown_mux_window_id = self.mux_window_id;+ let shown_page = self+ .space_connection_page+ .as_mut()+ .filter(|page| page.mux_window_id == shown_mux_window_id);+ let (return_space_id, return_thread_id) = match shown_page {+ Some(page) if page.domain_name == domain_name && !page.gave_up => {+ page.thread_id = thread_id;+ page.orphan_candidate_window_id = orphan_candidate_window_id;+ page.workspaces_to_kill_after_adopt = workspaces_to_kill_after_adopt;+ return None;+ }+ // Another Space's page, or this one's that gave up, gives way;+ // going back skips it.+ Some(page) => Some((page.return_space_id.clone(), page.return_thread_id.clone())),+ None => None,+ }+ .unwrap_or_else(|| self.place_to_return_to());+ let mux = Mux::get();+ let workspace = format!(+ "{}{domain_name}",+ crate::workspace_threads::CONNECTION_PAGE_WORKSPACE_PREFIX+ );+ let builder = mux.new_empty_window_for_domain(Some(workspace.clone()), None, None);+ let page_window_id = *builder;+ // Shown here before the frontend hears of it, so the reconcile finds+ // it taken instead of opening a window of its own for it; the thread+ // being left goes to the background like any thread switched away+ // from.+ mux.set_active_workspace(&workspace);+ self.switch_to_mux_window(page_window_id);+ drop(builder);+ self.space_connection_page = Some(SpaceConnectionPage {+ mux_window_id: page_window_id,+ domain_name: domain_name.to_string(),+ thread_id,+ orphan_candidate_window_id,+ workspaces_to_kill_after_adopt,+ return_space_id,+ return_thread_id,+ gave_up: false,+ });+ Some(page_window_id)+ }++ /// The attach behind the connection page failed. The page stays to+ /// show why, but no longer counts as connecting: opening the Space+ /// again, or its Reconnect, tries again.+ pub(crate) fn note_space_connection_page_gave_up(&mut self, page_window_id: MuxWindowId) {+ if let Some(page) = self+ .space_connection_page+ .as_mut()+ .filter(|page| page.mux_window_id == page_window_id)+ {+ page.gave_up = true;+ }+ }++ /// The server behind the connection page answered: open what the page+ /// was for, unless the person moved on (the connection then stays up in+ /// the background).+ pub(crate) fn open_connected_space_page(+ &mut self,+ page_window_id: MuxWindowId,+ domain_id: Option<DomainId>,+ ) {+ let Some(page) = self+ .space_connection_page+ .as_ref()+ .filter(|page| page.mux_window_id == page_window_id)+ .filter(|_| self.mux_window_id == page_window_id)+ else {+ return;+ };+ let domain_name = page.domain_name.clone();+ let thread_id = page.thread_id.clone();+ let (return_space_id, return_thread_id) =+ (page.return_space_id.clone(), page.return_thread_id.clone());+ let orphan_candidate_window_id = page.orphan_candidate_window_id;+ let workspaces_to_kill_after_adopt = page.workspaces_to_kill_after_adopt.clone();+ let Some(window) = self.window.clone() else {+ return;+ };+ let Some(thread_id) = self.thread_for_connected_page(&domain_name, thread_id) else {+ self.return_from_unreachable_space(return_space_id, return_thread_id, &window);+ return;+ };+ // Switching into a cold mux-domain Space is as explicit an open as+ // the Connect button, so it gets the same one-shot claim. Armed+ // only: the activation releases it when its tab is on screen, and+ // the paint path consumes it once that tab's gate is claimable.+ if let Some(domain_id) = domain_id {+ self.note_remote_open_intent(domain_id);+ }+ // Leaving the page for the thread closes it (switch_to_mux_window).+ self.activate_workspace_thread_impl(+ thread_id,+ &window,+ orphan_candidate_window_id,+ workspaces_to_kill_after_adopt,+ );+ }++ /// What a connection page that got through opens: the thread it was+ /// for, while this window may still open it, else another of the+ /// Space's. The thread can have gone while it connected -- deleted from+ /// another device, or out of the folders here as servers stopped+ /// showing as them -- and what was settled before the server's tree+ /// came, which drops anything only this device had, is settled again+ /// first and the server told of what it still lacks, as+ /// `connect_domain_into_space` does.+ fn thread_for_connected_page(&self, domain_name: &str, thread_id: String) -> Option<String> {+ let settled = crate::workspace_threads::ensure_mux_domain_space(domain_name);+ crate::workspace_threads::reconcile_remote_subtree(domain_name);+ std::iter::once(thread_id)+ .chain(std::iter::once(settled.thread_id))+ .chain(crate::workspace_threads::existing_thread_to_recover_after_window_death(+ &self.active_space_id,+ ))+ .find(|thread_id| self.may_open_thread(thread_id))+ }++ /// Whether this window may open `thread_id`: one of its Space's own, or+ /// one the Space shows -- the gate `activate_workspace_thread_impl`+ /// keeps.+ fn may_open_thread(&self, thread_id: &str) -> bool {+ crate::workspace_threads::thread_space_id(thread_id).as_deref()+ == Some(self.active_space_id.as_str())+ || crate::workspace_threads::thread_ref_exists(&self.active_space_id, thread_id)+ }++ /// The connection page this window leaves by showing `next_mux_window_id`.+ /// Leaving gives the connection up: closing the page's window answers+ /// whatever it was asking with a no and stops the retries.+ fn take_left_space_connection_page(+ &mut self,+ next_mux_window_id: MuxWindowId,+ ) -> Option<SpaceConnectionPage> {+ if self+ .space_connection_page+ .as_ref()+ .is_some_and(|page| page.mux_window_id != next_mux_window_id)+ {+ return self.space_connection_page.take();+ }+ None+ }++ /// The connection page closed while on screen: the person closed it,+ /// or it ran out its close delay after a failure.+ fn recover_from_closed_connection_page(&mut self, page: SpaceConnectionPage, window: &Window) {+ if !domain_is_attached(&page.domain_name) {+ self.return_from_unreachable_space(page.return_space_id, page.return_thread_id, window);+ return;+ }+ // Connected, and the page went before the thread made it on screen.+ let opening = self+ .local_thread_activation+ .as_ref()+ .is_some_and(|activation| activation.thread_id == page.thread_id);+ if opening {+ return;+ }+ let Some(thread_id) = self.thread_for_connected_page(&page.domain_name, page.thread_id)+ else {+ self.return_from_unreachable_space(page.return_space_id, page.return_thread_id, window);+ return;+ };+ if let Some(domain_id) = Mux::get()+ .get_domain_by_name(&page.domain_name)+ .map(|domain| domain.domain_id())+ {+ self.note_remote_open_intent(domain_id);+ }+ self.activate_workspace_thread_impl(+ thread_id,+ window,+ page.orphan_candidate_window_id,+ page.workspaces_to_kill_after_adopt,+ );+ }++ /// Where a connection page that closes unconnected goes back to: the+ /// thread on screen, when it is one this Space shows (its own, or a+ /// reference or server folder thread opened in place), otherwise the+ /// Space just left.+ fn place_to_return_to(&self) -> (String, Option<String>) {+ let shown_thread = self.current_mux_workspace().and_then(|workspace| {+ crate::workspace_threads::thread_id_for_workspace(&self.active_space_id, &workspace)+ .or_else(|| {+ crate::workspace_threads::origin_space_for_ref_workspace(+ &self.active_space_id,+ &workspace,+ )+ .and_then(|_| crate::workspace_threads::thread_id_for_workspace_any(&workspace))+ })+ });+ if shown_thread.is_some() {+ return (self.active_space_id.clone(), shown_thread);+ }+ let space_id = self+ .previous_space_id+ .clone()+ .unwrap_or_else(crate::workspace_threads::default_space_id);+ (space_id, None)+ }++ /// A remote Space with nothing left to show: go back to the Space the+ /// window came from — or the default Space, when that one is gone,+ /// taken, or another unreachable server — instead of closing the+ /// window, which as the last one disconnected every server. A page+ /// opened in place goes back to the thread it stood in for.+ fn return_from_unreachable_space(+ &mut self,+ return_space_id: String,+ return_thread_id: Option<String>,+ window: &Window,+ ) {+ if return_space_id == self.active_space_id {+ // Only while it is still there: activating it otherwise would+ // build it again, or ask for another server.+ let live_workspaces = Mux::get().iter_workspaces();+ if let Some(thread_id) = return_thread_id.filter(|thread_id| {+ crate::workspace_threads::activation_plan_for_thread(thread_id, &live_workspaces)+ .is_some_and(|plan| !plan.needs_materialize)+ }) {+ self.activate_workspace_thread(thread_id, window);+ // Handed to another window that shows it: carry on below.+ if Mux::get().get_window(self.mux_window_id).is_some() {+ return;+ }+ }+ }+ // An in-place return can lose its original thread while the+ // server is away. It still has the same Space fallbacks -- and any+ // local Space free for this window, for when those are all this+ // server's own: the device's first window connected straight to it.+ let local_spaces = crate::workspace_threads::spaces_for_window(self.space_owner_id)+ .into_iter()+ .filter(|space| !space.is_remote && !space.is_occupied_by_other_window)+ .map(|space| space.id);+ let candidates = std::iter::once(return_space_id)+ .chain(self.previous_space_id.clone())+ .chain(std::iter::once(crate::workspace_threads::default_space_id()))+ .chain(local_spaces);+ for space_id in candidates {+ let reachable = crate::workspace_threads::client_domain_for_space(&space_id)+ .map_or(true, |domain_name| domain_is_attached(&domain_name));+ if space_id != self.active_space_id+ && reachable+ && self.switch_space_to_thread(space_id, None, window)+ {+ return;+ }+ }+ if crate::workspace_threads::client_domain_for_space(&self.active_space_id).is_none() {+ if let Some(thread_id) =+ crate::workspace_threads::thread_to_recover_after_window_death(&self.active_space_id)+ {+ self.activate_workspace_thread(thread_id, window);+ return;+ }+ }+ // The last window, with no local Space to go to: closing it would+ // end every connection, so a new Space of its own.+ if front_end().gui_windows().len() <= 1 {+ let space_id = crate::workspace_threads::create_space(None);+ if self.switch_space_to_thread(space_id, None, window) {+ return;+ }+ }+ window.close();+ front_end().forget_known_window(window);+ }+/// The sidebar Reconnect button: bring the active Space's mux domain/// back. A parked retry loop (gave up after continuous failure) is/// resumed in place; a detached or never-connected domain is attached@@ -6749,6 +7141,35 @@ impl TermWindow {else {return;};+ // This server's connection page gave up and is still on screen: try+ // it again, so that what it was for opens once the server answers+ // and the failure goes with it.+ let failed_page = self+ .space_connection_page+ .as_ref()+ .filter(|page| {+ page.gave_up+ && page.mux_window_id == self.mux_window_id+ && page.domain_name == domain_name+ })+ .map(|page| {+ (+ page.thread_id.clone(),+ page.orphan_candidate_window_id,+ page.workspaces_to_kill_after_adopt.clone(),+ )+ });+ if let (Some((thread_id, orphan_candidate_window_id, workspaces_to_kill)), Some(window)) =+ (failed_page, self.window.clone())+ {+ self.activate_workspace_thread_impl(+ thread_id,+ &window,+ orphan_candidate_window_id,+ workspaces_to_kill,+ );+ 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);@@ -7404,7 +7825,7 @@ impl TermWindow {self.clear_right_sidebar_text_focus();self.set_content_view_active(false);self.remember_workspace_sidebar_scroll();- self.active_space_id = space_id.clone();+ self.previous_space_id = Some(std::mem::replace(&mut self.active_space_id, space_id.clone()));self.refresh_active_space_note_vault_flag();self.sync_content_view_surfaces_with_mux();self.workspace_sidebar_scroll_offset = self.remembered_workspace_sidebar_scroll();diff --git a/wezterm-gui/src/termwindow/mouseevent.rs b/wezterm-gui/src/termwindow/mouseevent.rsindex 43dd6ab1..fea54872 100644--- a/wezterm-gui/src/termwindow/mouseevent.rs+++ b/wezterm-gui/src/termwindow/mouseevent.rs@@ -174,6 +174,73 @@ fn space_destructive_menu_items()]}+/// A server's row in the one-row-per-server Space menu: a server with one+/// Space switches to it from the row itself; one with several opens them,+/// and a new one, in a submenu.+fn server_menu_row(+ label: String,+ domain: &str,+ spaces: &[&crate::workspace_threads::SpaceView],+) -> ContextMenuItem {+ if let [space] = spaces {+ let item = ContextMenuItem::item_with_icon(+ label,+ ContextMenuIcon::Server,+ KeyAssignment::SwitchSpace(space.id.to_string()),+ );+ return if space.is_occupied_by_other_window {+ item.disabled()+ } else {+ item+ };+ }+ let mut children: Vec<ContextMenuItem> = spaces+ .iter()+ .map(|space| {+ let item = ContextMenuItem::item_with_icon(+ if space.is_occupied_by_other_window {+ tr_with_name("menu-space-occupied", &space.name)+ } else {+ space.name.clone()+ },+ ContextMenuIcon::Stack,+ KeyAssignment::SwitchSpace(space.id.to_string()),+ );+ if space.is_occupied_by_other_window {+ item.disabled()+ } else {+ item+ }+ })+ .collect();+ children.push(ContextMenuItem::Separator);+ children.push(ContextMenuItem::item_with_icon(+ crate::i18n::tr("menu-new-space-here"),+ ContextMenuIcon::New,+ KeyAssignment::CreateSpaceOnDomain(domain.to_string()),+ ));+ ContextMenuItem::submenu_with_icon(label, ContextMenuIcon::Server, children)+}++/// "New Space on Server": one row per server, (label, mux domain), each+/// making a Space there.+fn new_space_on_server_menu(servers: Vec<(String, String)>) -> ContextMenuItem {+ ContextMenuItem::submenu_with_icon(+ crate::i18n::tr("menu-new-space-on-server"),+ ContextMenuIcon::Server,+ servers+ .into_iter()+ .map(|(label, domain)| {+ ContextMenuItem::item_with_icon(+ label,+ ContextMenuIcon::Server,+ KeyAssignment::CreateSpaceOnDomain(domain),+ )+ })+ .collect(),+ )+}+fn note_drag_scroll_delta(pointer_y: f32,top: f32,@@ -5984,9 +6051,16 @@ impl super::TermWindow {return;};// Reference rows reorder the local reference list, so the- // origin thread's pinned state is irrelevant there.- let draggable = self.sidebar_row_is_thread_ref(&thread_id)- || !crate::workspace_threads::thread_is_pinned(&thread_id);+ // origin thread's pinned state is irrelevant there. A server+ // folder row has no reference to move, so it stays put.+ let draggable = if self.sidebar_row_is_thread_ref(&thread_id) {+ crate::workspace_threads::thread_ref_is_explicit(+ &self.active_space_id,+ &thread_id,+ )+ } else {+ !crate::workspace_threads::thread_is_pinned(&thread_id)+ };let title = crate::workspace_threads::thread_name(&thread_id).unwrap_or_else(|| thread_id.clone());self.arm_sidebar_row_drag(@@ -6336,18 +6410,51 @@ impl super::TermWindow {for space in spaces.iter().filter(|space| space.domain.is_none()) {items.push(space_item(space));}+ // While servers show as folders their Spaces are not listed: they+ // live in a local Space's sidebar. One opened from its folder stays+ // listed while it is open, so the menu still says where the window+ // is.+ if let Some(space) = spaces+ .iter()+ .find(|space| space.shown_as_folders && space.is_active)+ {+ items.push(+ ContextMenuItem::item_with_icon(+ space.name.clone(),+ ContextMenuIcon::Server,+ KeyAssignment::SwitchSpace(space.id.to_string()),+ )+ .checked(true),+ );+ }// Keep the servers in the order their Spaces appear rather than// sorting: that order is the user's.let mut domains: Vec<&str> = vec![];- for domain in spaces.iter().filter_map(|space| space.domain.as_deref()) {+ for domain in spaces+ .iter()+ .filter(|space| !space.shown_as_folders)+ .filter_map(|space| space.domain.as_deref())+ {if !domains.contains(&domain) {domains.push(domain);}}- for domain in domains {- items.push(ContextMenuItem::Separator);+ // Folded to one row each, servers sit together; the one the window+ // is on stays spelled out, so moving between its Spaces is one click.+ let one_row = crate::native_settings::space_menu_one_row_per_server();+ let mut last_was_row = false;+ for domain in domains.iter().copied() {+ let here: Vec<&crate::workspace_threads::SpaceView> = spaces+ .iter()+ .filter(|space| space.domain.as_deref() == Some(domain))+ .collect();+ let collapsed = one_row && !here.iter().any(|space| space.is_active);+ if !(collapsed && last_was_row) {+ items.push(ContextMenuItem::Separator);+ }+ last_was_row = collapsed;let state = spaces.iter().find(|space| space.domain.as_deref() == Some(domain))@@ -6371,6 +6478,10 @@ impl super::TermWindow {tr_with_name("menu-space-server-group-offline", &name)}};+ if collapsed {+ items.push(server_menu_row(header, domain, &here));+ continue;+ }// A server is a heading, not something to switch to. Saying that// with a section header rather than a disabled row is what makes it// *look* like a heading: the platform styles it as a caption and@@ -6406,6 +6517,21 @@ impl super::TermWindow {ContextMenuIcon::New,KeyAssignment::CreateSpace,));+ // A server folded to a single row has no "New Space Here" of its+ // own; they all gather here, one per server.+ if one_row && !domains.is_empty() {+ items.push(new_space_on_server_menu(+ domains+ .iter()+ .map(|domain| {+ (+ crate::ssh_hosts::connect_domain_label(domain),+ domain.to_string(),+ )+ })+ .collect(),+ ));+ }items.push(ContextMenuItem::item_with_icon(spaces.iter()@@ -6753,41 +6879,45 @@ impl super::TermWindow {// holding it).if is_thread_ref {items.push(ContextMenuItem::Separator);- let remove_item = self.context_menu_application_item_with_icon(- crate::i18n::tr("menu-remove-thread-ref"),- ContextMenuIcon::Close,- crate::termwindow::ContextMenuApplicationAction::RemoveThreadFromCollection {- collection_space_id: active_space.clone(),- thread_id: thread_id.clone(),- },- true,- );- items.push(remove_item);- // Move the REFERENCE elsewhere: gone from this Space's list,- // added to the target's. ref_host_candidates already excludes- // the origin and every Space holding it — this one included.- let move_targets: Vec<ContextMenuItem> =- crate::workspace_threads::ref_host_candidates(&thread_id)- .into_iter()- .map(|(space_id, name)| {- self.context_menu_application_item_with_icon(- name,- ContextMenuIcon::ExternalLink,- crate::termwindow::ContextMenuApplicationAction::MoveThreadRefToSpace {- from_space_id: active_space.clone(),- space_id,- thread_id: thread_id.clone(),- },- true,- )- })- .collect();- if !move_targets.is_empty() {- items.push(ContextMenuItem::submenu_with_icon(- crate::i18n::tr("menu-move-to-space"),- ContextMenuIcon::ExternalLink,- move_targets,- ));+ // A server folder row has no reference of its own to remove or+ // move: it shows for as long as its server shows here.+ if crate::workspace_threads::thread_ref_is_explicit(&active_space, &thread_id) {+ let remove_item = self.context_menu_application_item_with_icon(+ crate::i18n::tr("menu-remove-thread-ref"),+ ContextMenuIcon::Close,+ crate::termwindow::ContextMenuApplicationAction::RemoveThreadFromCollection {+ collection_space_id: active_space.clone(),+ thread_id: thread_id.clone(),+ },+ true,+ );+ items.push(remove_item);+ // Move the REFERENCE elsewhere: gone from this Space's list,+ // added to the target's. ref_host_candidates already excludes+ // the origin and every Space holding it — this one included.+ let move_targets: Vec<ContextMenuItem> =+ crate::workspace_threads::ref_host_candidates(&thread_id)+ .into_iter()+ .map(|(space_id, name)| {+ self.context_menu_application_item_with_icon(+ name,+ ContextMenuIcon::ExternalLink,+ crate::termwindow::ContextMenuApplicationAction::MoveThreadRefToSpace {+ from_space_id: active_space.clone(),+ space_id,+ thread_id: thread_id.clone(),+ },+ true,+ )+ })+ .collect();+ if !move_targets.is_empty() {+ items.push(ContextMenuItem::submenu_with_icon(+ crate::i18n::tr("menu-move-to-space"),+ ContextMenuIcon::ExternalLink,+ move_targets,+ ));+ }}if let Some(origin_space) = crate::workspace_threads::thread_space_id(&thread_id) {let origin_item = self.context_menu_application_item_with_icon(@@ -6895,13 +7025,79 @@ impl super::TermWindow {}};// Reference it before activating: the activation gate only lets this- // window open threads its Space owns or references.- crate::workspace_threads::add_thread_ref(&self.active_space_id, &thread_id);+ // window open threads its Space owns or references. A server folder+ // shows its new thread without one.+ if !crate::workspace_threads::thread_ref_exists(&self.active_space_id, &thread_id) {+ crate::workspace_threads::add_thread_ref(&self.active_space_id, &thread_id);+ }if !self.open_remote_workspace_thread_without_connecting(&thread_id, context) {self.activate_workspace_thread(thread_id, context);}}+ /// While servers show as folders, connecting the server `domain_name`+ /// leaves this window in its Space: the server's folders show here from+ /// now on, and its thread opens in place -- through the connection page,+ /// as any folder thread of a server not yet connected does. Returns+ /// false to have the caller connect the usual way, into the server's own+ /// Space: always when servers keep Spaces of their own; when this window+ /// is on a server's own Space, which shows no folders; and while this+ /// device has not heard from the server yet -- the first connect seeds+ /// the Space it invents on the server (`connect_domain_into_space`), and+ /// only that way falls back to plain ssh when the host has no ThinkTerm.+ /// Its folders land here either way.+ pub(crate) fn connect_server_into_folder(+ &mut self,+ domain_name: &str,+ context: &dyn WindowOps,+ ) -> bool {+ if !crate::native_settings::servers_as_folders() {+ return false;+ }+ let known = crate::workspace_threads::known_mux_domain_space(domain_name);+ if known.is_some() {+ // The plan may have added a row here the server has not seen,+ // which its next tree would take away again.+ crate::workspace_threads::reconcile_remote_subtree(domain_name);+ }+ let plan = known+ .clone()+ .unwrap_or_else(|| crate::workspace_threads::ensure_mux_domain_space(domain_name));+ let moved =+ crate::workspace_threads::place_server_folder(&plan.space_id, &self.active_space_id);+ if moved {+ // The folders left another Space: a window there showing one of+ // the server's threads lets it go.+ for gui_window in crate::frontend::front_end().gui_windows() {+ gui_window+ .window+ .notify(TermWindowNotif::Apply(Box::new(|term_window| {+ term_window.leave_server_folder_content_if_hidden();+ })));+ }+ }+ if known.is_none()+ || !crate::workspace_threads::thread_ref_exists(&self.active_space_id, &plan.thread_id)+ {+ return false;+ }+ if moved {+ // Once those windows have let go: one still showing the thread+ // would be handed it, and focused, and then let it go.+ if let Some(window) = self.window.clone() {+ let thread_id = plan.thread_id;+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {+ if let Some(window) = term_window.window.clone() {+ term_window.activate_workspace_thread(thread_id, &window);+ }+ })));+ return true;+ }+ }+ self.activate_workspace_thread(plan.thread_id, context);+ true+ }+pub(crate) fn create_workspace_thread(&mut self, project_id: &str, context: &dyn WindowOps) {let thread_id = match crate::workspace_threads::create_thread(project_id, None) {Ok(thread_id) => thread_id,@@ -6954,6 +7150,9 @@ impl super::TermWindow {let name = crate::ssh_hosts::connect_name_after_rename(&crate::ssh_hosts::connect_domain_name(&spec),);+ if self.connect_server_into_folder(&name, context) {+ return true;+ }// 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@@ -7340,7 +7539,7 @@ impl super::TermWindow {!= Some(self.active_space_id.as_str())}- fn activate_workspace_thread_impl(+ pub(super) fn activate_workspace_thread_impl(&mut self,thread_id: String,context: &dyn WindowOps,@@ -7497,14 +7696,38 @@ impl super::TermWindow {.get_domain_by_name(domain_name).map_or(false, |d| d.state() == mux::domain::DomainState::Attached);if !attached {- // Attach on demand (auth prompts go through the ConnectionUI),- // then re-run this activation once the domain is live.+ // Attach on demand (auth prompts go through the ConnectionUI,+ // on a page of the Space's own), then open the thread once+ // the domain is live.let Some(window) = self.window.clone() else {context.invalidate();return;};let domain_name = domain_name.to_string();- let mux_window_id = self.mux_window_id;+ let Some(page_window_id) = self.show_space_connection_page(+ &domain_name,+ thread_id,+ orphan_candidate_window_id,+ workspaces_to_kill_after_adopt,+ ) else {+ // The Space's page is connecting already.+ context.invalidate();+ return;+ };+ // The page's window is empty until the ConnectionUI's tab+ // lands in it; nothing may prune it before then.+ let page_activity = mux::activity::Activity::new();+ // Open while it holds the page; empty before the tab lands,+ // and again once the person closed it.+ let mut page_seen = false;+ let page_is_open = move || match Mux::get().get_window(page_window_id) {+ Some(page) if !page.is_empty() => {+ page_seen = true;+ true+ }+ Some(_) => !page_seen,+ None => false,+ };// Bridge the frames between this switch and the retry engine// raising its own in-flight flag: without it the sidebar// paints "Disconnected — Reconnect" for the gap.@@ -7523,24 +7746,27 @@ impl super::TermWindow {};let ui = mux::connui::ConnectionUI::with_params(mux::connui::ConnectionUIParams {- window_id: Some(mux_window_id),+ window_id: Some(page_window_id),..Default::default()},);+ // No primary window: none of the server's windows+ // belongs in the page's.let outcome = crate::attach_domain_with_retry(domain,- Some(mux_window_id),+ None,ui,- move || Mux::get().get_window(mux_window_id).is_some(),+ page_is_open,Some(std::time::Duration::from_secs(60)),).await?;anyhow::Ok(matches!(outcome, crate::AttachRetryOutcome::Attached))}.await;+ drop(page_activity);let cleanup_name = domain_name.clone();match result {- // Cancelled (the hosting window went away mid-retry)+ // Cancelled (the page was closed or left mid-retry)// leaves nothing to activate.Ok(false) => {}Ok(true) => {@@ -7548,27 +7774,14 @@ impl super::TermWindow {.get_domain_by_name(&domain_name).map(|domain| domain.domain_id());window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {- // Switching into a cold mux-domain Space is as- // explicit an open as the Connect button, so it- // gets the same one-shot claim. Armed only: the- // retried activation releases it when its tab- // is on screen, and the paint path consumes it- // once that tab's gate is claimable.- if let Some(domain_id) = domain_id {- term_window.note_remote_open_intent(domain_id);- }- if let Some(win) = term_window.window.clone() {- term_window.activate_workspace_thread_impl(- thread_id,- &win,- orphan_candidate_window_id,- workspaces_to_kill_after_adopt,- );- }+ term_window.open_connected_space_page(page_window_id, domain_id);})));}Err(err) => {log::error!("attaching {domain_name} for thread switch: {err:#}");+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {+ term_window.note_space_connection_page_gave_up(page_window_id);+ })));}}window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {@@ -10375,6 +10588,7 @@ mod space_menu_tests {is_remote,domain: is_remote.then(|| "DO SYD X user".to_string()),is_domain_attached: false,+ shown_as_folders: false,}}@@ -10414,6 +10628,72 @@ mod space_menu_tests {);}+ fn server_space(id: &str, occupied: bool) -> SpaceView {+ SpaceView {+ id: id.to_string(),+ name: id.to_string(),+ is_active: false,+ is_occupied_by_other_window: occupied,+ ..space(true)+ }+ }++ fn action(item: &ContextMenuItem) -> KeyAssignment {+ actions(std::slice::from_ref(item)).remove(0)+ }++ /// Folded to one row, a server with one Space is that Space: the row+ /// switches straight to it, with nothing to open.+ #[test]+ fn a_server_with_one_space_switches_from_its_row() {+ let only = server_space("s1", false);+ let row = super::server_menu_row("devbox".to_string(), "devbox", &[&only]);+ assert!(submenu_of(&row).is_empty());+ assert_eq!(action(&row), KeyAssignment::SwitchSpace("s1".to_string()));+ }++ /// Several Spaces open from the row, with a new one after them.+ #[test]+ fn a_server_with_several_spaces_opens_them_from_its_row() {+ let (first, second) = (server_space("s1", false), server_space("s2", false));+ let row = super::server_menu_row("devbox".to_string(), "devbox", &[&first, &second]);+ let children = submenu_of(&row);+ assert_eq!(children.len(), 4);+ assert!(matches!(children[2], ContextMenuItem::Separator));+ assert_eq!(+ [&children[0], &children[1], &children[3]].map(action),+ [+ KeyAssignment::SwitchSpace("s1".to_string()),+ KeyAssignment::SwitchSpace("s2".to_string()),+ KeyAssignment::CreateSpaceOnDomain("devbox".to_string()),+ ]+ );+ }++ /// A Space open in another window cannot be switched to from here, so+ /// the row of a server that has only that one is greyed.+ #[test]+ fn a_server_whose_only_space_is_open_elsewhere_is_greyed() {+ let only = server_space("s1", true);+ let row = super::server_menu_row("devbox".to_string(), "devbox", &[&only]);+ assert!(matches!(row, ContextMenuItem::Item { enabled: false, .. }));+ }++ #[test]+ fn new_space_on_server_offers_every_server() {+ let menu = super::new_space_on_server_menu(vec![+ ("devbox".to_string(), "devbox".to_string()),+ ("server-b".to_string(), "server-b".to_string()),+ ]);+ assert_eq!(+ actions(submenu_of(&menu)),+ vec![+ KeyAssignment::CreateSpaceOnDomain("devbox".to_string()),+ KeyAssignment::CreateSpaceOnDomain("server-b".to_string()),+ ]+ );+ }+/// The four lines that prompted this: one parent row carrying the name,/// with the actions underneath.#[test]diff --git a/wezterm-gui/src/termwindow/resize.rs b/wezterm-gui/src/termwindow/resize.rsindex a8f75925..71c5a028 100644--- a/wezterm-gui/src/termwindow/resize.rs+++ b/wezterm-gui/src/termwindow/resize.rs@@ -1285,6 +1285,8 @@ impl super::TermWindow {}pub(crate) fn finish_remote_open(&mut self, domain_id: mux::domain::DomainId) {+ // Got through: from here on the window is the Space's like any.+ self.opened_to_connect = false;if let Some(intent) = self.remote_open_intent.as_mut() {if intent.domain_id == domain_id {intent.ready = true;diff --git a/wezterm-gui/src/termwindow/ui/command_palette.rs b/wezterm-gui/src/termwindow/ui/command_palette.rsindex 5ff00b60..3edefc59 100644--- a/wezterm-gui/src/termwindow/ui/command_palette.rs+++ b/wezterm-gui/src/termwindow/ui/command_palette.rs@@ -1398,7 +1398,12 @@ impl crate::TermWindow {}fn build_space_group(&self) -> Option<PaletteGroup> {- let spaces = crate::workspace_threads::spaces_for_window(self.space_owner_id);+ // A server shown as folders is reached from its folder, as in the+ // Space menu; the one open now still names the current value.+ let spaces: Vec<_> = crate::workspace_threads::spaces_for_window(self.space_owner_id)+ .into_iter()+ .filter(|space| !space.shown_as_folders || space.is_active)+ .collect();if spaces.len() < GROUP_FOLD_THRESHOLD {return None;}diff --git a/wezterm-gui/src/termwindow/ui/context_menu.rs b/wezterm-gui/src/termwindow/ui/context_menu.rsindex 23699abd..c8970165 100644--- a/wezterm-gui/src/termwindow/ui/context_menu.rs+++ b/wezterm-gui/src/termwindow/ui/context_menu.rs@@ -273,6 +273,31 @@ impl crate::TermWindow {}}+ /// A server's thread on screen through a folder this Space no longer+ /// shows -- the folder went to another Space, or servers keep Spaces of+ /// their own again -- is let go of like a removed reference. Kept up,+ /// its terminal would have no row in the sidebar, and Files would look+ /// at this machine (`content_space_id`).+ pub(crate) fn leave_server_folder_content_if_hidden(&mut self) {+ let Some(workspace) = self.current_mux_workspace() else {+ return;+ };+ let Some(home) = crate::workspace_threads::space_id_for_workspace(&workspace) else {+ return;+ };+ if home == self.active_space_id+ || crate::workspace_threads::client_domain_for_space(&home).is_none()+ || crate::workspace_threads::origin_space_for_ref_workspace(+ &self.active_space_id,+ &workspace,+ )+ .is_some()+ {+ return;+ }+ self.leave_detached_ref_content();+ }+pub(crate) fn perform_context_menu_application_action(&mut self, action_id: u64) {let Some(action) = self.context_menu_application_actionsdiff --git a/wezterm-gui/src/termwindow/ui/sidebar.rs b/wezterm-gui/src/termwindow/ui/sidebar.rsindex 5bd2b2f1..33211d5e 100644--- a/wezterm-gui/src/termwindow/ui/sidebar.rs+++ b/wezterm-gui/src/termwindow/ui/sidebar.rs@@ -2765,9 +2765,15 @@ impl crate::TermWindow {disclosure_size,muted_fg,)?;+ // A server folder is the server itself, not a link to+ // threads picked one by one.self.paint_sidebar_icon(layers,- SvgIcon::Link2,+ if group.server_folder {+ SvgIcon::Server+ } else {+ SvgIcon::Link2+ },group_icon_x,icon_y,icon_size,@@ -2975,7 +2981,16 @@ impl crate::TermWindow {&chrome,foreground,)?;- let text_right = if is_hovered { delete_x } else { marks_right };+ // Only a reference can be taken out: a row a server+ // folder shows, with none of its own, stays as long+ // as the folder does.+ let removable = is_hovered+ && (!reference.server_folder+ || workspace_threads::thread_ref_is_explicit(+ self.workspace_sidebar_space_id(),+ &session.id,+ ));+ let text_right = if removable { delete_x } else { marks_right };let text_fg = if dimmed {muted_fg.mul_alpha(0.7)} else if is_selected {@@ -2994,7 +3009,7 @@ impl crate::TermWindow {text_fg,)?;- if is_hovered {+ if removable {// An X, not a trash can: removing a reference// leaves the origin thread running untouched.let hovered = self.is_pointer_over_ui_rect(diff --git a/wezterm-gui/src/workspace_threads.rs b/wezterm-gui/src/workspace_threads.rsindex 41ad49d5..84e2a191 100644--- a/wezterm-gui/src/workspace_threads.rs+++ b/wezterm-gui/src/workspace_threads.rs@@ -53,6 +53,33 @@ pub struct WorkspaceThreadStore {#[serde(default, skip_serializing_if = "Vec::is_empty")]pub imported_sessions: Vec<ImportedSession>,pub projects: Vec<Project>,+ /// While servers show as folders: the local Space each server's Spaces+ /// show in, mux domain → local Space id, set by connecting the server+ /// from that Space. Kept by server rather than by Space, because the+ /// Space a first connect invents gives way to the server's own once its+ /// tree arrives. A server not listed shows in `server_folder_host_space`.+ /// Per-device, like the fields above.+ #[serde(default, skip_serializing_if = "HashMap::is_empty")]+ pub server_folder_spaces: HashMap<String, SpaceId>,+ /// Mux domains whose server has sent this device its tree at least once.+ /// A server Space of any other domain is only what a first connect+ /// invented -- possibly one that never got through -- so it does not+ /// make the server known yet (`known_mux_domain_space`).+ #[serde(default, skip_serializing_if = "std::collections::BTreeSet::is_empty")]+ pub synced_server_domains: std::collections::BTreeSet<String>,+ /// Servers whose Space a connect from here invented and that have not+ /// sent their tree since: their folders stay out of sight, so a first+ /// connect that never gets through -- it fails, or the install it needs+ /// is turned down -- leaves no folder behind.+ #[serde(default, skip_serializing_if = "std::collections::BTreeSet::is_empty")]+ pub invented_server_domains: std::collections::BTreeSet<String>,+ /// The Appearance choice to show servers as folders in this device's+ /// Spaces (see `NativeServerPlacement`), mirrored so store methods can+ /// follow it without reading settings under the store's lock. Entry+ /// points that depend on it refresh it first; see+ /// `lock_store_following_settings`.+ #[serde(skip)]+ pub servers_as_folders: bool,}/// One session the Import page brought in, and the Space it became.@@ -387,6 +414,9 @@ pub struct ThreadRefGroupView {/// Whether the origin domain is currently attached; a detached group's/// rows paint dimmed.pub attached: bool,+ /// A server folder: the group shows a server's project because servers+ /// are set to show as folders, not (only) threads referenced one by one.+ pub server_folder: bool,/// Filled in by the sidebar from its runtime collapse state before/// painting/geometry/hit-testing (never persisted here).pub collapsed: bool,@@ -457,6 +487,9 @@ pub struct ThreadRefView {/// it should try to attach `machine_label`'s domain rather than/// activate directly.pub dangling: bool,+ /// The row's project is one of the Space's server folders (servers show+ /// as folders there). The Space may hold a reference to it as well.+ pub server_folder: bool,}#[derive(Debug, Clone, Copy, PartialEq, Eq)]@@ -643,6 +676,10 @@ pub struct SpaceView {/// Always false for local Spaces; consult `is_swipe_reachable` instead of/// reading this directly.pub is_domain_attached: bool,+ /// A remote Space while servers show as folders: its threads appear in+ /// a local Space, so the Space menu and swipes pass it by. It can still+ /// be opened from its folder.+ pub shown_as_folders: bool,}impl SpaceView {@@ -655,7 +692,9 @@ impl SpaceView {/// connection UI and error reporting) instead of parking the gesture on a/// page that may take ten seconds to exist or never arrive.pub fn is_swipe_reachable(&self) -> bool {- !self.is_occupied_by_other_window && (!self.is_remote || self.is_domain_attached)+ !self.is_occupied_by_other_window+ && !self.shown_as_folders+ && (!self.is_remote || self.is_domain_attached)}}@@ -665,7 +704,16 @@ pub fn adjacent_swipe_space_ids() -> (Option<SpaceId>, Option<SpaceId>) {let reachable = spaces.iter()- .filter(|space| space.is_swipe_reachable())+ .filter(|space| {+ space.is_swipe_reachable()+ // A window on a server's own Space, which swipes pass by+ // while servers show as folders, swipes out of it all the+ // same: it is on screen, and the server there.+ || (space.id == active_space_id+ && space.shown_as_folders+ && !space.is_occupied_by_other_window+ && (!space.is_remote || space.is_domain_attached))+ }).collect::<Vec<_>>();let Some(index) = reachable.iter()@@ -814,10 +862,19 @@ pub fn workspace_thread_store_is_unreadable() -> bool {}pub fn load_workspace_thread_store() -> Result<WorkspaceThreadStore> {- load_workspace_thread_store_from_path(&workspace_thread_store_path())+ // The groom as it loads keeps a server folder's thread a Space reopens+ // only while servers show as folders: it has to know first.+ load_store_from_path(+ &workspace_thread_store_path(),+ crate::native_settings::servers_as_folders(),+ )}pub fn load_workspace_thread_store_from_path(path: &Path) -> Result<WorkspaceThreadStore> {+ load_store_from_path(path, false)+}++fn load_store_from_path(path: &Path, servers_as_folders: bool) -> Result<WorkspaceThreadStore> {if !path.exists() {return Ok(WorkspaceThreadStore::default());}@@ -834,6 +891,7 @@ pub fn load_workspace_thread_store_from_path(path: &Path) -> Result<WorkspaceThr}let mut store: WorkspaceThreadStore =serde_json::from_value(value).with_context(|| format!("parse {}", path.display()))?;+ store.servers_as_folders = servers_as_folders;store.normalize_after_load();Ok(store)}@@ -1328,10 +1386,11 @@ pub fn switch_window_space(owner_id: u64, space_id: &str) -> bool {pub fn spaces_for_window(owner_id: u64) -> Vec<SpaceView> {let active_space_id = space_for_window(owner_id);let occupied = WINDOW_SPACES.lock().clone();- let mut store = THREAD_STORE.lock();+ let mut store = lock_store_following_settings();if store.normalize_after_load() {persist_locked(&store);}+ let folders = store.servers_as_folders;let mut views: Vec<SpaceView> = store.spaces.iter()@@ -1346,6 +1405,7 @@ pub fn spaces_for_window(owner_id: u64) -> Vec<SpaceView> {is_remote: space.client_domain.is_some(),domain: space.client_domain.clone(),is_domain_attached: false,+ shown_as_folders: folders && space.client_domain.is_some(),}).collect();// Resolved after the store lock is released: the mux takes its own locks@@ -1577,6 +1637,16 @@ pub fn move_thread_ref_before(moved}+/// The store, with `servers_as_folders` brought up to date first. The+/// setting is read before the lock is taken, so the store never waits on+/// the settings while it is held.+fn lock_store_following_settings() -> parking_lot::MutexGuard<'static, WorkspaceThreadStore> {+ let folders = crate::native_settings::servers_as_folders();+ let mut store = THREAD_STORE.lock();+ store.servers_as_folders = folders;+ store+}+/// The reference list of a Space, in display order.pub fn space_thread_refs(host_space_id: &str) -> Vec<String> {THREAD_STORE@@ -1591,7 +1661,8 @@ pub fn space_thread_refs(host_space_id: &str) -> Vec<String> {/// Remember which reference the user last opened from this Space, so the/// next switch back restores it.pub fn note_thread_active_ref(host_space_id: &str, thread_id: &str) {- let mut store = THREAD_STORE.lock();+ let mut store = lock_store_following_settings();+ let in_server_folder = store.shows_server_folder_thread(host_space_id, thread_id);let Some(space) = store.spaces.iter_mut()@@ -1599,7 +1670,7 @@ pub fn note_thread_active_ref(host_space_id: &str, thread_id: &str) {else {return;};- if !space.thread_refs.iter().any(|id| id == thread_id) {+ if !in_server_folder && !space.thread_refs.iter().any(|id| id == thread_id) {return;}if space.active_thread_ref.as_deref() != Some(thread_id) {@@ -1625,10 +1696,22 @@ pub fn clear_thread_active_ref(host_space_id: &str) {}}+/// Whether `host_space_id` opens `thread_id` in place: it holds a reference+/// to it, or shows it in one of its server folders.pub fn thread_ref_exists(host_space_id: &str, thread_id: &str) -> bool {- THREAD_STORE.lock().spaces.iter().any(|space| {- space.id == host_space_id && space.thread_refs.iter().any(|id| id == thread_id)- })+ let store = lock_store_following_settings();+ store.holds_thread_ref(host_space_id, thread_id)+ || store.shows_server_folder_thread(host_space_id, thread_id)+}++/// Whether `host_space_id` holds a reference of its own to `thread_id`, as+/// opposed to showing it in a server folder. Only such a row can be taken+/// out of the Space or moved to another one; a server folder row stays as+/// long as its server shows there.+pub fn thread_ref_is_explicit(host_space_id: &str, thread_id: &str) -> bool {+ THREAD_STORE+ .lock()+ .holds_thread_ref(host_space_id, thread_id)}/// Deliberate host deletion: drop every Space's references whose origin@@ -1647,10 +1730,18 @@ pub fn purge_thread_refs_for_machines(machines: &[String]) -> bool {/// The origin project a reference group's "+" should create a thread in./// Group keys are origin project ids, so this only confirms the key names-/// the project of some resolvable ref in `host_space_id`'s list (a machine-/// fallback key for dangling groups never matches).+/// one of `host_space_id`'s server folders or the project of some+/// resolvable ref in its list (a machine fallback key for dangling groups+/// never matches).pub fn ref_group_origin_project(host_space_id: &str, group_key: &str) -> Option<ProjectId> {- let store = THREAD_STORE.lock();+ let store = lock_store_following_settings();+ if store+ .server_folder_projects(host_space_id)+ .iter()+ .any(|project| project.id == group_key)+ {+ return Some(group_key.to_string());+ }let space = store.spaces.iter()@@ -1816,6 +1907,20 @@ pub fn move_thread_ref_to_space(/// `wezterm-mux://` sentinel path) and its first thread come along, because a/// Space with nothing in it has nowhere to put a terminal.pub fn create_space_on_domain(domain_name: &str, name: Option<String>) -> Result<SpaceId> {+ new_space_on_domain(domain_name, name, true)+}++/// As `create_space_on_domain`, for a window staying where it is: see+/// `add_space`.+pub fn add_space_on_domain(domain_name: &str, name: Option<String>) -> Result<SpaceId> {+ new_space_on_domain(domain_name, name, false)+}++fn new_space_on_domain(+ domain_name: &str,+ name: Option<String>,+ make_last_active: bool,+) -> Result<SpaceId> {ensure!(remote_tree_mutation_allowed(Some(domain_name)),"{domain_name} is disconnected"@@ -2251,24 +2356,31 @@ pub fn space_id_for_workspace(workspace: &str) -> Option<SpaceId> {}/// The origin Space of `workspace`, but only when the thread it is bound to-/// is actually referenced by `host_space_id`. A window that was just-/// switched to (nothing clicked yet) still displays the previous Space's-/// workspace — that one must NOT leak through, or Files/paste would-/// silently keep targeting the previous machine.+/// is actually referenced by `host_space_id`, or shown in one of its server+/// folders. A window that was just switched to (nothing clicked yet) still+/// displays the previous Space's workspace — that one must NOT leak+/// through, or Files/paste would silently keep targeting the previous+/// machine.pub fn origin_space_for_ref_workspace(host_space_id: &str, workspace: &str) -> Option<SpaceId> {- let store = THREAD_STORE.lock();+ let store = lock_store_following_settings();let space = store.spaces.iter().find(|space| space.id == host_space_id)?;+ let server_folders: Vec<&str> = store+ .server_folder_projects(host_space_id)+ .iter()+ .map(|project| project.id.as_str())+ .collect();store.projects.iter().find_map(|project| {+ let in_server_folder = server_folders.contains(&project.id.as_str());project.threads.iter().any(|session| {(session.materialized_workspace_name.as_deref() == Some(workspace)|| workspace_name_for_thread(&project.id, &session.id) == workspace)- && space.thread_refs.iter().any(|id| id == &session.id)+ && (in_server_folder || space.thread_refs.iter().any(|id| id == &session.id))}).then(|| project.space_id.clone())})@@ -2545,6 +2657,7 @@ fn group_thread_refs_by_origin(refs: Vec<ThreadRefView>) -> Vec<ThreadRefGroupVimatch groups.iter_mut().find(|group| group.key == key) {Some(group) => {group.attached |= reference.origin_domain_attached;+ group.server_folder |= reference.server_folder;group.threads.push(reference);}None => groups.push(ThreadRefGroupView {@@ -2558,6 +2671,7 @@ fn group_thread_refs_by_origin(refs: Vec<ThreadRefView>) -> Vec<ThreadRefGroupVimachine_is_local: reference.machine_is_local,origin_space_name: reference.origin_space_name.clone(),attached: reference.origin_domain_attached,+ server_folder: reference.server_folder,collapsed: false,threads: vec![reference],}),@@ -2619,6 +2733,61 @@ pub fn thread_to_recover_after_window_death(space_id: &str) -> Option<WorkspaceTif !store.has_space(space_id) {return None;}+ if let Some(thread_id) = other_thread_after_window_death(&store, space_id) {+ return Some(thread_id);+ }++ let active_project_id = store.active_project_id_for_space(space_id);+ let project_id = active_project_id+ .filter(|project_id| {+ store+ .projects+ .iter()+ .any(|p| p.space_id == space_id && &p.id == project_id && !p.is_archived())+ })+ .or_else(|| {+ store+ .projects+ .iter()+ .find(|p| p.space_id == space_id && !p.is_archived())+ .map(|p| p.id.clone())+ })?;+ let thread_id = store.create_thread(&project_id, None);+ persist_locked(&store);+ Some(thread_id)+}++/// As `thread_to_recover_after_window_death`, but never a new thread: a+/// remote Space's thread is only real once its server has it, and one made+/// here alone is not.+pub fn existing_thread_to_recover_after_window_death(space_id: &str) -> Option<WorkspaceThreadId> {+ let mut store = THREAD_STORE.lock();+ store.normalize_after_load();+ other_thread_after_window_death(&store, space_id)+}++/// The thread the Space shows as recorded: the reference it restores, or+/// its active project's active thread. Unlike+/// `ensure_active_thread_for_space`, nothing is made when there is none.+pub fn recorded_active_thread_for_space(space_id: &str) -> Option<WorkspaceThreadId> {+ let store = THREAD_STORE.lock();+ if let Some(thread_id) = store.thread_ref_to_restore(space_id) {+ return Some(thread_id);+ }+ let project_id = store.active_project_id_for_space(space_id)?;+ store+ .projects+ .iter()+ .find(|project| project.space_id == space_id && project.id == project_id)?+ .active_thread_id+ .clone()+}++/// The most recently used thread of the Space other than its active one.+fn other_thread_after_window_death(+ store: &WorkspaceThreadStore,+ space_id: &str,+) -> Option<WorkspaceThreadId> {let active_project_id = store.active_project_id_for_space(space_id);let dead_thread_id = active_project_id.as_ref()@@ -2644,27 +2813,7 @@ pub fn thread_to_recover_after_window_death(space_id: &str) -> Option<WorkspaceT}}}- if let Some((_, thread_id)) = best {- return Some(thread_id);- }-- let project_id = active_project_id- .filter(|project_id| {- store- .projects- .iter()- .any(|p| p.space_id == space_id && &p.id == project_id && !p.is_archived())- })- .or_else(|| {- store- .projects- .iter()- .find(|p| p.space_id == space_id && !p.is_archived())- .map(|p| p.id.clone())- })?;- let thread_id = store.create_thread(&project_id, None);- persist_locked(&store);- Some(thread_id)+ best.map(|(_, thread_id)| thread_id)}pub fn create_project_from_path(space_id: &str, path: &str) -> Result<WorkspaceThreadId> {@@ -5044,6 +5193,20 @@ impl WorkspaceThreadStore {.or_insert(last);moved = true;}+ if let Some(local) = self.server_folder_spaces.remove(from) {+ self.server_folder_spaces+ .entry(to.to_string())+ .or_insert(local);+ moved = true;+ }+ if self.synced_server_domains.remove(from) {+ self.synced_server_domains.insert(to.to_string());+ moved = true;+ }+ if self.invented_server_domains.remove(from) {+ self.invented_server_domains.insert(to.to_string());+ moved = true;+ }moved}}@@ -5153,6 +5316,9 @@ pub fn ingest_remote_tree(domain_name: &str, tree: codec::ThinkTermTree) {);return;}+ // The server answered: from now on its Space here is more than a first+ // connect's guess.+ note_server_tree_arrived(domain_name);// The first tree of a connection is the only place allowed to invent a// Space when the server has none. Online mutations from the previous@@ -5607,8 +5773,8 @@ fn submit_thread_state(store: &WorkspaceThreadStore, thread_id: &str) {/// for a dangling group) — the drag ghost shows it while the group header/// is being reordered.pub fn ref_group_title(host_space_id: &str, group_key: &str) -> Option<String> {- let store = THREAD_STORE.lock();- group_thread_refs_by_origin(store.view_for_thread_refs(host_space_id, &[], None))+ let store = lock_store_following_settings();+ store.view_for_ref_groups(host_space_id, &[], None).into_iter().find(|group| group.key == group_key).map(|group| group.label)@@ -5618,7 +5784,7 @@ pub fn ref_group_title(host_space_id: &str, group_key: &str) -> Option<String> {/// and ref-group keys, exactly as displayed. Feeds drag targeting (the/// logical-order end anchor) and reordering.pub fn ordered_sidebar_folder_keys(space_id: &str) -> Vec<String> {- let store = THREAD_STORE.lock();+ let store = lock_store_following_settings();ordered_folder_keys_locked(&store, space_id)}@@ -5630,7 +5796,7 @@ fn ordered_folder_keys_locked(store: &WorkspaceThreadStore, space_id: &str) -> V.map(|project| project.id.clone()).collect();let group_keys: Vec<String> =- group_thread_refs_by_origin(store.view_for_thread_refs(space_id, &[], None))+ store.view_for_ref_groups(space_id, &[], None).into_iter().map(|group| group.key).collect();@@ -6092,9 +6258,50 @@ impl WorkspaceThreadStore {changed |= self.ensure_unique_thread_names();changed |= self.retire_collection_spaces();changed |= self.groom_thread_refs();+ changed |= self.groom_server_folder_spaces();changed}+ /// Forget a server this device keeps no Space of any more, and where a+ /// server's folders went once that local Space is gone (they show in+ /// the host Space again): neither record can outgrow the Spaces here.+ fn groom_server_folder_spaces(&mut self) -> bool {+ let before = (+ self.server_folder_spaces.len(),+ self.synced_server_domains.len(),+ self.invented_server_domains.len(),+ );+ let spaces = &self.spaces;+ let has_spaces =+ |domain: &str| spaces.iter().any(|space| space.client_domain.as_deref() == Some(domain));+ self.server_folder_spaces.retain(|domain, local| {+ has_spaces(domain)+ && spaces+ .iter()+ .any(|space| space.id == *local && space.client_domain.is_none())+ });+ self.synced_server_domains.retain(|domain| has_spaces(domain));+ self.invented_server_domains.retain(|domain| has_spaces(domain));+ // A server with Spaces here in neither record dates from before+ // they were kept: it was connected, so it counts as heard from.+ // Every Space made for a server since is in one of the two.+ for space in spaces {+ if let Some(domain) = space.client_domain.as_deref() {+ if !self.synced_server_domains.contains(domain)+ && !self.invented_server_domains.contains(domain)+ {+ self.synced_server_domains.insert(domain.to_string());+ }+ }+ }+ before+ != (+ self.server_folder_spaces.len(),+ self.synced_server_domains.len(),+ self.invented_server_domains.len(),+ )+ }+/// The collection-Space prototype is retired: a Space that carried the/// flag becomes an ordinary local Space and keeps its refs. The flag is/// never written back, so this migration is idempotent and old binaries@@ -6183,6 +6390,14 @@ impl WorkspaceThreadStore {}}}+ // A server folder row has no reference to keep it, yet a Space+ // restores it when it was opened last (`thread_ref_to_restore`).+ let server_folder_threads: Vec<WorkspaceThreadId> = self+ .spaces+ .iter()+ .flat_map(|space| self.server_folder_projects(&space.id))+ .flat_map(|project| project.threads.iter().map(|thread| thread.id.clone()))+ .collect();let mut changed = false;for space in &mut self.spaces {if space.thread_refs.is_empty() && space.thread_ref_meta.is_empty() {@@ -6220,7 +6435,7 @@ impl WorkspaceThreadStore {thread_ref_meta.retain(|id, _| thread_refs.iter().any(|r| r == id));changed |= thread_ref_meta.len() != before;if let Some(active) = active_thread_ref {- if !thread_refs.contains(active) {+ if !thread_refs.contains(active) && !server_folder_threads.contains(active) {*active_thread_ref = None;changed = true;}@@ -6377,7 +6592,9 @@ impl WorkspaceThreadStore {let last_opened = space.active_thread_ref.clone()- .filter(|id| space.thread_refs.contains(id))+ .filter(|id| {+ space.thread_refs.contains(id) || self.shows_server_folder_thread(space_id, id)+ }).filter(resolvable);if last_opened.is_some() {return last_opened;@@ -6494,6 +6711,45 @@ impl WorkspaceThreadStore {true}+ fn view_for_ref_groups(+ &self,+ space_id: &str,+ live_workspaces: &[String],+ active_workspace: Option<&str>,+ ) -> Vec<ThreadRefGroupView> {+ let mut groups = group_thread_refs_by_origin(self.view_for_thread_refs(+ space_id,+ live_workspaces,+ active_workspace,+ ));+ // A server's project remains a folder even after its last thread+ // is deleted. Its header is also where a new thread can be made.+ for project in self.server_folder_projects(space_id) {+ if groups.iter().any(|group| group.key == project.id) {+ continue;+ }+ let Some(origin) = self.spaces.iter().find(|space| space.id == project.space_id) else {+ continue;+ };+ let (machine_label, machine_is_local) = origin_machine_for_project(project, &self.spaces);+ groups.push(ThreadRefGroupView {+ key: project.id.clone(),+ label: project.name.clone(),+ machine_label,+ machine_is_local,+ origin_space_name: origin.name.clone(),+ attached: origin+ .client_domain+ .as_deref()+ .is_some_and(remote_tree_domain_is_attached),+ server_folder: true,+ collapsed: false,+ threads: Vec::new(),+ });+ }+ groups+ }+fn view_for_thread_refs(&self,space_id: &str,@@ -6503,7 +6759,8 @@ impl WorkspaceThreadStore {let Some(space) = self.spaces.iter().find(|space| space.id == space_id) else {return Vec::new();};- space+ let server_folders = self.server_folder_projects(space_id);+ let mut views: Vec<ThreadRefView> = space.thread_refs.iter().filter_map(|thread_id| {@@ -6535,6 +6792,7 @@ impl WorkspaceThreadStore {origin_domain_attached: false,workspace_name: String::new(),dangling: true,+ server_folder: false,});};// A ref into an archived project is hidden, not pruned:@@ -6543,44 +6801,190 @@ impl WorkspaceThreadStore {if project.is_archived() {return None;}- let origin = self.spaces.iter().find(|s| s.id == project.space_id)?;let session = project.threads.iter().find(|t| &t.id == thread_id)?;- let workspace_name = session- .materialized_workspace_name- .clone()- .unwrap_or_else(|| workspace_name_for_thread(&project.id, &session.id));- let thread = WorkspaceThreadView {- id: session.id.clone(),- name: session.name.clone(),- is_active: active_workspace == Some(workspace_name.as_str()),- is_materialized: live_workspaces.iter().any(|live| live == &workspace_name),- is_pinned: session.is_pinned,- is_unread: session.is_unread,- work_status: session.work_status(),- };- let (machine_label, machine_is_local) =- origin_machine_for_project(project, &self.spaces);- let origin_domain_attached = origin- .client_domain- .as_deref()- .map(remote_tree_domain_is_attached)- .unwrap_or(true);- Some(ThreadRefView {- thread,- origin_space_id: origin.id.clone(),- origin_space_name: origin.name.clone(),- origin_project_id: project.id.clone(),- origin_project_name: project.name.clone(),- machine_label,- machine_is_local,- origin_domain_attached,- workspace_name,- dangling: false,- })+ let server_folder = server_folders.iter().any(|folder| folder.id == project.id);+ self.resolved_ref_view(+ project,+ session,+ live_workspaces,+ active_workspace,+ server_folder,+ )+ })+ .collect();+ // Then the server folders, each thread in its project's order. One+ // the Space also references stays where its reference put it.+ for project in server_folders {+ for session in &project.threads {+ if space.thread_refs.contains(&session.id) {+ continue;+ }+ views.extend(self.resolved_ref_view(+ project,+ session,+ live_workspaces,+ active_workspace,+ true,+ ));+ }+ }+ views+ }++ /// The row for a thread a Space shows from somewhere else, whether by+ /// reference or in a server folder.+ fn resolved_ref_view(+ &self,+ project: &Project,+ session: &WorkspaceThread,+ live_workspaces: &[String],+ active_workspace: Option<&str>,+ server_folder: bool,+ ) -> Option<ThreadRefView> {+ let origin = self.spaces.iter().find(|s| s.id == project.space_id)?;+ let workspace_name = session+ .materialized_workspace_name+ .clone()+ .unwrap_or_else(|| workspace_name_for_thread(&project.id, &session.id));+ let thread = WorkspaceThreadView {+ id: session.id.clone(),+ name: session.name.clone(),+ is_active: active_workspace == Some(workspace_name.as_str()),+ is_materialized: live_workspaces.iter().any(|live| live == &workspace_name),+ is_pinned: session.is_pinned,+ is_unread: session.is_unread,+ work_status: session.work_status(),+ };+ let (machine_label, machine_is_local) = origin_machine_for_project(project, &self.spaces);+ let origin_domain_attached = origin+ .client_domain+ .as_deref()+ .map(remote_tree_domain_is_attached)+ .unwrap_or(true);+ Some(ThreadRefView {+ thread,+ origin_space_id: origin.id.clone(),+ origin_space_name: origin.name.clone(),+ origin_project_id: project.id.clone(),+ origin_project_name: project.name.clone(),+ machine_label,+ machine_is_local,+ origin_domain_attached,+ workspace_name,+ dangling: false,+ server_folder,+ })+ }++ /// Whether `space_id` holds a reference of its own to `thread_id`.+ fn holds_thread_ref(&self, space_id: &str, thread_id: &str) -> bool {+ self.spaces+ .iter()+ .any(|space| space.id == space_id && space.thread_refs.iter().any(|id| id == thread_id))+ }++ /// The server projects `space_id` shows as folders. None unless servers+ /// are set to show as folders; then the live projects of every server+ /// Space that shows in it (`server_folder_shown_in`), in store order.+ /// Archived ones stay hidden, as they are for references, and so do+ /// those of a server whose first connect has not got through+ /// (`invented_server_domains`).+ fn server_folder_projects(&self, space_id: &str) -> Vec<&Project> {+ if !self.servers_as_folders {+ return Vec::new();+ }+ self.projects+ .iter()+ .filter(|project| {+ !project.is_archived()+ && self.is_client_domain_space(&project.space_id)+ && !self.server_space_is_invented(&project.space_id)+ && self.server_folder_shown_in(&project.space_id) == Some(space_id)}).collect()}+ /// Whether `space_id` is a server's Space a first connect invented, its+ /// server not heard from since.+ fn server_space_is_invented(&self, space_id: &str) -> bool {+ self.spaces+ .iter()+ .find(|space| space.id == space_id)+ .and_then(|space| space.client_domain.as_deref())+ .is_some_and(|domain| self.invented_server_domains.contains(domain))+ }++ /// The local Space `server_space_id`'s folders show in: the one its+ /// server was connected from, while that Space is still here, else the+ /// host Space.+ fn server_folder_shown_in(&self, server_space_id: &str) -> Option<&str> {+ self.spaces+ .iter()+ .find(|space| space.id == server_space_id)+ .and_then(|space| space.client_domain.as_deref())+ .and_then(|domain| self.server_folder_spaces.get(domain))+ .map(String::as_str)+ .filter(|local| {+ self.spaces+ .iter()+ .any(|space| space.id == *local && space.client_domain.is_none())+ })+ .or_else(|| self.server_folder_host_space())+ }++ /// Show the folders of `server_space_id`'s server in `local_space_id`+ /// from now on. Only a server Space can be placed, and only in a local+ /// one.+ fn place_server_folder(&mut self, server_space_id: &str, local_space_id: &str) -> bool {+ let Some(domain) = self+ .spaces+ .iter()+ .find(|space| space.id == server_space_id)+ .and_then(|space| space.client_domain.clone())+ else {+ return false;+ };+ if !self+ .spaces+ .iter()+ .any(|space| space.id == local_space_id && space.client_domain.is_none())+ || self.server_folder_shown_in(server_space_id) == Some(local_space_id)+ {+ return false;+ }+ self.server_folder_spaces+ .insert(domain, local_space_id.to_string());+ true+ }++ /// Whether `domain_name`'s server is one this device has heard from:+ /// it has a Space here and the server has sent its tree at least once.+ fn is_known_server(&self, domain_name: &str) -> bool {+ self.synced_server_domains.contains(domain_name)+ && !self+ .space_ids_for_domains(&[domain_name.to_string()])+ .is_empty()+ }++ /// The local Space the server folders show in when nothing placed them:+ /// the default one, or the first local Space when the default is itself+ /// a server's -- as on a device whose very first window connected+ /// straight to one.+ fn server_folder_host_space(&self) -> Option<&str> {+ self.spaces+ .iter()+ .find(|space| space.is_default && space.client_domain.is_none())+ .or_else(|| self.spaces.iter().find(|space| space.client_domain.is_none()))+ .map(|space| space.id.as_str())+ }++ /// Whether `thread_id` is in one of `space_id`'s server folders.+ fn shows_server_folder_thread(&self, space_id: &str, thread_id: &str) -> bool {+ self.server_folder_projects(space_id)+ .iter()+ .any(|project| project.threads.iter().any(|thread| thread.id == thread_id))+ }+fn rename_space(&mut self, space_id: &str, name: String) -> bool {let name = name.trim();if name.is_empty() {@@ -6918,9 +7322,13 @@ impl WorkspaceThreadStore {fn sync_current_project(&mut self, space_id: &str, active_workspace: &str) -> bool {let mut changed = self.normalize_after_load();- // A window watching a shared pane shows a workspace of its own:- // binding the active thread to it would lose the thread's.- if is_share_view_workspace(active_workspace) {+ // A window watching a shared pane, or showing a server's connection+ // page, shows a workspace of its own: binding the active thread to+ // it would lose the thread's, and in a local Space a project would+ // be made up for it.+ if is_share_view_workspace(active_workspace)+ || is_connection_page_workspace(active_workspace)+ {return changed;}// A refs-only Space (a migrated collection) owns no projects: the@@ -10561,6 +10969,16 @@ pub fn is_share_view_workspace(workspace: &str) -> bool {workspace.starts_with(SHARE_VIEW_WORKSPACE_PREFIX)}+/// The workspaces of the pages a window shows while it connects a server on+/// demand, one per server (see `termwindow::SpaceConnectionPage`). As with+/// a share view, no thread owns one and none may be bound to one: nothing+/// restores, snapshots or counts it as a live thread.+pub const CONNECTION_PAGE_WORKSPACE_PREFIX: &str = "thinkterm-connecting:";++pub fn is_connection_page_workspace(workspace: &str) -> bool {+ workspace.starts_with(CONNECTION_PAGE_WORKSPACE_PREFIX)+}+/// Whether `workspace` is the mux workspace this thread runs in: its/// materialized name once the server has reported one, else the name the/// thread is planned under. Both the writer and the reader of remote font@@ -10928,6 +11346,53 @@ pub fn ensure_mux_domain_space(domain_name: &str) -> MuxDomainSpacePlan {plan}+/// `ensure_mux_domain_space` for a server this device has heard from+/// already (`is_known_server`); `None` for one it meets for the first+/// time, whose Space only the first connect may invent and then seed on+/// the server -- and for one whose first connect never got through, which+/// leaves an invented Space behind and has to be tried the first way again.+pub fn known_mux_domain_space(domain_name: &str) -> Option<MuxDomainSpacePlan> {+ let mut store = THREAD_STORE.lock();+ if !store.is_known_server(domain_name) {+ return None;+ }+ let plan = store.ensure_mux_domain_space(domain_name);+ persist_locked(&store);+ Some(plan)+}++/// Remember that `domain_name`'s server has sent its tree, which makes it+/// known (`known_mux_domain_space`). Only a server this device keeps a+/// Space of is remembered, so the record goes with its Spaces.+fn note_server_tree_arrived(domain_name: &str) {+ let mut store = THREAD_STORE.lock();+ if store.invented_server_domains.remove(domain_name) {+ persist_locked(&store);+ }+ if store.synced_server_domains.contains(domain_name)+ || store+ .space_ids_for_domains(&[domain_name.to_string()])+ .is_empty()+ {+ return;+ }+ store+ .synced_server_domains+ .insert(domain_name.to_string());+ persist_locked(&store);+}++/// Show a server Space's folders in `local_space_id` from now on, as when+/// the server is connected from a window showing that Space.+pub fn place_server_folder(server_space_id: &str, local_space_id: &str) -> bool {+ let mut store = THREAD_STORE.lock();+ let changed = store.place_server_folder(server_space_id, local_space_id);+ if changed {+ persist_locked(&store);+ }+ changed+}+/// 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 {@@ -10972,6 +11437,7 @@ impl WorkspaceThreadStore {let space_id = store.preferred_space_for_domain(domain_name).unwrap_or_else(|| {+ store.invented_server_domains.insert(domain_name.to_string());store.create_space_record_for_domain(label.clone(), Some(domain_name.to_string()))});@@ -11315,6 +11781,33 @@ mod tests {(store, coll_id, t1_id, t2_id)}+ #[test]+ fn window_death_names_only_threads_that_exist() {+ let mut store = test_store();+ let space_id = store.create_space_record("Server".to_string());+ let mut project = default_project_for_space(&space_id);+ let only = WorkspaceThread::new(project.id.clone(), "only".to_string(), None);+ let only_id = only.id.clone();+ project.threads.push(only);+ project.active_thread_id = Some(only_id);+ let project_id = project.id.clone();+ store.projects.push(project);+ store.set_active_project_for_space(&space_id, project_id.clone());++ // The dying thread was the only one: nothing to move to, and+ // nothing made up for a server that has not heard of it.+ assert_eq!(other_thread_after_window_death(&store, &space_id), None);+ assert_eq!(store.projects.last().unwrap().threads.len(), 1);++ let other = WorkspaceThread::new(project_id, "other".to_string(), None);+ let other_id = other.id.clone();+ store.projects.last_mut().unwrap().threads.push(other);+ assert_eq!(+ other_thread_after_window_death(&store, &space_id),+ Some(other_id)+ );+ }+#[test]fn refs_only_space_is_never_claimed_by_startup_windows() {let (mut store, coll_id, t1, _) = store_with_collection();@@ -11501,6 +11994,340 @@ mod tests {assert!(!store.add_thread_ref(&remote, &t1));}+ /// A store whose one server's tree has been taken in, for the server+ /// folder tests: (store, the default Space, the server's threads).+ fn server_folder_store() -> (WorkspaceThreadStore, String, Vec<String>) {+ let mut store = remote_test_store("syd");+ assert!(store.ingest_remote_tree("syd", &sample_tree()));+ let local = store.spaces[0].id.clone();+ let threads = store+ .projects+ .iter()+ .find(|project| project.id == "rp1")+ .unwrap()+ .threads+ .iter()+ .map(|thread| thread.id.clone())+ .collect();+ (store, local, threads)+ }++ fn ref_row_ids(rows: &[ThreadRefView]) -> Vec<String> {+ rows.iter().map(|row| row.thread.id.clone()).collect()+ }++ #[test]+ fn servers_show_as_folders_in_the_default_space_only_once_chosen() {+ let (mut store, local, threads) = server_folder_store();+ assert!(+ store.view_for_thread_refs(&local, &[], None).is_empty(),+ "servers keep their own Spaces unless asked otherwise"+ );++ store.servers_as_folders = true;+ let rows = store.view_for_thread_refs(&local, &[], None);+ assert_eq!(ref_row_ids(&rows), threads);+ assert!(rows.iter().all(|row| row.server_folder && !row.dangling));+ let groups = store.view_for_ref_groups(&local, &[], None);+ assert_eq!(groups.len(), 1);+ assert_eq!(groups[0].key, "rp1");+ assert!(groups[0].server_folder);++ let other = store.create_space_record("Paper".to_string());+ assert!(+ store.view_for_thread_refs(&other, &[], None).is_empty(),+ "every server shows in the default Space, not in each one"+ );+ }++ #[test]+ fn an_empty_server_project_keeps_its_folder_and_new_thread_target() {+ let mut store = remote_test_store("server-a");+ let local = store.spaces[0].id.clone();+ let tree = sample_tree();+ assert!(store.ingest_remote_tree("server-a", &tree));+ store.servers_as_folders = true;++ let mut empty = tree.clone();+ empty.projects[0].threads.clear();+ assert!(store.ingest_remote_tree("server-a", &empty));+ store.normalize_after_load();+ assert!(store.view_for_thread_refs(&local, &[], None).is_empty());+ let groups = store.view_for_ref_groups(&local, &[], None);+ assert_eq!(groups.len(), 1);+ assert_eq!(groups[0].key, "rp1");+ assert_eq!(groups[0].label, empty.projects[0].name);+ assert!(groups[0].server_folder);+ assert!(!groups[0].machine_is_local);+ assert!(groups[0].threads.is_empty());+ assert!(ordered_folder_keys_locked(&store, &local).contains(&groups[0].key));++ assert!(store.ingest_remote_tree("server-a", &tree));+ let groups = store.view_for_ref_groups(&local, &[], None);+ assert_eq!(groups.len(), 1);+ assert_eq!(groups[0].key, "rp1");+ assert_eq!(groups[0].threads.len(), tree.projects[0].threads.len());++ store+ .projects+ .iter_mut()+ .find(|project| project.id == "rp1")+ .unwrap()+ .archived_at = Some(1);+ assert!(store.view_for_ref_groups(&local, &[], None).is_empty());+ }++ #[test]+ fn renaming_a_server_preserves_its_folder_placement_and_known_status() {+ let mut store = remote_test_store("server-a");+ assert!(store.ingest_remote_tree("server-a", &sample_tree()));+ store.synced_server_domains.insert("server-a".to_string());+ store.servers_as_folders = true;+ let local = store.create_space_record("Work".to_string());+ assert!(store.place_server_folder("space-remote", &local));++ assert!(store.move_spaces_to_domain("server-a", "server-b"));+ store.normalize_after_load();+ assert_eq!(+ store.server_folder_shown_in("space-remote"),+ Some(local.as_str())+ );+ assert_eq!(store.server_folder_spaces.get("server-b"), Some(&local));+ assert!(!store.server_folder_spaces.contains_key("server-a"));+ assert!(store.is_known_server("server-b"));+ assert!(!store.is_known_server("server-a"));+ assert!(!store.synced_server_domains.contains("server-a"));+ assert!(!store.move_spaces_to_domain("server-a", "server-b"));++ let saved = serde_json::to_vec(&store).unwrap();+ let mut restored: WorkspaceThreadStore = serde_json::from_slice(&saved).unwrap();+ restored.normalize_after_load();+ assert_eq!(+ restored.server_folder_shown_in("space-remote"),+ Some(local.as_str())+ );+ assert!(restored.is_known_server("server-b"));+ }++ /// A device whose first window connected straight to a server has that+ /// server's Space as its default; the folders go to the first local+ /// Space instead of nowhere.+ #[test]+ fn server_folders_find_a_local_space_when_the_default_is_a_servers() {+ let (mut store, local, threads) = server_folder_store();+ for space in &mut store.spaces {+ space.is_default = space.client_domain.is_some();+ }+ store.servers_as_folders = true;+ assert_eq!(store.server_folder_host_space(), Some(local.as_str()));+ assert_eq!(+ ref_row_ids(&store.view_for_thread_refs(&local, &[], None)),+ threads+ );+ }++ /// Connecting a server from another Space moves its folders there; a+ /// server Space is no place for them.+ #[test]+ fn a_server_folder_moves_to_the_space_it_was_connected_from() {+ let (mut store, local, threads) = server_folder_store();+ store.servers_as_folders = true;+ let paper = store.create_space_record("Paper".to_string());++ assert!(store.place_server_folder("space-remote", &paper));+ assert_eq!(+ ref_row_ids(&store.view_for_thread_refs(&paper, &[], None)),+ threads+ );+ assert!(store.view_for_thread_refs(&local, &[], None).is_empty());+ assert!(+ !store.place_server_folder("space-remote", &paper),+ "placing it where it is changes nothing"+ );++ assert!(!store.place_server_folder("space-remote", "space-remote"));+ assert!(!store.place_server_folder("space-remote", "no-such-space"));+ assert!(!store.place_server_folder(&local, &paper), "a local Space is no server");+ assert_eq!(store.server_folder_shown_in("space-remote"), Some(paper.as_str()));+ }++ #[test]+ fn a_server_folder_goes_back_to_the_host_space_once_its_space_is_gone() {+ let (mut store, local, threads) = server_folder_store();+ store.servers_as_folders = true;+ let paper = store.create_space_record("Paper".to_string());+ assert!(store.place_server_folder("space-remote", &paper));++ store.spaces.retain(|space| space.id != paper);+ store.normalize_after_load();++ assert!(store.server_folder_spaces.is_empty());+ assert_eq!(+ ref_row_ids(&store.view_for_thread_refs(&local, &[], None)),+ threads+ );+ }++ /// A device meeting a server places its folders while the Space its+ /// first connect invented stands in for the server's own; the server's+ /// Space taking over keeps them where they were placed.+ #[test]+ fn a_server_folder_stays_put_when_the_servers_own_space_takes_over() {+ let (mut store, _, _) = server_folder_store();+ store.servers_as_folders = true;+ let paper = store.create_space_record("Paper".to_string());+ assert!(store.place_server_folder("space-remote", &paper));++ let own = store.create_space_record_for_domain("syd".to_string(), Some("syd".into()));+ store+ .projects+ .retain(|project| project.space_id != "space-remote");+ store.spaces.retain(|space| space.id != "space-remote");+ store.normalize_after_load();++ assert_eq!(store.server_folder_shown_in(&own), Some(paper.as_str()));+ }++ /// Only a server that has sent its tree is known: the Space a first+ /// connect invents -- left behind when that connect never got through --+ /// is not enough, and the record goes with the server's last Space.+ #[test]+ fn a_server_is_known_once_its_tree_arrived() {+ let mut store = remote_test_store("syd");+ assert!(!store.is_known_server("syd"));+ store.synced_server_domains.insert("syd".to_string());+ assert!(store.is_known_server("syd"));+ assert!(!store.is_known_server("server-b"));++ store.spaces.retain(|space| space.client_domain.is_none());+ store.normalize_after_load();+ assert!(store.synced_server_domains.is_empty());+ }++ #[test]+ fn a_server_folder_thread_opens_in_place_without_being_a_reference() {+ let (mut store, local, threads) = server_folder_store();+ store.servers_as_folders = true;+ assert!(store.shows_server_folder_thread(&local, &threads[0]));+ assert!(!store.holds_thread_ref(&local, &threads[0]));+ assert_eq!(+ store+ .server_folder_projects(&local)+ .iter()+ .map(|project| project.id.as_str())+ .collect::<Vec<_>>(),+ ["rp1"]+ );++ store.servers_as_folders = false;+ assert!(!store.shows_server_folder_thread(&local, &threads[0]));+ }++ #[test]+ fn a_referenced_server_thread_keeps_its_place_and_shows_once() {+ let (mut store, local, threads) = server_folder_store();+ assert!(store.add_thread_ref(&local, &threads[1]));+ store.servers_as_folders = true;+ let rows = store.view_for_thread_refs(&local, &[], None);+ assert_eq!(+ ref_row_ids(&rows),+ vec![threads[1].clone(), threads[0].clone()]+ );+ assert!(+ rows[0].server_folder,+ "a reference into a server folder's project reads as part of the folder"+ );+ assert!(store.holds_thread_ref(&local, &threads[1]));+ }++ #[test]+ fn the_server_folder_thread_opened_last_is_restored_after_grooming() {+ let (mut store, local, threads) = server_folder_store();+ store.servers_as_folders = true;+ // A reference of its own makes grooming visit the Space at all.+ assert!(store.add_thread_ref(&local, &threads[1]));+ store+ .spaces+ .iter_mut()+ .find(|space| space.id == local)+ .unwrap()+ .active_thread_ref = Some(threads[0].clone());++ store.normalize_after_load();++ let space = store.spaces.iter().find(|space| space.id == local).unwrap();+ assert_eq!(space.active_thread_ref.as_deref(), Some(threads[0].as_str()));+ assert_eq!(+ store.thread_ref_to_restore(&local).as_deref(),+ Some(threads[0].as_str())+ );+ }++ /// Whether servers show as folders is not saved: loading is told, or+ /// its groom lets the thread go before anything sets it.+ #[test]+ fn the_server_folder_thread_opened_last_is_restored_after_a_restart() {+ let (mut store, local, threads) = server_folder_store();+ assert!(store.add_thread_ref(&local, &threads[1]));+ store+ .spaces+ .iter_mut()+ .find(|space| space.id == local)+ .unwrap()+ .active_thread_ref = Some(threads[0].clone());+ let dir = tempdir().unwrap();+ let path = dir.path().join("workspace_threads.json");+ save_workspace_thread_store_to_path(&path, &store).unwrap();++ let loaded = load_store_from_path(&path, true).unwrap();++ let space = loaded.spaces.iter().find(|space| space.id == local).unwrap();+ assert_eq!(space.active_thread_ref.as_deref(), Some(threads[0].as_str()));+ }++ /// A store from before servers' records were kept: the servers it+ /// connected count as heard from, not as met for the first time.+ #[test]+ fn servers_connected_before_their_records_were_kept_count_as_known() {+ let mut store = remote_test_store("syd");+ store.synced_server_domains.clear();+ store.invented_server_domains.clear();+ store.normalize_after_load();+ assert!(store.is_known_server("syd"));++ // One a connect from here invented is not taken for one.+ store.synced_server_domains.clear();+ store.invented_server_domains.insert("syd".to_string());+ store.normalize_after_load();+ assert!(!store.is_known_server("syd"));+ }++ /// A first connect invents the server's Space. Until the server sends+ /// its tree no folder of it shows, so a connect that never gets through+ /// leaves none behind.+ #[test]+ fn an_invented_server_space_shows_no_folder_until_its_tree_arrives() {+ let mut store = test_store();+ store.servers_as_folders = true;+ let local = default_space_id();+ let plan = store.ensure_mux_domain_space("server-b");+ assert!(store.server_folder_projects(&local).is_empty());+ assert!(!store.shows_server_folder_thread(&local, &plan.thread_id));+ // Connecting again finds the Space it invented, still unheard from.+ assert_eq!(store.ensure_mux_domain_space("server-b").space_id, plan.space_id);+ assert!(store.server_folder_projects(&local).is_empty());++ // As `note_server_tree_arrived` has it.+ store.invented_server_domains.remove("server-b");+ assert!(store.shows_server_folder_thread(&local, &plan.thread_id));++ // Gone with the server's last Space.+ store.invented_server_domains.insert("server-b".to_string());+ store.spaces.retain(|space| space.client_domain.is_none());+ store.normalize_after_load();+ assert!(store.invented_server_domains.is_empty());+ }+#[test]fn dangling_remote_ref_is_kept_and_rendered_from_meta() {let mut store = remote_test_store("syd");@@ -11689,6 +12516,7 @@ mod tests {is_remote,domain: is_remote.then(|| "server".to_string()),is_domain_attached: false,+ shown_as_folders: false,}}@@ -11761,6 +12589,30 @@ mod tests {assert_eq!(adjacent_swipe_space_ids(&spaces, "remote"), (None, None));}+ #[test]+ fn adjacent_space_swipe_targets_skip_servers_shown_as_folders() {+ let spaces = vec![+ space_view("local-1", false, false),+ SpaceView {+ shown_as_folders: true,+ ..attached_remote_space_view("attached")+ },+ space_view("local-2", false, false),+ ];++ // Its threads live in a local Space's sidebar, so it is no page of+ // its own, attached or not.+ assert_eq!(+ adjacent_swipe_space_ids(&spaces, "local-1"),+ (None, Some("local-2".into()))+ );+ // A window on it all the same swipes out of it.+ assert_eq!(+ adjacent_swipe_space_ids(&spaces, "attached"),+ (Some("local-1".into()), Some("local-2".into()))+ );+ }+#[test]fn adjacent_space_swipe_targets_include_attached_remote_spaces() {let spaces = vec![@@ -13323,6 +14175,59 @@ mod tests {assert_eq!(store.projects.len(), 1, "no project is made up for it");}+ #[test]+ fn a_connection_page_on_screen_leaves_the_threads_alone() {+ let space = default_space_id();+ let page = format!("{CONNECTION_PAGE_WORKSPACE_PREFIX}server-a");++ // Opened in place in a local Space, from a reference row.+ let mut store = test_store();+ let thread = WorkspaceThread::new(+ "project-default".to_string(),+ "main".to_string(),+ Some("workspace-default".to_string()),+ );+ let thread_id = thread.id.clone();+ let mut project = test_project_in_space(+ &space,+ "project-default",+ "Default",+ PathBuf::from("/tmp/default"),+ vec![thread],+ );+ project.active_thread_id = Some(thread_id);+ store.projects.push(project);+ store.set_active_project_for_space(&space, "project-default".to_string());+ store.sync_current_project(&space, &page);+ assert_eq!(store.projects.len(), 1, "no project is made up for it");+ assert_eq!(store.workspace_space_id(&page), None);++ // In the server's own Space, while its thread waits on the page.+ let mut store = test_store();+ store.spaces[0].client_domain = Some("server-a".to_string());+ let project_id = remote_project_id_for_space(&space, &mux_domain_host_id("server-a"));+ let mut thread = WorkspaceThread::new(project_id.clone(), "main".to_string(), None);+ let workspace = workspace_name_for_thread(&project_id, &thread.id);+ thread.materialized_workspace_name = Some(workspace.clone());+ let thread_id = thread.id.clone();+ let mut project = test_project_in_space(+ &space,+ &project_id,+ "server-a",+ PathBuf::from("wezterm-mux://server-a"),+ vec![thread],+ );+ project.active_thread_id = Some(thread_id);+ store.projects.push(project);+ store.set_active_project_for_space(&space, project_id);+ store.sync_current_project(&space, &page);+ assert_eq!(+ store.projects[0].threads[0].materialized_workspace_name,+ Some(workspace),+ "the thread keeps its own workspace"+ );+ }+#[test]fn current_workspace_owned_by_another_space_is_not_rebound() {let mut store = test_store();