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
gui: show a recovery page when a Project directory is refused
RoversXdfad8f5081ac
diff --git a/wezterm-gui/i18n/en-US.ftl b/wezterm-gui/i18n/en-US.ftlindex 204c4fd9..1c2622b3 100644--- a/wezterm-gui/i18n/en-US.ftl+++ b/wezterm-gui/i18n/en-US.ftl@@ -333,6 +333,14 @@ folder-unreadable-windows = On Windows: check the folder's Properties › Securifolder-unreadable-unix = Check the folder's owner and mode. If ThinkTerm runs in a Flatpak or Snap sandbox, grant it access to this location.folder-missing = Folder not foundfolder-open-error = Unable to open this folder+project-root-no-terminal = No terminal was opened in the Project folder. ThinkTerm will not silently fall back to your home folder.+project-root-reauthorize = Re-authorize This Folder…+project-root-reauthorize-title = Grant access to this folder+project-root-reauthorize-prompt = Grant Access+project-root-recovered = ThinkTerm can open this folder again+project-root-recovered-note = ThinkTerm can read this folder again.+project-root-open-terminal = Open Project Terminal+project-root-other-folder = That is a different folder. The Project still points at the one above, and its access has not changed.right-notes-note-unreadable = This note can't be openedright-choose-existing-vault = Choose Existing Vault…right-create-new-vault = Create New Vault…diff --git a/wezterm-gui/i18n/fr-FR.ftl b/wezterm-gui/i18n/fr-FR.ftlindex 22fc8e8e..e3293a70 100644--- a/wezterm-gui/i18n/fr-FR.ftl+++ b/wezterm-gui/i18n/fr-FR.ftl@@ -333,6 +333,14 @@ folder-unreadable-windows = Sur Windows : vérifiez Propriétés › Sécuritéfolder-unreadable-unix = Vérifiez le propriétaire et les permissions du dossier. Si ThinkTerm s’exécute dans un bac à sable Flatpak ou Snap, accordez-lui l’accès à cet emplacement.folder-missing = Dossier introuvablefolder-open-error = Impossible d’ouvrir ce dossier+project-root-no-terminal = Aucun terminal n’a été ouvert dans le dossier du projet. ThinkTerm ne se repliera pas discrètement sur votre dossier personnel.+project-root-reauthorize = Réautoriser ce dossier…+project-root-reauthorize-title = Accorder l’accès à ce dossier+project-root-reauthorize-prompt = Accorder l’accès+project-root-recovered = ThinkTerm peut de nouveau ouvrir ce dossier+project-root-recovered-note = ThinkTerm peut de nouveau lire ce dossier.+project-root-open-terminal = Ouvrir le terminal du projet+project-root-other-folder = Il s’agit d’un autre dossier. Le projet pointe toujours vers celui ci-dessus et son accès n’a pas changé.right-notes-note-unreadable = Cette note ne peut pas être ouverteright-choose-existing-vault = Choisir un coffre existant…right-create-new-vault = Créer un nouveau coffre…diff --git a/wezterm-gui/i18n/ja-JP.ftl b/wezterm-gui/i18n/ja-JP.ftlindex 24b2ef02..8cde78b6 100644--- a/wezterm-gui/i18n/ja-JP.ftl+++ b/wezterm-gui/i18n/ja-JP.ftl@@ -324,6 +324,14 @@ folder-unreadable-windows = Windows:フォルダのプロパティ › セキュfolder-unreadable-unix = フォルダの所有者とパーミッションを確認してください。ThinkTerm が Flatpak または Snap のサンドボックスで動作している場合は、この場所へのアクセスを許可してください。folder-missing = フォルダが見つかりませんfolder-open-error = このフォルダを開けません+project-root-no-terminal = プロジェクトフォルダではターミナルを開いていません。ThinkTerm はホームフォルダへ暗黙にフォールバックしません。+project-root-reauthorize = このフォルダを再認可…+project-root-reauthorize-title = このフォルダへのアクセスを許可+project-root-reauthorize-prompt = アクセスを許可+project-root-recovered = ThinkTerm はこのフォルダを再び開けます+project-root-recovered-note = ThinkTerm はこのフォルダを再び読み取れます。+project-root-open-terminal = プロジェクトのターミナルを開く+project-root-other-folder = それは別のフォルダです。プロジェクトは上記のフォルダを指したままで、そのアクセス権は変わっていません。right-notes-note-unreadable = このノートは開けませんright-choose-existing-vault = 既存の保管庫を選択…right-create-new-vault = 新しい保管庫を作成…diff --git a/wezterm-gui/i18n/zh-CN.ftl b/wezterm-gui/i18n/zh-CN.ftlindex 2ff4e873..8e3121d1 100644--- a/wezterm-gui/i18n/zh-CN.ftl+++ b/wezterm-gui/i18n/zh-CN.ftl@@ -324,6 +324,14 @@ folder-unreadable-windows = Windows:检查该文件夹的属性 › 安全,以folder-unreadable-unix = 检查该文件夹的属主和权限位。若 ThinkTerm 运行在 Flatpak 或 Snap 沙箱中,需要为它授予该路径的访问权限。folder-missing = 找不到文件夹folder-open-error = 无法打开这个文件夹+project-root-no-terminal = 没有在 Project 文件夹中打开终端。ThinkTerm 不会静默回退到你的家目录。+project-root-reauthorize = 重新授权此文件夹…+project-root-reauthorize-title = 授予该文件夹的访问权限+project-root-reauthorize-prompt = 授予访问+project-root-recovered = ThinkTerm 现在可以打开这个文件夹了+project-root-recovered-note = ThinkTerm 现在可以读取这个文件夹了。+project-root-open-terminal = 打开项目终端+project-root-other-folder = 那是另一个文件夹。Project 仍然指向上面这个,它的访问权限没有变化。right-notes-note-unreadable = 这篇笔记无法打开right-choose-existing-vault = 选择现有库…right-create-new-vault = 新建库…diff --git a/wezterm-gui/src/frontend.rs b/wezterm-gui/src/frontend.rsindex fedd2e37..62dc5795 100644--- a/wezterm-gui/src/frontend.rs+++ b/wezterm-gui/src/frontend.rs@@ -747,16 +747,69 @@ impl GuiFrontEnd {)};- crate::workspace_threads::materialize_thread(+ // Strict first, so a refused Project directory does not quietly+ // become `$HOME`. If it is refused, park the problem for the window+ // that is about to be built and materialize leniently anyway: this+ // call is what *creates* that window, so failing here would open no+ // window at all -- a worse outcome than the wrong directory, and+ // one the user could not even see to fix.+ if let Err(err) = crate::workspace_threads::materialize_thread(plan.workspace_name.clone(),- layout,- initial_cwd,+ layout.clone(),+ initial_cwd.clone(),size,None,- term_config,- default_domain,+ term_config.clone(),+ default_domain.clone(),+ true,)- .await?;+ .await+ {+ let Some(failure) =+ crate::termwindow::ui::folder_problem::ProjectRootUnavailable::from_error_chain(+ &err,+ )+ else {+ return Err(err);+ };+ log::warn!("Space {space_id} starts in the home directory: {failure}");+ // The failed strict attempt can leave a tab-less mux window+ // behind; the lenient retry would then report AlreadyLive and+ // hand back a window with no tabs at all.+ let mux = Mux::get();+ for window_id in mux.iter_windows_in_workspace(&plan.workspace_name) {+ if mux+ .get_window(window_id)+ .is_some_and(|window| window.is_empty())+ {+ mux.kill_window(window_id);+ }+ }+ crate::termwindow::project_root_view::queue_project_root_problem(+ space_id.to_string(),+ plan.thread_id.clone(),+ crate::workspace_threads::thread_display_name(+ &plan.project_id,+ &plan.thread_id,+ ),+ failure,+ );+ crate::workspace_threads::materialize_thread(+ plan.workspace_name.clone(),+ layout,+ initial_cwd,+ size,+ None,+ term_config,+ default_domain,+ false,+ )+ .await?;+ // What just materialized is a shell in `$HOME`, not the Thread+ // the user asked for. Mark it so the next deliberate open adds+ // the Project terminal instead of handing this one back.+ crate::workspace_threads::mark_denied_project_fallback(plan.workspace_name.clone());+ }}mux.iter_windows_in_workspace(&plan.workspace_name)diff --git a/wezterm-gui/src/termwindow/content_view.rs b/wezterm-gui/src/termwindow/content_view.rsindex fd2af30f..cd316841 100644--- a/wezterm-gui/src/termwindow/content_view.rs+++ b/wezterm-gui/src/termwindow/content_view.rs@@ -345,6 +345,23 @@ pub(crate) enum RemoteConnectPhase {Failed { message: String },}+/// Result of re-checking a Project directory that a content view reported as+/// unusable, pushed by the owning `TermWindow` once the probe comes back off+/// the worker thread. Only the project-root view consumes it.+#[derive(Clone, Debug)]+pub(crate) enum ProjectRootProbe {+ /// The directory lists again: the user granted the access, remounted the+ /// volume, or put the folder back.+ Available,+ /// Still unusable, with a freshly classified reason -- which may differ+ /// from the original one.+ Blocked(crate::termwindow::ui::folder_problem::ProjectRootUnavailable),+ /// The user picked some *other* folder in the re-authorization panel;+ /// the Project is never repointed on the strength of that, the view just+ /// says what happened.+ OtherFolderChosen,+}+/// What `TermWindow` should do after a content view handled an input event.pub(crate) enum ContentViewResponse {/// Event not consumed by the view.@@ -415,6 +432,28 @@ pub(crate) trait ContentView {/// Default is a no-op; only the remote-thread view reacts.fn on_remote_connect_phase(&mut self, _phase: RemoteConnectPhase) {}+ /// Gate a re-authorization round trip for the project-root page and+ /// report whether it may start. Default is a no-op refusal; only the+ /// project-root view participates.+ fn begin_project_root_reauthorize(&mut self) -> bool {+ false+ }++ /// Push the outcome of that round trip back into the view that asked.+ fn on_project_root_reauthorize(&mut self, _outcome: ProjectRootProbe) {}++ /// Re-point an existing project-root page at a newer refusal, instead of+ /// opening a second page for the same Thread. Returns false for any other+ /// view type.+ fn replace_project_root_problem(+ &mut self,+ _space_id: String,+ _display_name: String,+ _failure: crate::termwindow::ui::folder_problem::ProjectRootUnavailable,+ ) -> bool {+ false+ }+/// Whether the view currently wants the cursor-blink animation running/// (true only while a text field is focused, to avoid needless repaints).fn wants_cursor_blink(&self) -> bool {diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rsindex faa1602b..51897816 100644--- a/wezterm-gui/src/termwindow/mod.rs+++ b/wezterm-gui/src/termwindow/mod.rs@@ -158,6 +158,7 @@ pub mod onboarding;pub mod palette;pub mod paneselect;mod prevcursor;+pub(crate) mod project_root_view;pub(crate) mod remote_files;pub mod remote_thread_view;pub(crate) mod remote_walk;@@ -248,6 +249,13 @@ pub(crate) struct MoshConnectState {/// Latest local Thread activation started by this window. Detached/// materialization tasks may finish out of order; only the generation that/// still matches this complete identity may change the visible workspace.+pub(crate) struct LocalThreadActivationState {+ pub generation: u64,+ pub thread_id: String,+ pub space_id: String,+ pub workspace_name: String,+}+use crate::spawn::SpawnWhere;use prevcursor::PrevCursorPos;@@ -2086,6 +2094,8 @@ pub struct TermWindow {/// Tracks Mosh bootstraps kicked off by `RemoteThreadView`s.mosh_connects: HashMap<ContentViewId, MoshConnectState>,next_mosh_connect_generation: u64,+ local_thread_activation: Option<LocalThreadActivationState>,+ next_local_thread_activation_generation: u64,space_owner_id: u64,active_space_id: String,/// True for windows the user did not explicitly open (domain-owned@@ -3133,6 +3143,8 @@ impl TermWindow {next_remote_connect_generation: 1,mosh_connects: HashMap::new(),next_mosh_connect_generation: 1,+ local_thread_activation: None,+ next_local_thread_activation_generation: 1,space_owner_id,active_space_id,dies_with_mux_window,@@ -3453,7 +3465,14 @@ impl TermWindow {term_window.frontend_recovery_slot(),)};- front_end().record_known_window(window, adopted_mux_window_id, recovery_slot);+ front_end().record_known_window(window.clone(), adopted_mux_window_id, recovery_slot);++ // A Project directory refused before this window existed has been+ // waiting for somewhere to be shown; this is the first moment there is+ // one.+ window.notify(TermWindowNotif::Apply(Box::new(|tw| {+ tw.show_pending_project_root_problem()+ })));Ok(())}diff --git a/wezterm-gui/src/termwindow/mouseevent.rs b/wezterm-gui/src/termwindow/mouseevent.rsindex 80565b4e..20cd767c 100644--- a/wezterm-gui/src/termwindow/mouseevent.rs+++ b/wezterm-gui/src/termwindow/mouseevent.rs@@ -49,6 +49,40 @@ use wezterm_term::{ClickPosition, LastMouseClick, StableRowIndex};const TAB_WHEEL_SURFACE_LOCK_MS: u64 = 700;const TAB_WHEEL_DIRECTION_LOCK_MS: u64 = 140;+/// Returns an in-flight startup-fallback repair to the pending state if its+/// detached future is cancelled before it can report an outcome.+struct DeniedProjectFallbackRepair {+ workspace: Option<String>,+}++impl DeniedProjectFallbackRepair {+ fn begin(workspace: String) -> Option<Self> {+ crate::workspace_threads::begin_denied_project_fallback_repair(&workspace).then_some(Self {+ workspace: Some(workspace),+ })+ }++ fn complete(mut self) {+ if let Some(workspace) = self.workspace.take() {+ crate::workspace_threads::complete_denied_project_fallback_repair(&workspace);+ }+ }++ fn retry(mut self) {+ if let Some(workspace) = self.workspace.take() {+ crate::workspace_threads::retry_denied_project_fallback_repair(&workspace);+ }+ }+}++impl Drop for DeniedProjectFallbackRepair {+ fn drop(&mut self) {+ if let Some(workspace) = self.workspace.take() {+ crate::workspace_threads::retry_denied_project_fallback_repair(&workspace);+ }+ }+}+fn tr_with_name(id: &'static str, name: &str) -> String {let mut args = FluentArgs::new();args.set("name", name.to_string());@@ -6266,6 +6300,17 @@ impl super::TermWindow {context.invalidate();return;}+ // Any valid selection supersedes an older detached local+ // materialization, including a selection that resolves synchronously+ // or takes a remote path. The old task may still finish, but it no+ // longer owns this window's visible state.+ let activation_generation = self.next_local_thread_activation_generation;+ self.next_local_thread_activation_generation = self+ .next_local_thread_activation_generation+ .saturating_add(1)+ .max(1);+ let activation_space_id = self.active_space_id.clone();+ self.local_thread_activation = None;if via_thread_ref {// Remember the choice so switching back to this Space restores// the reference, like a normal Space restores its active thread.@@ -6316,6 +6361,21 @@ impl super::TermWindow {if let Some(other) =crate::frontend::front_end().gui_window_for_mux_window(target){+ let workspace = plan.workspace_name.clone();+ let project_path = plan.project_path.clone();+ let project_id = plan.project_id.clone();+ let thread_id = plan.thread_id.clone();+ other.window.notify(TermWindowNotif::Apply(Box::new(+ move |term_window| {+ term_window.open_project_terminal_in_live_workspace(+ workspace,+ project_path,+ project_id,+ thread_id,+ term_window.active_space_id.clone(),+ );+ },+ )));other.window.focus();context.invalidate();return;@@ -6340,6 +6400,18 @@ impl super::TermWindow {if !plan.needs_materialize {self.adopt_workspace_in_this_window(&plan.workspace_name);+ // This workspace may be live only because startup fell back to a+ // `$HOME` shell for a refused Project; add the terminal that was+ // actually asked for. Added rather than swapped: the fallback+ // shell may have been used, and killing its mux window would take+ // this GUI window down with it.+ self.open_project_terminal_in_live_workspace(+ plan.workspace_name.clone(),+ plan.project_path.clone(),+ plan.project_id.clone(),+ plan.thread_id.clone(),+ self.active_space_id.clone(),+ );// Symmetric with the materialize branch below: if this switch// orphaned a startup mux window, tidy it up. cleanup_orphaned_mux_window// is a no-op when the window is still shown or has a thread binding.@@ -6511,12 +6583,20 @@ impl super::TermWindow {front_end().set_switching_workspaces(true);mux.set_active_workspace(&workspace_name);- let reconcile_window = self.window.clone();- let adopt_workspace = workspace_name.clone();- let detect_window = self.window.clone();let cleanup_workspaces = workspaces_to_kill_after_adopt;+ let problem_thread_id = plan.thread_id.clone();+ let problem_display_name =+ crate::workspace_threads::thread_display_name(&plan.project_id, &plan.thread_id);+ self.local_thread_activation = Some(super::LocalThreadActivationState {+ generation: activation_generation,+ thread_id: plan.thread_id.clone(),+ space_id: activation_space_id.clone(),+ workspace_name: workspace_name.clone(),+ });+ let completion_window = self.window.clone();+ let completion_workspace = workspace_name.clone();promise::spawn::spawn(async move {- let materialized = match crate::workspace_threads::materialize_thread(+ let result = crate::workspace_threads::materialize_thread(workspace_name,layout,initial_cwd,@@ -6524,42 +6604,219 @@ impl super::TermWindow {None,term_config,default_domain,+ true,)- .await+ .await;+ // Released inside the completion below, after the adopt.+ // Clearing it here reopens the additive-reconcile race: a+ // MuxNotification handler would find the active workspace's mux+ // window bound to no GUI window and spawn a second window.+ let Some(window) = completion_window else {+ front_end().set_switching_workspaces(false);+ return;+ };{- Ok(()) => true,- Err(err) => {- log::error!("failed to materialize ThinkTerm thread: {err:#}");- false+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {+ term_window.finish_local_thread_activation(+ activation_generation,+ problem_thread_id,+ activation_space_id,+ completion_workspace,+ result,+ problem_display_name,+ orphan_candidate_window_id,+ cleanup_workspaces,+ detect_remote_os,+ );+ })));+ }+ })+ .detach();++ context.invalidate();+ }++ /// Add a terminal rooted in the Project to a workspace that is already+ /// live, and make it active.+ ///+ /// Strict about its directory: this exists precisely because the Project+ /// was refused once, so silently landing in `$HOME` again -- the very+ /// thing being repaired -- must fail loudly instead. A refusal reopens the+ /// recovery page with the current classification.+ fn open_project_terminal_in_live_workspace(+ &mut self,+ workspace: String,+ project_path: std::path::PathBuf,+ project_id: String,+ thread_id: String,+ space_id: String,+ ) {+ let Some(cwd) = project_path.to_str().map(str::to_string) else {+ return;+ };+ let mux = Mux::get();+ let Some(mux_window_id) = mux.iter_windows_in_workspace(&workspace).into_iter().next()+ else {+ return;+ };+ let Some(repair) = DeniedProjectFallbackRepair::begin(workspace.clone()) else {+ return;+ };+ let display_name = crate::workspace_threads::thread_display_name(&project_id, &thread_id);+ let size = self.terminal_size;+ let term_config: Arc<dyn wezterm_term::TerminalConfiguration> =+ Arc::new(TermConfig::with_config(self.config.clone()));+ let window = self.window.clone();+ promise::spawn::spawn(async move {+ let mut command = portable_pty::CommandBuilder::new_default_prog();+ command.set_require_cwd(true);+ let result = Mux::get()+ .spawn_tab_or_window(+ Some(mux_window_id),+ config::keyassignment::SpawnTabDomain::DefaultDomain,+ Some(command),+ Some(cwd),+ size,+ None,+ workspace.clone(),+ None,+ )+ .await;+ match result {+ Ok((_tab, pane, _window_id)) => {+ pane.set_config(term_config);+ repair.complete();+ if let Some(window) = window {+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {+ term_window.invalidate_window();+ })));+ }}- };- adopt_workspace_into_window(&reconcile_window, &adopt_workspace);- front_end().set_switching_workspaces(false);- if materialized {- cleanup_orphaned_mux_window(orphan_candidate_window_id);- kill_workspace_windows(&cleanup_workspaces, Some(&adopt_workspace));- }- reconcile_workspace_layout_after_materialize(reconcile_window);-- if materialized {- if let Some((detect_domain, detect_project)) = detect_remote_os {- if let Some(domain) = Mux::get().get_domain_by_name(&detect_domain) {- if let Some(ssh) = domain.as_ref().downcast_ref::<RemoteSshDomain>() {- if let Some(distro) = ssh.detect_os_release().await {- if crate::ssh_hosts::set_host_distro(&detect_project, &distro) {- if let Some(win) = detect_window.as_ref() {- win.invalidate();- }- }+ Err(err) => {+ log::error!("open Project terminal in live workspace: {err:#}");+ let failure = crate::termwindow::ui::folder_problem::ProjectRootUnavailable::from_error_chain(&err);+ repair.retry();+ if let Some(window) = window {+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {+ if let Some(failure) = failure {+ term_window.show_project_root_problem(+ thread_id,+ space_id,+ display_name,+ failure,+ );+ } else {+ term_window.invalidate_window();}- }+ })));}}}}).detach();+ }- context.invalidate();+ #[allow(clippy::too_many_arguments)]+ fn finish_local_thread_activation(+ &mut self,+ generation: u64,+ thread_id: String,+ space_id: String,+ workspace_name: String,+ result: anyhow::Result<crate::workspace_threads::ThreadMaterializationOutcome>,+ display_name: String,+ orphan_candidate_window_id: Option<MuxWindowId>,+ workspaces_to_kill_after_adopt: Vec<String>,+ detect_remote_os: Option<(String, String)>,+ ) {+ let is_current = self.local_thread_activation.as_ref().is_some_and(|state| {+ local_thread_activation_matches(+ state,+ generation,+ &thread_id,+ &space_id,+ &workspace_name,+ &self.active_space_id,+ )+ });+ // Every exit below releases the switching guard and re-baselines the+ // layout; leaving either undone on a failed or overtaken activation+ // leaves a stuck guard and a stale fingerprint behind.+ let release = |term_window: &mut Self| {+ front_end().set_switching_workspaces(false);+ reconcile_workspace_layout_after_materialize(term_window.window.clone());+ term_window.invalidate_window();+ };++ if !is_current {+ // The materialized workspace is intentionally left live in the+ // background. A newer click owns the visible window now -- but the+ // cleanup this activation was carrying still has to happen, or the+ // orphan window and the workspaces it was told to kill leak for+ // the life of the process.+ cleanup_orphaned_mux_window(orphan_candidate_window_id);+ kill_workspace_windows(&workspaces_to_kill_after_adopt, None);+ release(self);+ return;+ }+ let state = self.local_thread_activation.take().unwrap();+ let workspace = state.workspace_name;++ if let Err(err) = result {+ log::error!("failed to materialize ThinkTerm thread: {err:#}");+ // The mux-level backstop refuses *inside* `spawn_tab_or_window`,+ // which leaves a tab-less window behind; that would make the+ // workspace look materialized and stop any retry.+ let mux = Mux::get();+ for window_id in mux.iter_windows_in_workspace(&workspace) {+ if mux+ .get_window(window_id)+ .is_some_and(|window| window.is_empty())+ {+ mux.kill_window(window_id);+ }+ }+ if let Some(failure) =+ crate::termwindow::ui::folder_problem::ProjectRootUnavailable::from_error_chain(+ &err,+ )+ {+ self.show_project_root_problem(thread_id, space_id, display_name, failure);+ }+ release(self);+ return;+ }++ if !self.adopt_workspace_in_this_window(&workspace) {+ log::error!("materialized ThinkTerm workspace {workspace:?} has no window to adopt");+ release(self);+ return;+ }+ cleanup_orphaned_mux_window(orphan_candidate_window_id);+ kill_workspace_windows(&workspaces_to_kill_after_adopt, Some(&workspace));+ front_end().set_switching_workspaces(false);+ self.snapshot_active_workspace_thread_layout();+ self.remember_workspace_layout_structure_fingerprint();+ reconcile_workspace_layout_after_materialize(self.window.clone());+ self.invalidate_window();++ if let Some((detect_domain, detect_project)) = detect_remote_os {+ let detect_window = self.window.clone();+ promise::spawn::spawn(async move {+ if let Some(domain) = Mux::get().get_domain_by_name(&detect_domain) {+ if let Some(ssh) = domain.as_ref().downcast_ref::<RemoteSshDomain>() {+ if let Some(distro) = ssh.detect_os_release().await {+ if crate::ssh_hosts::set_host_distro(&detect_project, &distro) {+ if let Some(window) = detect_window {+ window.invalidate();+ }+ }+ }+ }+ }+ })+ .detach();+ }}fn failed_remote_thread_for_pane(@@ -6774,6 +7031,7 @@ impl super::TermWindow {None,term_config,config::keyassignment::SpawnTabDomain::DomainName(domain_name),+ true,).await{@@ -8259,11 +8517,83 @@ fn reconcile_workspace_layout_after_materialize(window: Option<::window::Window>}}-/// After a target workspace has been materialized in a background task, adopt-/// its mux window into `window` (the window that initiated the switch) in-/// place, without disturbing any other window. Rebinding the frontend mapping-/// immediately closes the race where the additive reconcile might otherwise-/// spawn a duplicate window for the freshly materialized mux window.+fn local_thread_activation_matches(+ state: &super::LocalThreadActivationState,+ generation: u64,+ thread_id: &str,+ space_id: &str,+ workspace_name: &str,+ active_space_id: &str,+) -> bool {+ state.generation == generation+ && state.thread_id == thread_id+ && state.space_id == space_id+ && state.workspace_name == workspace_name+ && state.space_id == active_space_id+}++#[cfg(test)]+mod local_thread_activation_tests {+ use super::local_thread_activation_matches;+ use crate::termwindow::LocalThreadActivationState;++ fn state() -> LocalThreadActivationState {+ LocalThreadActivationState {+ generation: 7,+ thread_id: "thread-a".to_string(),+ space_id: "space-a".to_string(),+ workspace_name: "workspace-a".to_string(),+ }+ }++ #[test]+ fn only_the_exact_current_activation_may_complete() {+ let state = state();+ assert!(local_thread_activation_matches(+ &state,+ 7,+ "thread-a",+ "space-a",+ "workspace-a",+ "space-a"+ ));+ assert!(!local_thread_activation_matches(+ &state,+ 6,+ "thread-a",+ "space-a",+ "workspace-a",+ "space-a"+ ));+ assert!(!local_thread_activation_matches(+ &state,+ 7,+ "thread-b",+ "space-a",+ "workspace-a",+ "space-a"+ ));+ assert!(!local_thread_activation_matches(+ &state,+ 7,+ "thread-a",+ "space-a",+ "workspace-a",+ "space-b"+ ));+ assert!(!local_thread_activation_matches(+ &state,+ 7,+ "thread-a",+ "space-a",+ "workspace-b",+ "space-a"+ ));+ }+}++/// Adopt a materialized workspace into the window that initiated an operation+/// without disturbing any other GUI window already bound to the mux.pub(crate) fn adopt_workspace_into_window(window: &Option<::window::Window>, workspace: &str) {let mux = Mux::get();let Some(target) = mux.iter_windows_in_workspace(workspace).first().copied() else {diff --git a/wezterm-gui/src/termwindow/project_root_view.rs b/wezterm-gui/src/termwindow/project_root_view.rsnew file mode 100644index 00000000..a9bee07f--- /dev/null+++ b/wezterm-gui/src/termwindow/project_root_view.rs@@ -0,0 +1,1022 @@+//! The content-area page shown when a Thread cannot be opened in its Project+//! directory. It lives in the content area (not the sidebar, which may be+//! closed) and shares its [`FolderProblem`] classification with the Files+//! panel so the two never disagree. Structurally a sibling of+//! `remote_thread_view`.++use crate::quad::TripleLayerQuadAllocator;+use crate::termwindow::content_view::{ContentView, ContentViewResponse, ProjectRootProbe};+use crate::termwindow::ui::folder_problem::{FolderProblem, ProjectRootUnavailable};+use crate::termwindow::ui::icons::SvgIcon;+use crate::termwindow::ui::right_sidebar::{wrap_path_for_width, wrap_snippet_text_for_width};+use crate::termwindow::{ContentViewId, TermWindow, TermWindowNotif};+use crate::ui::{+ draw_scrollbar, rect, wheel_delta_pixels, ControlState, DrawContext, InteractionState,+ ScrollState, UiContext, UiPalette, UiTokens, WidgetKind,+};+use std::path::PathBuf;+use std::rc::Rc;+use std::sync::Mutex;+use wezterm_font::LoadedFont;+use window::WindowOps;+use window::{MouseEventKind as WMEK, MousePress, RectF};++const CONTENT_MAX_W: f32 = 860.0;+const PAD: f32 = 48.0;+const CARD_RADIUS: f32 = 18.0;+const BUTTON_RADIUS: f32 = 14.0;+const BUTTON_MIN_H: f32 = 52.0;+const HERO_ICON_SIZE: f32 = 64.0;+const DETAIL_MAX_LINES: usize = 4;+pub(crate) const PROJECT_ROOT_CONTENT_VIEW_KEY_PREFIX: &str = "project-root:";++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum ProjectRootAction {+ Reauthorize,+ OpenThread,+}++/// Deliberately only two states: everything beyond these existed to drive an+/// automatic re-open, and each extra state had to be raced against the others.+enum ViewPhase {+ Blocked(ProjectRootUnavailable),+ /// The directory reads again; the button delegates to the ordinary+ /// Thread-activation path.+ Granted,+}++pub(crate) struct ProjectRootView {+ thread_id: String,+ space_id: String,+ display_name: String,+ root: PathBuf,+ phase: ViewPhase,+ /// A re-authorization round trip is outstanding. A plain flag: the button+ /// is not offered while set, which also keeps the modeless macOS panel+ /// from being stacked on itself.+ reauth_in_flight: bool,+ /// The user picked some other folder in the panel; say so rather than+ /// silently repointing the Project.+ other_folder_note: Option<String>,+ widgets: UiContext<ProjectRootAction>,+ interaction: InteractionState<ProjectRootAction>,+ scroll: ScrollState,+ /// UI scale captured at paint time; mouse handlers get no `DrawContext`.+ last_ui_scale: f32,+}++impl ProjectRootView {+ pub(crate) fn new(+ thread_id: String,+ space_id: String,+ display_name: String,+ failure: ProjectRootUnavailable,+ ) -> Self {+ Self {+ thread_id,+ space_id,+ display_name,+ root: failure.path.clone(),+ phase: ViewPhase::Blocked(failure),+ reauth_in_flight: false,+ other_folder_note: None,+ widgets: UiContext::default(),+ interaction: InteractionState::default(),+ scroll: ScrollState::new(),+ last_ui_scale: 1.0,+ }+ }++ fn problem(&self) -> Option<FolderProblem> {+ match &self.phase {+ ViewPhase::Blocked(failure) => Some(failure.problem),+ ViewPhase::Granted => None,+ }+ }++ fn headline(&self) -> String {+ match &self.phase {+ ViewPhase::Blocked(failure) => failure.problem.title(),+ ViewPhase::Granted => crate::i18n::tr("project-root-recovered"),+ }+ }++ /// The explanatory paragraph under the headline.+ fn body(&self) -> Option<String> {+ match &self.phase {+ ViewPhase::Blocked(failure) => {+ let mut body = crate::i18n::tr("project-root-no-terminal");+ if let Some(hint) = failure.problem.hint() {+ body.push(' ');+ body.push_str(&hint);+ }+ Some(body)+ }+ ViewPhase::Granted => Some(crate::i18n::tr("project-root-recovered-note")),+ }+ }++ /// The raw OS refusal, so a bug report can name the errno.+ fn detail(&self) -> Option<&str> {+ match &self.phase {+ ViewPhase::Blocked(failure) => Some(failure.detail.as_str()),+ ViewPhase::Granted => None,+ }+ }++ /// (label, icon, action, primary). macOS only: there a picker selection+ /// grants access (TCC never re-prompts on its own); on other platforms a+ /// picker grants nothing, so the hint text points at the real remedy.+ fn buttons(&self) -> Vec<(String, SvgIcon, ProjectRootAction, bool)> {+ if self.reauth_in_flight || !cfg!(target_os = "macos") {+ return Vec::new();+ }+ match &self.phase {+ ViewPhase::Blocked(failure) if failure.problem.can_reauthorize() => vec![(+ crate::i18n::tr("project-root-reauthorize"),+ SvgIcon::FolderOpen,+ ProjectRootAction::Reauthorize,+ true,+ )],+ ViewPhase::Blocked(_) => Vec::new(),+ // Delegates to the exact activation a sidebar click triggers;+ // its predecessor's bugs all came from re-implementing that.+ ViewPhase::Granted => vec![(+ crate::i18n::tr("project-root-open-terminal"),+ SvgIcon::SquareTerminal,+ ProjectRootAction::OpenThread,+ true,+ )],+ }+ }++ fn wrap(+ &self,+ ctx: &DrawContext,+ font: &Rc<LoadedFont>,+ text: &str,+ width: f32,+ max_lines: usize,+ ) -> Vec<String> {+ if width <= 0.0 {+ return Vec::new();+ }+ wrap_snippet_text_for_width(text, max_lines, false, |segment| {+ ctx.measure_text_width(font, segment) / width+ })+ }++ #[allow(clippy::too_many_arguments)]+ fn paint_impl(+ &mut self,+ ctx: &DrawContext,+ layers: &mut TripleLayerQuadAllocator<'_>,+ area: RectF,+ palette: UiPalette,+ font: &Rc<LoadedFont>,+ title_font: &Rc<LoadedFont>,+ ) -> anyhow::Result<()> {+ self.widgets.clear();+ self.last_ui_scale = ctx.scale();+ ctx.draw_rect(+ layers,+ 0,+ area.origin.x,+ area.origin.y,+ area.size.width,+ area.size.height,+ palette.window_bg,+ )?;++ let pad = ctx.px(PAD);+ let shell_w = (area.size.width - pad * 2.0)+ .min(ctx.px(CONTENT_MAX_W))+ .max(0.0);+ let x = area.origin.x + ((area.size.width - shell_w) / 2.0).max(pad);+ let width = shell_w;+ let line_h = (ctx.metrics.cell_size.height as f32 + ctx.px(8.0)).max(ctx.px(34.0));++ // Wrap before laying out: the panel heights depend on how many lines+ // the text actually took, and a hint that wrapped to three lines must+ // not run under the buttons.+ let hero_icon_size = ctx.px(HERO_ICON_SIZE);+ let hero_text_x = x + hero_icon_size + ctx.px(22.0);+ let hero_text_w = (width - hero_icon_size - ctx.px(22.0)).max(0.0);+ let card_pad = ctx.px(20.0);+ let card_text_w = (width - card_pad * 2.0).max(0.0);++ let body_lines = self+ .body()+ .map(|body| self.wrap(ctx, font, &body, card_text_w, 6))+ .unwrap_or_default();+ let path_text = self.root.display().to_string();+ // Path-aware: break after separators, not mid-component.+ let path_lines = if card_text_w <= 0.0 {+ Vec::new()+ } else {+ wrap_path_for_width(&path_text, 2, |segment| {+ ctx.measure_text_width(font, segment) / card_text_w+ })+ };+ let detail_lines = self+ .detail()+ .map(|detail| self.wrap(ctx, font, detail, card_text_w, DETAIL_MAX_LINES))+ .unwrap_or_default();+ let note_lines = self+ .other_folder_note+ .clone()+ .map(|note| self.wrap(ctx, font, ¬e, card_text_w, 3))+ .unwrap_or_default();+ let buttons = self.buttons();+ let button_widths: Vec<f32> = buttons+ .iter()+ .map(|(label, ..)| {+ (ctx.measure_text_width(font, label) + ctx.px(92.0)).max(ctx.px(168.0))+ })+ .collect();++ let card_lines = path_lines.len() + body_lines.len() + detail_lines.len();+ let card_h = if card_lines == 0 {+ 0.0+ } else {+ // One blank line between each group that is present.+ let groups = [+ !path_lines.is_empty(),+ !body_lines.is_empty(),+ !detail_lines.is_empty(),+ ]+ .iter()+ .filter(|present| **present)+ .count();+ line_h * card_lines as f32+ + line_h * groups.saturating_sub(1) as f32 * 0.5+ + card_pad * 2.0+ };+ let note_h = if note_lines.is_empty() {+ 0.0+ } else {+ line_h * note_lines.len() as f32 + card_pad * 2.0+ };++ let top_margin = (area.size.height * 0.12).clamp(pad, ctx.px(112.0));+ let hero_h = ctx.px(112.0);+ let card_gap = ctx.px(22.0);+ let button_h = (line_h + ctx.px(22.0)).max(ctx.px(BUTTON_MIN_H));+ let button_gap = ctx.px(16.0);+ // Wrapped to the shell width: three localized labels can outgrow a+ // narrow window, and a button painted outside the content area is a+ // button mouse dispatch will never hit.+ let button_rows = {+ let mut rows = 0usize;+ let mut bx = 0.0f32;+ for w in &button_widths {+ if bx > 0.0 && bx + w > width {+ bx = 0.0;+ }+ if bx == 0.0 {+ rows += 1;+ }+ bx += w + button_gap;+ }+ rows+ };+ let button_block_h = if buttons.is_empty() {+ 0.0+ } else {+ button_rows as f32 * button_h+ + (button_rows as f32 - 1.0).max(0.0) * button_gap+ + card_gap+ };+ let content_h = top_margin+ + hero_h+ + card_h+ + if card_h > 0.0 { card_gap } else { 0.0 }+ + note_h+ + if note_h > 0.0 { card_gap } else { 0.0 }+ + button_block_h+ + pad;+ self.scroll.set_extents(area.size.height, content_h);++ let mut y = area.origin.y + top_margin - self.scroll.offset;++ let hero_icon = self+ .problem()+ .map(FolderProblem::icon)+ .unwrap_or(SvgIcon::FolderOpen);+ ctx.draw_rounded_frame(+ layers,+ 0,+ x,+ y + ctx.px(4.0),+ hero_icon_size,+ hero_icon_size,+ palette.control_bg,+ palette.control_border,+ ctx.px(20.0),+ )?;+ ctx.draw_svg_icon(+ layers,+ hero_icon,+ x + ctx.px(18.0),+ y + ctx.px(22.0),+ ctx.px(28.0),+ palette.secondary_text,+ )?;+ ctx.draw_text(+ layers,+ title_font,+ hero_text_x,+ y,+ &self.headline(),+ palette.text,+ hero_text_w,+ )?;+ ctx.draw_text(+ layers,+ font,+ hero_text_x,+ y + line_h + ctx.px(16.0),+ &self.display_name,+ palette.muted_text,+ hero_text_w,+ )?;+ y += hero_h;++ if card_h > 0.0 {+ ctx.draw_rounded_frame(+ layers,+ 0,+ x,+ y,+ width,+ card_h,+ palette.control_bg,+ palette.control_border,+ ctx.px(CARD_RADIUS),+ )?;+ let mut text_y = y + card_pad;+ // The path leads: the user has to recognise WHICH folder before+ // any of the buttons mean anything.+ for line in &path_lines {+ ctx.draw_text(+ layers,+ font,+ x + card_pad,+ text_y,+ line,+ palette.text,+ card_text_w,+ )?;+ text_y += line_h;+ }+ if !body_lines.is_empty() {+ if !path_lines.is_empty() {+ text_y += line_h * 0.5;+ }+ for line in &body_lines {+ ctx.draw_text(+ layers,+ font,+ x + card_pad,+ text_y,+ line,+ palette.muted_text,+ card_text_w,+ )?;+ text_y += line_h;+ }+ }+ if !detail_lines.is_empty() {+ text_y += line_h * 0.5;+ for line in &detail_lines {+ ctx.draw_text(+ layers,+ font,+ x + card_pad,+ text_y,+ line,+ palette.secondary_text,+ card_text_w,+ )?;+ text_y += line_h;+ }+ }+ y += card_h + card_gap;+ }++ if note_h > 0.0 {+ ctx.draw_rounded_frame(+ layers,+ 0,+ x,+ y,+ width,+ note_h,+ palette.control_bg,+ palette.control_border,+ ctx.px(CARD_RADIUS),+ )?;+ let mut text_y = y + card_pad;+ for line in ¬e_lines {+ ctx.draw_text(+ layers,+ font,+ x + card_pad,+ text_y,+ line,+ palette.muted_text,+ card_text_w,+ )?;+ text_y += line_h;+ }+ y += note_h + card_gap;+ }++ let mut bx = x;+ for ((label, icon, action, primary), w) in buttons.into_iter().zip(button_widths) {+ if bx > x && bx + w > x + width {+ bx = x;+ y += button_h + button_gap;+ }+ self.paint_action_button(+ ctx,+ layers,+ font,+ palette,+ rect(bx, y, w, button_h),+ &label,+ icon,+ action,+ primary,+ )?;+ bx += w + button_gap;+ }++ // Nothing here clips, so scrolled-away content would bleed into the+ // window chrome above.+ if self.scroll.offset > 0.0 && area.origin.y > 0.0 {+ ctx.draw_rect(+ layers,+ 2,+ area.origin.x,+ 0.0,+ area.size.width,+ area.origin.y,+ palette.sidebar_bg,+ )?;+ }+ if self.scroll.has_overflow() {+ draw_scrollbar(+ ctx,+ layers,+ palette,+ UiTokens::for_dpi(ctx.dimensions.dpi),+ area,+ self.scroll,+ )?;+ }++ Ok(())+ }++ #[allow(clippy::too_many_arguments)]+ fn paint_action_button(+ &mut self,+ ctx: &DrawContext,+ layers: &mut TripleLayerQuadAllocator<'_>,+ font: &Rc<LoadedFont>,+ palette: UiPalette,+ area: RectF,+ label: &str,+ icon: SvgIcon,+ action: ProjectRootAction,+ primary: bool,+ ) -> anyhow::Result<()> {+ self.widgets.push(area, WidgetKind::Button, action);+ let state = self.button_state(action, primary);+ let (mut bg, mut border) = state.colors(palette);+ let mut text = palette.text;+ if primary {+ bg = if state == ControlState::Pressed {+ palette.selected_bg.mul_alpha(0.82)+ } else {+ palette.selected_bg+ };+ border = palette.selected_bg;+ text = palette.selected_text;+ }+ ctx.draw_rounded_frame(+ layers,+ 0,+ area.origin.x,+ area.origin.y,+ area.size.width,+ area.size.height,+ bg,+ border,+ ctx.px(BUTTON_RADIUS),+ )?;+ let icon_size = ctx.px(22.0);+ let icon_x = area.origin.x + ctx.px(18.0);+ let icon_y = area.origin.y + (area.size.height - icon_size) / 2.0;+ ctx.draw_svg_icon(layers, icon, icon_x, icon_y, icon_size, text)?;+ let text_x = icon_x + icon_size + ctx.px(12.0);+ ctx.draw_text(+ layers,+ font,+ text_x,+ Self::centered_text_y(ctx, area),+ label,+ text,+ area.size.width - (text_x - area.origin.x) - ctx.px(16.0),+ )?;+ Ok(())+ }++ fn button_state(&self, action: ProjectRootAction, primary: bool) -> ControlState {+ if self.interaction.pressed == Some(action) {+ ControlState::Pressed+ } else if self.interaction.hovered == Some(action) {+ ControlState::Hovered+ } else if primary {+ ControlState::Active+ } else {+ ControlState::Normal+ }+ }++ fn centered_text_y(ctx: &DrawContext, area: RectF) -> f32 {+ let cell_height = ctx.metrics.cell_size.height as f32;+ area.origin.y + ((area.size.height - cell_height) / 2.0).max(0.0)+ }++ fn on_mouse_impl(&mut self, x: f32, y: f32, kind: WMEK) -> ContentViewResponse {+ let hit = self.widgets.hit_test(x, y).map(|target| target.action);+ match kind {+ WMEK::VertWheel(amount) => {+ let old = self.scroll.offset;+ self.scroll+ .scroll_by(wheel_delta_pixels(amount, self.last_ui_scale));+ if (self.scroll.offset - old).abs() > 0.01 {+ ContentViewResponse::Redraw+ } else {+ ContentViewResponse::Ignored+ }+ }+ WMEK::Move => {+ if self.interaction.hovered != hit {+ self.interaction.hovered = hit;+ ContentViewResponse::Redraw+ } else {+ ContentViewResponse::Ignored+ }+ }+ WMEK::Press(MousePress::Left) => {+ self.interaction.pressed = hit;+ ContentViewResponse::Redraw+ }+ WMEK::Release(MousePress::Left) => {+ let pressed = self.interaction.pressed.take();+ if let (Some(hit), Some(pressed)) = (hit, pressed) {+ if hit == pressed {+ return self.apply(hit);+ }+ }+ ContentViewResponse::Redraw+ }+ _ => ContentViewResponse::Ignored,+ }+ }++ fn apply(&mut self, action: ProjectRootAction) -> ContentViewResponse {+ match action {+ ProjectRootAction::Reauthorize => {+ self.other_folder_note = None;+ self.interaction = InteractionState::default();+ reauthorize_response(self.root.clone())+ }+ ProjectRootAction::OpenThread => open_thread_response(self.thread_id.clone()),+ }+ }+}++impl ContentView for ProjectRootView {+ fn title(&self) -> String {+ self.display_name.clone()+ }++ fn show_in_tab_bar(&self) -> bool {+ false+ }++ fn tab_key(&self) -> Option<String> {+ Some(format!(+ "{}{}",+ PROJECT_ROOT_CONTENT_VIEW_KEY_PREFIX, self.thread_id+ ))+ }++ fn space_id(&self) -> Option<&str> {+ Some(&self.space_id)+ }++ /// Gate a re-authorization round trip, and report whether it may start.+ ///+ /// False while one is already out: the macOS open panel is modeless, so+ /// the window stays clickable behind it and a second press would stack a+ /// second panel over the first.+ fn begin_project_root_reauthorize(&mut self) -> bool {+ if self.reauth_in_flight {+ return false;+ }+ self.reauth_in_flight = true;+ self.interaction = InteractionState::default();+ true+ }++ fn on_project_root_reauthorize(&mut self, outcome: ProjectRootProbe) {+ self.reauth_in_flight = false;+ self.interaction = InteractionState::default();+ match outcome {+ ProjectRootProbe::Available => {+ self.other_folder_note = None;+ self.phase = ViewPhase::Granted;+ }+ ProjectRootProbe::Blocked(failure) => {+ self.root = failure.path.clone();+ self.phase = ViewPhase::Blocked(failure);+ }+ // The picker returned a different folder. The Project is not+ // repointed on the strength of that -- repointing a Project and+ // granting access to one are different acts -- so the page says+ // what happened and stays as it was.+ ProjectRootProbe::OtherFolderChosen => {+ self.other_folder_note = Some(crate::i18n::tr("project-root-other-folder"));+ }+ }+ }++ fn replace_project_root_problem(+ &mut self,+ space_id: String,+ display_name: String,+ failure: ProjectRootUnavailable,+ ) -> bool {+ self.space_id = space_id;+ self.display_name = display_name;+ self.root = failure.path.clone();+ self.phase = ViewPhase::Blocked(failure);+ self.other_folder_note = None;+ self.interaction = InteractionState::default();+ true+ }++ fn paint(+ &mut self,+ ctx: &DrawContext,+ layers: &mut TripleLayerQuadAllocator<'_>,+ area: RectF,+ palette: UiPalette,+ font: &Rc<LoadedFont>,+ title_font: &Rc<LoadedFont>,+ _section_font: &Rc<LoadedFont>,+ _cursor_on: bool,+ ) -> anyhow::Result<()> {+ self.paint_impl(ctx, layers, area, palette, font, title_font)+ }++ fn on_mouse(&mut self, x: f32, y: f32, kind: WMEK) -> ContentViewResponse {+ self.on_mouse_impl(x, y, kind)+ }++ fn on_key(+ &mut self,+ key: wezterm_term::KeyCode,+ _mods: wezterm_term::KeyModifiers,+ ) -> ContentViewResponse {+ match key {+ wezterm_term::KeyCode::Escape => ContentViewResponse::Close,+ _ => ContentViewResponse::Ignored,+ }+ }+}++/// A refusal found before any window existed to show it in: app startup+/// materializes a Space's Thread before its `TermWindow` is built. Failing+/// the window would leave the user with no window at all, so startup falls+/// back to a lenient spawn, parks the problem here, and the new window picks+/// it up.+struct PendingProjectRootProblem {+ space_id: String,+ thread_id: String,+ display_name: String,+ failure: ProjectRootUnavailable,+}++static PENDING_PROBLEMS: Mutex<Vec<PendingProjectRootProblem>> = Mutex::new(Vec::new());++pub(crate) fn queue_project_root_problem(+ space_id: String,+ thread_id: String,+ display_name: String,+ failure: ProjectRootUnavailable,+) {+ let Ok(mut pending) = PENDING_PROBLEMS.lock() else {+ return;+ };+ // One per Thread: a Space re-materialized twice must not stack up pages.+ pending.retain(|entry| entry.thread_id != thread_id);+ // Nothing drains entries for a Space no window ever claims, so the queue+ // is bounded rather than left to grow for the life of the process.+ const MAX_PARKED: usize = 8;+ if pending.len() >= MAX_PARKED {+ pending.remove(0);+ }+ pending.push(PendingProjectRootProblem {+ space_id,+ thread_id,+ display_name,+ failure,+ });+}++impl TermWindow {+ /// Show any refusal that was parked while this window was still being+ /// built. Called once, at the end of window construction.+ pub(crate) fn show_pending_project_root_problem(&mut self) {+ let taken = {+ let Ok(mut pending) = PENDING_PROBLEMS.lock() else {+ return;+ };+ // Drain everything parked for this Space; the most recent wins.+ // Removing only one would strand a second Thread's entry forever.+ let mut mine = Vec::new();+ let mut index = 0;+ while index < pending.len() {+ if pending[index].space_id == self.active_space_id {+ mine.push(pending.remove(index));+ } else {+ index += 1;+ }+ }+ let Some(taken) = mine.pop() else {+ return;+ };+ taken+ };+ // Space ids are recycled, so re-check the Thread still lives in this+ // Space before showing a page about it.+ if crate::workspace_threads::thread_space_id(&taken.thread_id).as_deref()+ != Some(taken.space_id.as_str())+ {+ return;+ }+ self.show_project_root_problem(+ taken.thread_id,+ taken.space_id,+ taken.display_name,+ taken.failure,+ );+ }++ /// Show the page for a Thread that could not be opened in its Project+ /// directory. Keyed on the thread: clicking the same broken Thread twice+ /// re-points the existing page instead of stacking a second one.+ pub(crate) fn show_project_root_problem(+ &mut self,+ thread_id: String,+ space_id: String,+ display_name: String,+ failure: ProjectRootUnavailable,+ ) -> ContentViewId {+ let key = format!("{PROJECT_ROOT_CONTENT_VIEW_KEY_PREFIX}{thread_id}");+ if let Some(id) = self.content_view_id_for_key(&key) {+ // A key that somehow belongs to another view type falls through+ // to open a fresh page rather than panicking.+ if self.content_view_mut_by_id(id).is_some_and(|view| {+ view.replace_project_root_problem(+ space_id.clone(),+ display_name.clone(),+ failure.clone(),+ )+ }) {+ self.set_active_content_view_id(Some(id));+ self.invalidate_window();+ return id;+ }+ log::warn!("content view key {key} is not a project-root page; opening a new one");+ }+ let view = ProjectRootView::new(thread_id, space_id, display_name, failure);+ let id = self.open_content_view(Box::new(view));+ self.invalidate_window();+ id+ }++ /// Hand the folder back through the native picker, then confirm with one+ /// directory read. Every filesystem touch happens on a worker: an+ /// unresponsive mount is exactly the case this page exists for.+ pub(crate) fn reauthorize_project_root(&mut self, view_id: ContentViewId, root: PathBuf) {+ let started = self+ .content_view_mut_by_id(view_id)+ .is_some_and(|view| view.begin_project_root_reauthorize());+ if !started {+ return;+ }+ self.invalidate_window();+ let Some(window) = self.window.as_ref().cloned() else {+ self.deliver_project_root_reauthorize(+ view_id,+ ProjectRootProbe::Blocked(ProjectRootUnavailable {+ path: root,+ problem: FolderProblem::Other,+ detail: "window is no longer available".to_string(),+ }),+ );+ return;+ };+ let notify = window.clone();+ window.pick_folder_async_with_options(+ window::FolderPickerOptions {+ title: crate::i18n::tr("project-root-reauthorize-title"),+ prompt: crate::i18n::tr("project-root-reauthorize-prompt"),+ directory: Some(root.clone()),+ },+ Box::new(move |chosen| {+ promise::spawn::spawn(async move {+ let outcome = promise::spawn::spawn_into_new_thread(move || {+ Ok(reauthorize_outcome(root, chosen))+ })+ .await+ .unwrap_or_else(|err| {+ ProjectRootProbe::Blocked(ProjectRootUnavailable {+ path: PathBuf::new(),+ problem: FolderProblem::Other,+ detail: format!("{err:#}"),+ })+ });+ notify.notify(TermWindowNotif::Apply(Box::new(move |term_window| {+ term_window.deliver_project_root_reauthorize(view_id, outcome);+ })));+ })+ .detach();+ }),+ );+ }++ fn deliver_project_root_reauthorize(+ &mut self,+ view_id: ContentViewId,+ outcome: ProjectRootProbe,+ ) {+ // The view may have been closed while the panel was up; there is+ // nothing to update and nothing to report.+ if let Some(view) = self.content_view_mut_by_id(view_id) {+ view.on_project_root_reauthorize(outcome);+ self.invalidate_window();+ }+ }+}++/// Decide what a finished picker means, on a worker thread.+///+/// Cancelling re-states the refusal rather than inventing a verdict: nothing+/// about the folder changed, so the page should look exactly as it did.+fn reauthorize_outcome(root: PathBuf, chosen: Option<PathBuf>) -> ProjectRootProbe {+ let Some(chosen) = chosen else {+ return probe_root(root);+ };+ if !same_path(&chosen, &root) {+ return ProjectRootProbe::OtherFolderChosen;+ }+ probe_root(root)+}++fn probe_root(root: PathBuf) -> ProjectRootProbe {+ match std::fs::read_dir(&root) {+ Ok(_) => ProjectRootProbe::Available,+ Err(err) => ProjectRootProbe::Blocked(ProjectRootUnavailable::from_io(root, &err)),+ }+}++/// Compare two folders for "is this the same place". Canonicalization is+/// best-effort: the folder is one the system may refuse to traverse, and a+/// refusal falls back to comparing the paths as given.+fn same_path(a: &std::path::Path, b: &std::path::Path) -> bool {+ match (std::fs::canonicalize(a), std::fs::canonicalize(b)) {+ (Ok(a), Ok(b)) => a == b,+ _ => a == b,+ }+}++/// Open the Thread by asking for exactly what a sidebar click asks for. The+/// page is dismissed first; a still-refused Project simply re-opens it.+fn open_thread_response(thread_id: String) -> ContentViewResponse {+ ContentViewResponse::Run(Box::new(move |tw: &mut TermWindow| {+ if let Some(view_id) = tw.content_view_response_tab_id {+ tw.close_content_view_by_id(view_id);+ }+ let Some(window) = tw.window.as_ref().cloned() else {+ return;+ };+ tw.activate_workspace_thread(thread_id, &window);+ }))+}++/// Let the user hand the folder back to ThinkTerm through the native picker.+fn reauthorize_response(root: PathBuf) -> ContentViewResponse {+ ContentViewResponse::Run(Box::new(move |tw: &mut TermWindow| {+ let Some(view_id) = tw.content_view_response_tab_id else {+ return;+ };+ tw.reauthorize_project_root(view_id, root);+ }))+}++#[cfg(test)]+mod tests {+ use super::*;++ fn blocked(path: &str) -> ProjectRootUnavailable {+ ProjectRootUnavailable {+ path: PathBuf::from(path),+ problem: FolderProblem::UnreadableRoot,+ detail: "denied".to_string(),+ }+ }++ fn view() -> ProjectRootView {+ ProjectRootView::new(+ "thread-a".to_string(),+ "space-a".to_string(),+ "Project / Thread".to_string(),+ blocked("/project"),+ )+ }++ /// The macOS open panel is modeless, so the window stays clickable while+ /// it is up. A second press must not stack a second panel.+ #[test]+ fn only_one_reauthorization_may_be_in_flight() {+ let mut view = view();+ assert!(view.begin_project_root_reauthorize());+ assert!(!view.begin_project_root_reauthorize());+ assert!(+ view.buttons().is_empty(),+ "the button must not be offered while a panel is up"+ );++ view.on_project_root_reauthorize(ProjectRootProbe::Available);+ assert!(matches!(view.phase, ViewPhase::Granted));+ assert!(view.begin_project_root_reauthorize());+ }++ /// A refusal that arrives after the picker replaces the classification and+ /// the path, so a folder that changed its failure mode is reported as it+ /// now is.+ #[test]+ fn a_fresh_refusal_replaces_the_old_one() {+ let mut view = view();+ assert!(view.begin_project_root_reauthorize());+ view.on_project_root_reauthorize(ProjectRootProbe::Blocked(ProjectRootUnavailable {+ path: PathBuf::from("/project"),+ problem: FolderProblem::MissingRoot,+ detail: "gone".to_string(),+ }));+ assert!(matches!(&view.phase, ViewPhase::Blocked(failure)+ if failure.problem == FolderProblem::MissingRoot));+ }++ /// Picking somewhere else never repoints the Project; it says so and+ /// leaves the refusal on screen.+ #[test]+ fn another_folder_is_reported_not_adopted() {+ let mut view = view();+ assert!(view.begin_project_root_reauthorize());+ view.on_project_root_reauthorize(ProjectRootProbe::OtherFolderChosen);+ assert!(matches!(view.phase, ViewPhase::Blocked(_)));+ assert_eq!(view.root, PathBuf::from("/project"));+ assert!(view.other_folder_note.is_some());+ }++ /// Cancelling the panel is not a verdict: the page must look exactly as+ /// it did, not claim the folder became readable.+ #[test]+ fn cancelling_the_picker_restates_the_refusal() {+ let outcome = super::reauthorize_outcome(PathBuf::from("/nope/missing"), None);+ assert!(matches!(outcome, ProjectRootProbe::Blocked(_)));+ }++ #[test]+ fn deduplicated_problem_uses_the_latest_context() {+ let mut view = view();+ assert!(view.replace_project_root_problem(+ "space-b".to_string(),+ "New name".to_string(),+ blocked("/new-project"),+ ));+ assert_eq!(view.space_id, "space-b");+ assert_eq!(view.display_name, "New name");+ assert_eq!(view.root, PathBuf::from("/new-project"));+ assert!(matches!(view.phase, ViewPhase::Blocked(_)));+ }+}diff --git a/wezterm-gui/src/workspace_threads.rs b/wezterm-gui/src/workspace_threads.rsindex 0946e4ec..a2ee4dca 100644--- a/wezterm-gui/src/workspace_threads.rs+++ b/wezterm-gui/src/workspace_threads.rs@@ -658,6 +658,8 @@ lazy_static::lazy_static! {static ref WINDOW_SPACES: Mutex<HashMap<u64, SpaceId>> = Mutex::new(HashMap::new());static ref MATERIALIZING_LAYOUT_WORKSPACES: Mutex<HashMap<String, usize>> =Mutex::new(HashMap::new());+ static ref DENIED_PROJECT_FALLBACKS: Mutex<DeniedProjectFallbackRepairs> =+ Mutex::new(DeniedProjectFallbackRepairs::default());/// Workspaces whose saved layout this build could not decode. They opened/// as a single terminal, so snapshotting them would write that one pane/// over the arrangement we failed to read — turning a version skew into@@ -2244,6 +2246,72 @@ pub fn thread_connection_state(store.thread_connection_state(thread_id, live_workspaces)}+/// Workspaces that exist only because their Project directory was refused at+/// startup and got the lenient `$HOME` fallback. Recording them lets the next+/// deliberate open add the terminal that was actually asked for. Session-+/// scoped: the fallback does not outlive the process.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum DeniedProjectFallbackState {+ Pending,+ Repairing,+}++#[derive(Debug, Default)]+struct DeniedProjectFallbackRepairs {+ states: HashMap<String, DeniedProjectFallbackState>,+}++impl DeniedProjectFallbackRepairs {+ fn mark(&mut self, workspace: String) {+ self.states+ .entry(workspace)+ .or_insert(DeniedProjectFallbackState::Pending);+ }++ fn begin(&mut self, workspace: &str) -> bool {+ let Some(state) = self.states.get_mut(workspace) else {+ return false;+ };+ if *state != DeniedProjectFallbackState::Pending {+ return false;+ }+ *state = DeniedProjectFallbackState::Repairing;+ true+ }++ fn complete(&mut self, workspace: &str) {+ if self.states.get(workspace) == Some(&DeniedProjectFallbackState::Repairing) {+ self.states.remove(workspace);+ }+ }++ fn retry(&mut self, workspace: &str) {+ if let Some(state @ DeniedProjectFallbackState::Repairing) = self.states.get_mut(workspace)+ {+ *state = DeniedProjectFallbackState::Pending;+ }+ }+}++pub(crate) fn mark_denied_project_fallback(workspace: String) {+ DENIED_PROJECT_FALLBACKS.lock().mark(workspace);+}++/// Claim the one repair attempt allowed for a fallback workspace.+pub(crate) fn begin_denied_project_fallback_repair(workspace: &str) -> bool {+ DENIED_PROJECT_FALLBACKS.lock().begin(workspace)+}++/// Remove the fallback note only after its Project terminal exists.+pub(crate) fn complete_denied_project_fallback_repair(workspace: &str) {+ DENIED_PROJECT_FALLBACKS.lock().complete(workspace);+}++/// Make a failed or cancelled repair eligible for the next deliberate open.+pub(crate) fn retry_denied_project_fallback_repair(workspace: &str) {+ DENIED_PROJECT_FALLBACKS.lock().retry(workspace);+}+pub fn thread_space_id(thread_id: &str) -> Option<SpaceId> {let store = THREAD_STORE.lock();store.thread_space_id(thread_id)@@ -2599,6 +2667,45 @@ impl Drop for MaterializeThreadLayoutGuard {}}+/// Owns every mux window created by one saved-layout restore until the layout+/// is complete. Dropping an unfinished future is an error path too, so this is+/// RAII rather than cleanup at the handful of current `?` sites.+struct MaterializeWindowsRollback {+ window_ids: Vec<MuxWindowId>,+ cleanup: Option<Box<dyn FnMut(MuxWindowId)>>,+}++impl MaterializeWindowsRollback {+ fn new(cleanup: impl FnMut(MuxWindowId) + 'static) -> Self {+ Self {+ window_ids: Vec::new(),+ cleanup: Some(Box::new(cleanup)),+ }+ }++ fn record(&mut self, window_id: MuxWindowId) {+ if !self.window_ids.contains(&window_id) {+ self.window_ids.push(window_id);+ }+ }++ fn commit(mut self) {+ self.window_ids.clear();+ self.cleanup = None;+ }+}++impl Drop for MaterializeWindowsRollback {+ fn drop(&mut self) {+ let Some(cleanup) = self.cleanup.as_mut() else {+ return;+ };+ for window_id in self.window_ids.drain(..) {+ cleanup(window_id);+ }+ }+}+pub fn snapshot_active_space_thread_layout_with_font_scales<F>(space_id: &str,workspace: &str,@@ -2690,7 +2797,15 @@ pub fn snapshot_active_space_thread_layout_with_font_scales<F>(}}-pub async fn materialize_thread(+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum ThreadMaterializationOutcome {+ AlreadyLive,+ RemoteEnsured,+ RestoredLayout,+ SpawnedFresh,+}++pub(crate) async fn materialize_thread(workspace_name: String,layout: Option<WorkspaceThreadLayoutSnapshot>,initial_cwd: Option<String>,@@ -2698,10 +2813,14 @@ pub async fn materialize_thread(src_window_id: Option<MuxWindowId>,term_config: Arc<dyn TerminalConfiguration>,default_domain: SpawnTabDomain,-) -> Result<()> {+ // Whether an unavailable Project directory should fail this call. App+ // startup passes `true` then retries with `false`: it builds the window+ // *from* this materialization, and no window is worse than the wrong cwd.+ strict_project_cwd: bool,+) -> Result<ThreadMaterializationOutcome> {let mux = Mux::get();if !mux.iter_windows_in_workspace(&workspace_name).is_empty() {- return Ok(());+ return Ok(ThreadMaterializationOutcome::AlreadyLive);}// A remote mux owns both its ThinkTerm tree and terminal topology. Use@@ -2736,11 +2855,73 @@ pub async fn materialize_thread(workspace_name);}- return Ok(());+ return Ok(ThreadMaterializationOutcome::RemoteEnsured);}}}+ // Refuse to open a Thread whose Project directory cannot be read, before+ // anything is materialized. Not the same check as `require_cwd` below:+ // that flag guards a fresh spawn's directory, while this probe catches a+ // layout an earlier silent fallback already poisoned with `$HOME` --+ // which spawns fine and would never trip the flag. Inherited/OSC cwds+ // never opt into the strict path.+ //+ // Gated on the local domain as a positive test: a mux/SSH Thread passes+ // its *remote* project path, and stat-ing that here answers a question+ // about the wrong host.+ // `is_plain_local()`, not "is a LocalDomain": WSL, exec and serial domains+ // are all `LocalDomain`s whose cwd is interpreted inside a distribution or+ // container, and stat-ing the HOST path for them answers a question about+ // the wrong filesystem -- a host-side refusal would block a Thread that+ // works fine where it actually runs.+ // Evaluated only when strictness is wanted: on Windows `is_plain_local()`+ // shells out to `wsl.exe -l -v`, and the lenient retry does not need the+ // answer. `is_plain_local()`, not "is a LocalDomain": WSL/exec/serial are+ // `LocalDomain`s whose cwd lives on another filesystem.+ let strict_cwd = if strict_project_cwd && initial_cwd.is_some() {+ let domain = mux.resolve_spawn_tab_domain(None, &default_domain).ok();+ // On a worker with the probe below, not before it. On Windows+ // `is_plain_local()` resolves the WSL domain list, which shells out to+ // an uncached `wsl.exe -l -v`; on the window-thread executor that+ // freezes the UI for the subprocess on every cold materialization.+ promise::spawn::spawn_into_new_thread(move || {+ Ok(domain.is_some_and(|domain| {+ domain+ .downcast_ref::<mux::domain::LocalDomain>()+ .is_some_and(mux::domain::LocalDomain::is_plain_local)+ }))+ })+ .await+ .unwrap_or(false)+ } else {+ false+ };+ if let Some(cwd) = initial_cwd.as_deref().filter(|_| strict_cwd) {+ // On a worker: this runs on the window thread's executor, and a+ // Project on a stalled network mount must not freeze the GUI for the+ // mount timeout -- the same rule the sidebar's directory reads follow.+ let probe_cwd = cwd.to_string();+ let unavailable = promise::spawn::spawn_into_new_thread(move || {+ Ok(match std::fs::read_dir(&probe_cwd) {+ Err(err) => Some(+ crate::termwindow::ui::folder_problem::ProjectRootUnavailable::from_io(+ probe_cwd.clone(),+ &err,+ ),+ ),+ Ok(_) => None,+ })+ })+ .await+ // The worker failing says nothing about the folder; let the spawn+ // proceed and the require_cwd backstop below decide.+ .unwrap_or(None);+ if let Some(failure) = unavailable {+ return Err(anyhow::Error::new(failure));+ }+ }+// Decoding before the branch, rather than inside `materialize_layout`, is// what makes a layout this build cannot read a lost *arrangement* instead// of a Thread that will not open: an undecodable snapshot falls through to@@ -2763,7 +2944,8 @@ pub async fn materialize_thread(size,term_config,)- .await+ .await?;+ Ok(ThreadMaterializationOutcome::RestoredLayout)} else {// A thread whose Space lives on a mux server needs its window tagged// with that domain. `spawn_tab_or_window` makes untagged windows, and@@ -2803,11 +2985,23 @@ pub async fn materialize_thread();}+ // Ask for the Project directory rather than merely preferring it:+ // the probe above only speaks for the moment it ran, and this closes+ // the gap to the actual spawn. `Some(new_default_prog())` behaves+ // identically to the `None` it replaces in `build_command` (verified:+ // the arms only differ on a `default_cwd` fallback this branch, which+ // always sets a cwd, can never reach).+ let command = initial_cwd.as_ref().filter(|_| strict_cwd).map(|_| {+ let mut command = CommandBuilder::new_default_prog();+ command.set_require_cwd(true);+ command+ });+let spawned = mux.spawn_tab_or_window(window_id,default_domain,- None,+ command,initial_cwd,size,None,@@ -2820,7 +3014,7 @@ pub async fn materialize_thread(let (_tab, pane, _window_id) = spawned.context("spawn default thread window")?;pane.set_config(term_config);let _ = src_window_id;- Ok(())+ Ok(ThreadMaterializationOutcome::SpawnedFresh)}}@@ -2894,6 +3088,33 @@ pub fn thread_layout(thread_id: &str) -> Option<WorkspaceThreadLayoutSnapshot> {.and_then(|session| session.layout.clone())}+/// "Project \u{b7} Thread", matching [`thread_display_name_for_workspace`] so a+/// Thread is named the same way wherever it appears -- including collapsing+/// the case where the two names are equal, which would otherwise render as+/// "Foo \u{b7} Foo" on this one surface. Takes the store lock once.+pub fn thread_display_name(project_id: &str, thread_id: &str) -> String {+ let store = THREAD_STORE.lock();+ let project = store+ .projects+ .iter()+ .find(|project| project.id == project_id);+ let thread_name = project+ .and_then(|project| project.threads.iter().find(|thread| thread.id == thread_id))+ .map(|thread| thread.name.clone());+ let project_name = project.map(|project| project.name.clone());+ match (project_name, thread_name) {+ (Some(project), Some(thread)) => {+ if project.is_empty() || project == thread {+ thread+ } else {+ format!("{project} \u{b7} {thread}")+ }+ }+ (Some(name), None) | (None, Some(name)) => name,+ (None, None) => thread_id.to_string(),+ }+}+pub fn thread_name(thread_id: &str) -> Option<String> {let store = THREAD_STORE.lock();store@@ -7518,6 +7739,9 @@ async fn materialize_layout(size: TerminalSize,term_config: Arc<dyn TerminalConfiguration>,) -> Result<()> {+ let rollback_mux = Arc::clone(&mux);+ let mut rollback =+ MaterializeWindowsRollback::new(move |window_id| rollback_mux.kill_window(window_id));let terminal_specs = layout.terminal_specs.iter()@@ -7527,9 +7751,27 @@ async fn materialize_layout(let mut spawned_tabs = 0usize;for node in &tabs {let first_entry = first_pane_entry(node);- let cwd = first_entry- .and_then(|entry| working_dir_for_entry(entry, &terminal_specs))- .or_else(|| initial_cwd.clone());+ let saved_cwd = first_entry.and_then(|entry| working_dir_for_entry(entry, &terminal_specs));+ // Only a tab starting in the Project directory is strict. A pane's+ // own saved cwd is inherited state and keeps the long-standing+ // fallback; the Project directory was asked for by name, and+ // silently substituting `$HOME` for it is the defect this removes.+ let uses_project_root = match (&saved_cwd, &initial_cwd) {+ // No saved cwd: this tab is being started in the Project root.+ (None, Some(_)) => true,+ // A saved cwd that IS the Project root -- the ordinary case for a+ // healthy Thread. It must carry the backstop as well, or the race+ // the backstop exists to close is open on exactly the Threads that+ // were never broken.+ (Some(saved), Some(root)) => saved == root,+ _ => false,+ };+ let cwd = saved_cwd.or_else(|| initial_cwd.clone());+ let command = uses_project_root.then(|| {+ let mut command = CommandBuilder::new_default_prog();+ command.set_require_cwd(true);+ command+ });let domain = first_entry.map(|entry| spawn_domain_for_entry(&mux, entry, &terminal_specs, true)).unwrap_or(SpawnTabDomain::DefaultDomain);@@ -7537,7 +7779,7 @@ async fn materialize_layout(.spawn_tab_or_window(window_id,domain,- None,+ command,cwd,node.root_size().unwrap_or(size),None,@@ -7546,6 +7788,7 @@ async fn materialize_layout().await.context("spawn thread tab")?;+ rollback.record(win_id);pane.set_config(Arc::clone(&term_config));window_id = Some(win_id);restore_node(@@ -7567,6 +7810,7 @@ async fn materialize_layout(}}+ rollback.commit();Ok(())}@@ -8483,6 +8727,59 @@ fn now_ts() -> i64 {mod tests {use super::*;+ #[test]+ fn denied_project_fallback_is_cleared_only_after_a_successful_repair() {+ let mut repairs = DeniedProjectFallbackRepairs::default();+ repairs.mark("workspace-a".to_string());++ assert!(repairs.begin("workspace-a"));+ assert!(+ !repairs.begin("workspace-a"),+ "a repair already in flight must not be duplicated"+ );++ repairs.retry("workspace-a");+ assert!(+ repairs.begin("workspace-a"),+ "a failed repair must remain eligible for retry"+ );++ repairs.complete("workspace-a");+ assert!(+ !repairs.begin("workspace-a"),+ "only a successful repair removes the fallback note"+ );+ }++ #[test]+ fn layout_window_rollback_cleans_every_uncommitted_window() {+ let cleaned = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));+ {+ let observed = std::rc::Rc::clone(&cleaned);+ let mut rollback = MaterializeWindowsRollback::new(move |window_id| {+ observed.borrow_mut().push(window_id);+ });+ rollback.record(17);+ rollback.record(17);+ rollback.record(18);+ }+ assert_eq!(&*cleaned.borrow(), &[17, 18]);++ cleaned.borrow_mut().clear();+ {+ let observed = std::rc::Rc::clone(&cleaned);+ let mut rollback = MaterializeWindowsRollback::new(move |window_id| {+ observed.borrow_mut().push(window_id);+ });+ rollback.record(19);+ rollback.commit();+ }+ assert!(+ cleaned.borrow().is_empty(),+ "a committed layout must keep its mux window"+ );+ }+#[test]fn window_owner_lookup_tracks_claims_without_changing_them() {let assignments = HashMap::from([(11, "space-a".to_string()), (22, "space-b".to_string())]);