diff --git a/crates/ide-agent/src/lib.rs b/crates/ide-agent/src/lib.rs index df7c22954d..2d83171d6b 100644 --- a/crates/ide-agent/src/lib.rs +++ b/crates/ide-agent/src/lib.rs @@ -2291,14 +2291,25 @@ impl AgentManager { } } + /// Stops sending events to UI sinks (project closing). + pub fn detach_sinks(&self) { + self.shared.sinks.write().clear(); + } + /// Stops every agent (project closed). pub fn shutdown(&self) { - for task in self.tasks.read().values() { - task.kill(); - // What arrived after the last save (a subagent's late updates). - task.persist(); + self.detach_sinks(); + let tasks: Vec<_> = self.tasks.read().values().cloned().collect(); + for task in tasks { + let was_live = task.kill().is_some(); + if was_live { + // Persist late subagent updates and cleared live background state. + task.persist(); + } else { + // Flush pending delayed saves without rewriting untouched or archived tasks. + task.save(); + } } - self.shared.sinks.write().clear(); } } diff --git a/crates/ide-agent/src/tests.rs b/crates/ide-agent/src/tests.rs index c0848cde49..86c727970f 100644 --- a/crates/ide-agent/src/tests.rs +++ b/crates/ide-agent/src/tests.rs @@ -1632,6 +1632,47 @@ async fn shutdown_writes_the_saves_still_waiting_and_a_delete_drops_them() { assert_eq!(saved_title(&kept_path).as_deref(), Some("renamed")); } +/// Closing a project with many restored/archived tasks must not rewrite tasks that never changed. +#[tokio::test] +async fn shutdown_skips_rewriting_untouched_restored_tasks() { + let tmp = tempfile::tempdir().unwrap(); + let mgr = manager(tmp.path(), Arc::new(FakeAgent::default())); + let untouched = idle_task(&mgr, "untouched").await; + let archived = idle_task(&mgr, "archived").await; + mgr.archive(&archived.id).unwrap(); + let dirty = idle_task(&mgr, "dirty").await; + mgr.shutdown(); + + let (untouched_path, archived_path, dirty_path) = + (task_file(tmp.path(), &untouched.id), task_file(tmp.path(), &archived.id), task_file(tmp.path(), &dirty.id)); + let restored = manager(tmp.path(), Arc::new(FakeAgent::default())); + let before_untouched = FILE_WRITES.lock().get(&untouched_path).copied().unwrap_or(0); + let before_archived = FILE_WRITES.lock().get(&archived_path).copied().unwrap_or(0); + let before_dirty = FILE_WRITES.lock().get(&dirty_path).copied().unwrap_or(0); + + let dirty_handle = restored.task(&dirty.id).unwrap(); + dirty_handle.state.lock().task.title = "updated".into(); + dirty_handle.persist_soon(); + + restored.shutdown(); + + assert_eq!( + FILE_WRITES.lock().get(&untouched_path).copied().unwrap_or(0), + before_untouched, + "untouched task should not be rewritten on shutdown" + ); + assert_eq!( + FILE_WRITES.lock().get(&archived_path).copied().unwrap_or(0), + before_archived, + "archived task should not be rewritten on shutdown" + ); + assert!( + FILE_WRITES.lock().get(&dirty_path).copied().unwrap_or(0) > before_dirty, + "pending persist_soon task must still be flushed on shutdown" + ); + assert_eq!(saved_title(&dirty_path).as_deref(), Some("updated")); +} + /// Archiving saves the task as it is, including changes nobody asked to be saved. #[tokio::test] async fn archiving_saves_the_task_before_it_returns() { diff --git a/crates/ide-host/src/lib.rs b/crates/ide-host/src/lib.rs index 767db8de49..14dd8b57f3 100644 --- a/crates/ide-host/src/lib.rs +++ b/crates/ide-host/src/lib.rs @@ -144,11 +144,31 @@ pub struct Host { requests: requests::Requests, project_requests: RwLock>>, /// Shutdowns of projects closed with [`Host::close_project_detached`]. - closing: parking_lot::Mutex>>, + closing: parking_lot::Mutex>, /// One open at a time per window (see [`Host::opening`]). open_locks: parking_lot::Mutex>>>, } +struct DetachedClose { + root: Option, + handle: std::thread::JoinHandle<()>, +} + +struct ShutdownWork { + notebooks: Vec>, + bridges: Vec>, + lsp: Option>, + debug: Option<(Arc, String, Option)>, + agents: Vec>, + terminals: Option, + processes: Option, + retired: Option>, +} + +fn roots_overlap(a: &std::path::Path, b: &std::path::Path) -> bool { + a == b || a.starts_with(b) || b.starts_with(a) +} + /// How long exit waits for project shutdown before giving up. const EXIT_SHUTDOWN_WAIT: std::time::Duration = std::time::Duration::from_secs(10); @@ -333,7 +353,7 @@ impl Host { /// [`Self::close_project_detached`] there. pub fn close_project(&self, window: &str) { if let Some(shutdown) = self.begin_close(window) { - self.wait_blocking(shutdown); + self.wait_blocking(shutdown.handle); } } @@ -343,15 +363,15 @@ impl Host { pub fn close_project_detached(&self, window: &str) { if let Some(shutdown) = self.begin_close(window) { let mut closing = self.closing.lock(); - closing.retain(|handle| !handle.is_finished()); + closing.retain(|entry| !entry.handle.is_finished()); closing.push(shutdown); } } - /// Detaches the project from `window` and stops what it started, synchronously, - /// so the window can open another project at once. Returns the thread that - /// finishes shutting down its workers. - fn begin_close(&self, window: &str) -> Option> { + /// Detaches the project from `window` synchronously so the caller (including the UI + /// event-loop thread) never blocks on disk I/O or process shutdown, and returns the + /// background handle that stops its workers, agents, terminals and processes. + fn begin_close(&self, window: &str) -> Option { self.mcp_reports.forget_window(window); self.mcp_requests.forget_window(window); self.mcp_agent_runs.forget_window(window); @@ -398,78 +418,115 @@ impl Host { phpstan.stop(); } project.documents.clear_workspace_edit_history(); - project.agents.shutdown(); + project.agents.detach_sinks(); project.flutter.stop(); project.devtools.stop(); project.widget_preview.stop(); project.notebooks.stop_admission(); - // What the closing window started goes with it — the builds and searches it - // asked for, its runs, its shells and its debug sessions — and its language - // servers shut down. - self.processes.kill_project(&project.root); - self.terminals.kill_key(self.owner_window(window)); - Some(self.spawn_project_shutdown( - vec![project.notebooks.clone()], - project.kotlin_bridge.iter().cloned().collect(), - Some(project.lsp.clone()), + // Detach runs and terminals synchronously so a new project opened in the same window + // never collides with them, then terminate them and shut down agents on the background thread. + let processes = self.processes.detach_project_kills(&project.root); + let terminals = self.terminals.detach_key(self.owner_window(window)); + let root = (!project.light).then(|| project.root.clone()); + let handle = self.spawn_project_shutdown(ShutdownWork { + notebooks: vec![project.notebooks.clone()], + bridges: project.kotlin_bridge.iter().cloned().collect(), + lsp: Some(project.lsp.clone()), // Debug sessions under the root belong to windows: a project served without one starts none. - Some((self.debugger.clone(), window.to_owned(), (!background).then(|| project.root.clone()))), - Some(project), - )) + debug: Some((self.debugger.clone(), window.to_owned(), (!background).then(|| project.root.clone()))), + agents: vec![project.agents.clone()], + terminals: Some(terminals), + processes: Some(processes), + retired: Some(project), + }); + Some(DetachedClose { root, handle }) } - /// Project/window destruction must finish owned kernel cleanup, not enqueue + /// Project/window destruction must finish owned kernel and agent cleanup, not enqueue /// work which can be lost as the desktop runtime exits: the returned thread is /// joined by the closer or, for a detached close, before exit. - fn spawn_project_shutdown( - &self, - notebooks: Vec>, - bridges: Vec>, - lsp: Option>, - debug: Option<(Arc, String, Option)>, - retired: Option>, - ) -> std::thread::JoinHandle<()> { - for bridge in &bridges { + fn spawn_project_shutdown(&self, work: ShutdownWork) -> std::thread::JoinHandle<()> { + for bridge in &work.bridges { bridge.stop(); } - for service in ¬ebooks { + for service in &work.notebooks { service.stop_admission(); } let runtime = self.runtime.clone(); std::thread::spawn(move || { + if let Some(processes) = work.processes { + processes.kill(); + } + if let Some(terminals) = work.terminals { + terminals.terminate(); + } + let agents = (!work.agents.is_empty()).then(|| { + let agents = work.agents; + std::thread::spawn(move || { + for manager in agents { + manager.shutdown(); + } + }) + }); // Dropping the project stops its file watcher and index worker, which first finish the // batch they are applying (many file events while a build writes its output), so it // isn't done on the closing caller's thread (the UI thread for a window close). - let retired = retired.map(|project| std::thread::spawn(move || drop(project))); + let retired = work.retired.map(|project| std::thread::spawn(move || drop(project))); runtime.block_on(async move { - for bridge in bridges { + for bridge in work.bridges { bridge.shutdown().await; } - for service in notebooks { + for service in work.notebooks { service.shutdown().await; } - if let Some(lsp) = lsp { + if let Some(lsp) = work.lsp { lsp.shutdown_all().await; } - if let Some((debug, key, root)) = debug { + if let Some((debug, key, root)) = work.debug { debug.stop_key(&key).await; if let Some(root) = root { debug.stop_under(&root).await; } } }); + if let Some(agents) = agents { + let _ = agents.join(); + } if let Some(retired) = retired { let _ = retired.join(); } }) } - /// Waits for detached closes, so a project opened next never races the - /// language servers of one still shutting down (e.g. over a shared workspace). + /// Waits for every detached close to finish. + #[cfg(test)] pub(crate) fn wait_detached_closes(&self) { let pending: Vec<_> = self.closing.lock().drain(..).collect(); for shutdown in pending { - self.wait_blocking(shutdown); + self.wait_blocking(shutdown.handle); + } + } + + /// Waits only for detached closes whose root overlaps `root`, so opening an unrelated project + /// never blocks on another project's background shutdown. + pub(crate) fn wait_detached_closes_for(&self, root: &std::path::Path) { + let matching = { + let mut closing = self.closing.lock(); + closing.retain(|entry| !entry.handle.is_finished()); + let mut wait = Vec::new(); + let mut keep = Vec::new(); + for entry in closing.drain(..) { + if entry.root.as_deref().is_some_and(|other| roots_overlap(other, root)) { + wait.push(entry.handle); + } else { + keep.push(entry); + } + } + *closing = keep; + wait + }; + for handle in matching { + self.wait_blocking(handle); } } @@ -495,18 +552,23 @@ impl Host { /// Called before the desktop runtime exits, including update/restart exits, on /// the event-loop thread: waits for detached closes and the open projects' - /// kernels, but no longer than [`EXIT_SHUTDOWN_WAIT`], so a runtime worker + /// kernels and agents, but no longer than [`EXIT_SHUTDOWN_WAIT`], so a runtime worker /// stuck on the event loop cannot keep the process from exiting. pub fn shutdown_notebooks_on_exit(&self) { let projects = self.projects(); - let mut pending: Vec<_> = self.closing.lock().drain(..).collect(); - pending.push(self.spawn_project_shutdown( - projects.iter().map(|project| project.notebooks.clone()).collect(), - projects.iter().filter_map(|project| project.kotlin_bridge.clone()).collect(), - None, - None, - None, - )); + let mut pending: Vec<_> = self.closing.lock().drain(..).map(|entry| entry.handle).collect(); + if !projects.is_empty() { + pending.push(self.spawn_project_shutdown(ShutdownWork { + notebooks: projects.iter().map(|project| project.notebooks.clone()).collect(), + bridges: projects.iter().filter_map(|project| project.kotlin_bridge.clone()).collect(), + lsp: None, + debug: None, + agents: projects.iter().map(|project| project.agents.clone()).collect(), + terminals: None, + processes: None, + retired: None, + })); + } let deadline = std::time::Instant::now() + EXIT_SHUTDOWN_WAIT; while pending.iter().any(|handle| !handle.is_finished()) { if std::time::Instant::now() >= deadline { diff --git a/crates/ide-host/src/project.rs b/crates/ide-host/src/project.rs index 0dd93e4e5e..36769e1923 100644 --- a/crates/ide-host/src/project.rs +++ b/crates/ide-host/src/project.rs @@ -125,8 +125,8 @@ impl Host { // A window takes the root over from the MCP server's background project, whose // shutdown the wait below sits out; none opens until this open is over. let _claim = (!crate::mcp::BackgroundProjects::is_key(window)).then(|| self.mcp_background.claim(self, &root)); - self.close_project(window); - self.wait_detached_closes(); + self.close_project_detached(window); + self.wait_detached_closes_for(&root); let sink: SharedSink = (self.sink_for)(window); // Before anything the project starts: its children get the project's environment. let trusted = Arc::new(AtomicBool::new(self.trust.window_trusted(&root)?)); @@ -867,8 +867,10 @@ impl Host { } return Ok(current); } - self.close_project(window); - self.wait_detached_closes(); + self.close_project_detached(window); + if let Some(dir) = watch_dir.as_deref() { + self.wait_detached_closes_for(dir); + } let sink: SharedSink = (self.sink_for)(window); let settings = Arc::new(SettingsStore::load(&self.config_dir, None)); let effective = settings.effective(); diff --git a/crates/ide-run/src/lib.rs b/crates/ide-run/src/lib.rs index fb317dcb42..55bb21ba8f 100644 --- a/crates/ide-run/src/lib.rs +++ b/crates/ide-run/src/lib.rs @@ -21,7 +21,7 @@ mod utf8; pub mod wrap; pub use detect::cmake::{build_configs as cmake_build_configs, prepare as prepare_cmake}; -pub use process::{ProcessManager, StartOptions}; +pub use process::{DetachedProcessKills, ProcessManager, StartOptions}; use ide_core::{IdeResult, RunId}; use serde::{Deserialize, Serialize}; diff --git a/crates/ide-run/src/process.rs b/crates/ide-run/src/process.rs index 852a464e27..6fcc7109aa 100644 --- a/crates/ide-run/src/process.rs +++ b/crates/ide-run/src/process.rs @@ -888,15 +888,25 @@ impl ProcessManager { } } - /// Kills every running process tree at once (shutting down). - pub fn kill_project(&self, root: &Path) { + /// Collects every running process tree for `root` and marks it stopping so the actual + /// termination can run on a background thread without blocking the UI thread or racing + /// processes started later. + pub fn detach_project_kills(&self, root: &Path) -> DetachedProcessKills { + let mut targets = Vec::new(); for entry in self.runs.lock().values().filter(|e| e.project_root == root) { if !entry.exited.load(Ordering::Acquire) && let Some(pid) = *entry.pid.lock() { - kill_tree(entry, pid, true); + entry.stopping.store(true, Ordering::Release); + targets.push((entry.clone(), pid)); } } + DetachedProcessKills(targets) + } + + /// Kills every running process tree at once (shutting down). + pub fn kill_project(&self, root: &Path) { + self.detach_project_kills(root).kill(); } pub fn kill_all(&self) { @@ -939,6 +949,19 @@ impl ProcessManager { } } +/// Running process trees snapshotted from [`ProcessManager`] to be killed off the caller's thread. +pub struct DetachedProcessKills(Vec<(Arc, u32)>); + +impl DetachedProcessKills { + pub fn kill(self) { + for (entry, pid) in self.0 { + if !entry.exited.load(Ordering::Acquire) { + kill_tree(&entry, pid, true); + } + } + } +} + impl Drop for ProcessManager { fn drop(&mut self) { self.kill_all(); diff --git a/crates/ide-terminal/src/lib.rs b/crates/ide-terminal/src/lib.rs index dcb443b371..ca065242fc 100644 --- a/crates/ide-terminal/src/lib.rs +++ b/crates/ide-terminal/src/lib.rs @@ -510,13 +510,17 @@ impl TerminalManager { } } + /// Detaches every terminal opened by `key` so it can be terminated on a background thread + /// without blocking the caller or racing a new project opened in the same window. + pub fn detach_key(&self, key: &str) -> DetachedTerminals { + let mut sessions = self.sessions.lock(); + let ids: Vec = sessions.iter().filter(|(_, s)| s.key == key).map(|(id, _)| *id).collect(); + DetachedTerminals(ids.into_iter().filter_map(|id| sessions.remove(&id)).collect()) + } + /// Closes the terminals `key` opened: the project of that window is closing. pub fn kill_key(&self, key: &str) { - let ids: Vec = - self.sessions.lock().iter().filter(|(_, s)| s.key == key).map(|(id, _)| *id).collect(); - for id in ids { - let _ = self.kill(id); - } + self.detach_key(key).terminate(); } pub fn kill(&self, id: TerminalId) -> IdeResult<()> { @@ -733,6 +737,17 @@ mod win { } } +/// Terminal sessions detached from [`TerminalManager`] to be terminated off the caller's thread. +pub struct DetachedTerminals(Vec>); + +impl DetachedTerminals { + pub fn terminate(self) { + for session in self.0 { + terminate(&session); + } + } +} + /// Hangs up the shell (and its process group), escalating to SIGKILL if it lingers. fn terminate(session: &Session) { let (writer, killer) = match &session.io { diff --git a/src-tauri/src/commands/window.rs b/src-tauri/src/commands/window.rs index 0cc04d4997..f7cb9272b4 100644 --- a/src-tauri/src/commands/window.rs +++ b/src-tauri/src/commands/window.rs @@ -334,6 +334,10 @@ pub struct CloseContext { pub quitting: bool, /// Number of open project windows (settings windows excluded), including the caller. pub windows: u32, + /// Whether this window currently has auxiliary document windows that must settle first. + pub has_document_windows: bool, + /// Whether this close runs alongside other windows or on a background tab (prompts serialize and raise). + pub batch: bool, } #[desktop_command(trust = always)] @@ -350,10 +354,40 @@ pub fn window_close_context(app: AppHandle, window: Window, windows: State<'_, W Some(keeper) if pending.len() > 1 && keeper == window.label() => all.len() - pending.len() + 1, _ => all.len(), }; - CloseContext { quitting: windows.quitting(), windows: count as u32 } + let quitting = windows.quitting(); + let has_document_windows = !windows::document_windows(&app, window.label()).is_empty(); + let hidden_tab = windows.groups.lock().group(window.label()).is_some_and(|g| g.selected != window.label()); + let batch = quitting || pending.len() > 1 || windows.in_tab_close_batch(window.label()) || hidden_tab; + CloseContext { quitting, windows: count as u32, has_document_windows, batch } } -/// Quits: closes every window, each of which runs its own unsaved-changes check. +/// Acquires the interactive prompt turn for a batch close and brings this window forward. +/// Returns `false` if the batch was cancelled while waiting. +#[desktop_command(trust = always)] +#[tauri::command] +#[specta::specta] +pub async fn window_begin_prompt(app: AppHandle, window: WebviewWindow) -> bool { + crate::window_groups::begin_prompt(&app, &window).await +} + +/// Releases the interactive prompt turn held by this window. +#[desktop_command(trust = always)] +#[tauri::command] +#[specta::specta] +pub fn window_end_prompt(app: AppHandle, window: Window) { + crate::window_groups::end_prompt(&app, window.label()); +} + +/// Signals that this window passed its close checks and waits for peers closing in the same +/// batch/tab group so they hide together in one frame. Returns `false` if the batch was cancelled. +#[desktop_command(trust = always)] +#[tauri::command] +#[specta::specta] +pub async fn window_ready_to_close(app: AppHandle, window: WebviewWindow) -> bool { + crate::window_groups::ready_to_close(&app, &window).await +} + +/// Quits: closes every window in parallel, each of which runs its own unsaved-changes check. #[desktop_command(trust = always)] #[tauri::command] #[specta::specta] @@ -362,15 +396,17 @@ pub fn app_quit(app: AppHandle, windows: State<'_, WindowsState>) { return; } windows.set_quitting(true); - windows::continue_quit(&app, None); + windows::start_quit(&app); } /// A window vetoed the quit (user cancelled its unsaved-changes prompt). #[desktop_command(trust = always)] #[tauri::command] #[specta::specta] -pub fn app_cancel_quit(app: AppHandle, windows: State<'_, WindowsState>) { +pub fn app_cancel_quit(app: AppHandle, window: Window, windows: State<'_, WindowsState>) { windows.set_quitting(false); + windows.abort_all_closing(Some(window.label())); + windows.close_settled(window.label()); tauri::async_runtime::spawn(async move { let _ = crate::window_groups::persist(&app).await; }); @@ -926,9 +962,11 @@ ide_command::desktop_domain!( menu_model, menu_refresh, menu_set_disabled, + window_begin_prompt, window_close_context, window_complete_launch, window_cycle, + window_end_prompt, window_flash_taskbar, window_is_fullscreen, window_new, @@ -942,6 +980,7 @@ ide_command::desktop_domain!( window_open_projects, window_open_remote, window_open_settings, + window_ready_to_close, window_set_smooth_scrolling, window_set_titlebar_height, window_take_launch, diff --git a/src-tauri/src/commands/window_group.rs b/src-tauri/src/commands/window_group.rs index 4ee9793760..feea3a4002 100644 --- a/src-tauri/src/commands/window_group.rs +++ b/src-tauri/src/commands/window_group.rs @@ -49,7 +49,6 @@ pub async fn window_group_detach(window: WebviewWindow, label: String) -> IdeRes #[tauri::command] #[specta::specta] pub fn window_group_close(window: WebviewWindow, label: String) -> IdeResult<()> { - groups::select(window.app_handle(), window.label(), &label)?; window .app_handle() .get_webview_window(&label) diff --git a/src-tauri/src/macos.rs b/src-tauri/src/macos.rs index 4053be31ff..9eb560dae8 100644 --- a/src-tauri/src/macos.rs +++ b/src-tauri/src/macos.rs @@ -126,6 +126,26 @@ pub fn move_tab_to_new_window(window: &WebviewWindow) -> tauri::Result<()> { }) } +/// Hides `windows` together in a single main-thread turn so a closing window or tab group +/// disappears at once instead of flipping through remaining tabs while webviews tear down. +/// Native fullscreen windows are left for AppKit's own Space close transition. +pub fn hide_windows(windows: Vec) { + if windows.is_empty() { + return; + } + let first = windows[0].clone(); + let _ = on_main(&first, move || { + for window in &windows { + if window.is_fullscreen().unwrap_or(false) { + continue; + } + if let Some(native) = native(window) { + native.orderOut(None); + } + } + }); +} + fn has_tab_bar(view: &objc2_app_kit::NSView) -> bool { let class = view.class().name().to_string_lossy(); class.contains("TabBar") || view.subviews().iter().any(|v| has_tab_bar(&v)) diff --git a/src-tauri/src/window_groups.rs b/src-tauri/src/window_groups.rs index 3ed040bd28..9e8474e7b0 100644 --- a/src-tauri/src/window_groups.rs +++ b/src-tauri/src/window_groups.rs @@ -6,7 +6,7 @@ use crate::{ use ide_core::{IdeError, IdeEvent, IdeResult}; use serde::{Deserialize, Serialize}; use specta::Type; -use std::collections::VecDeque; +use std::collections::HashSet; use std::path::PathBuf; use std::sync::atomic::Ordering; use tauri::{AppHandle, Manager, WebviewWindow}; @@ -169,35 +169,59 @@ pub fn detach(app: &AppHandle, caller: &str) -> IdeResult<()> { pub fn destroyed(app: &AppHandle, caller: &str) { let Some(state) = app.try_state::() else { return }; let next = state.groups.lock().detach(caller); + let batch_done_keep = { + let mut batch = state.tab_closes.lock(); + if let Some(b) = batch.as_mut() + && b.pending.remove(caller) + && b.pending.is_empty() + { + Some(batch.take().unwrap().keep) + } else { + None + } + }; + let next_closing = next.as_deref().is_some_and(|label| state.is_closing(label)); + let more_closing = state.has_other_pending_closes(caller); if !state.quitting() { - if let Some(window) = next.and_then(|label| app.get_webview_window(&label)) { + if let Some(keep) = batch_done_keep { + if let Some(window) = app.get_webview_window(&keep) + && !window.is_focused().unwrap_or(false) + { + windows::focus(&window); + } + } else if !next_closing && let Some(window) = next.as_deref().and_then(|label| app.get_webview_window(label)) { windows::focus(&window); } - let app = app.clone(); - tauri::async_runtime::spawn(async move { - let _ = persist(&app).await; - }); - } - changed(app); - let advance = state.tab_closes.lock().as_mut().is_some_and(|batch| { - let closing = batch.pending.front().is_some_and(|l| l == caller); - if closing { - batch.pending.pop_front(); + if !more_closing { + let app = app.clone(); + tauri::async_runtime::spawn(async move { + let _ = persist(&app).await; + }); } - closing - }); - if advance { - close_next(app); + } + if !next_closing || !more_closing { + changed(app); } } -/// Tabs left to close; the first one is closing now. +/// Tabs closing together in a batch (Close Other / Left / Right Tabs), keeping `keep`. pub struct TabCloses { - keep: String, - pending: VecDeque, + pub(crate) keep: String, + pub(crate) pending: HashSet, } -/// Closes `labels` one at a time so each project's unsaved-changes prompt is shown in turn, then selects `keep`. +impl TabCloses { + pub(crate) fn contains(&self, label: &str) -> bool { + self.pending.contains(label) + } + + pub(crate) fn has_other(&self, exclude: &str) -> bool { + self.pending.iter().any(|l| l != exclude) + } +} + +/// Closes `labels` in parallel without flipping tabs; any tab that needs a confirmation prompt +/// acquires the prompt turn and raises itself, and `keep` stays selected when the batch finishes. pub fn close_tabs(app: &AppHandle, caller: &str, keep: &str, labels: Vec) -> IdeResult<()> { let state = app.state::(); let members = state @@ -209,55 +233,235 @@ pub fn close_tabs(app: &AppHandle, caller: &str, keep: &str, labels: Vec if !members.iter().any(|m| m == keep) { return Err(IdeError::invalid("The window is not in this group")); } - let pending = members.into_iter().filter(|m| m != keep && labels.contains(m)).collect(); + let targets: Vec = members.into_iter().filter(|m| m != keep && labels.contains(m)).collect(); + if targets.is_empty() { + return Ok(()); + } + let pending: HashSet = targets.iter().cloned().collect(); *state.tab_closes.lock() = Some(TabCloses { keep: keep.to_owned(), pending }); - close_next(app); + // Pre-register every target before invoking `close()` so early responders see the full cohort. + for label in &targets { + state.close_requested(label); + } + let mut any_sent = false; + for label in targets { + if let Some(window) = app.get_webview_window(&label) + && window.close().is_ok() + { + any_sent = true; + continue; + } + if let Some(b) = state.tab_closes.lock().as_mut() { + b.pending.remove(&label); + } + state.close_settled(&label); + } + if !any_sent { + *state.tab_closes.lock() = None; + if let Some(window) = app.get_webview_window(keep) { + windows::focus(&window); + } + } Ok(()) } -/// The closing tab's project vetoed (its unsaved-changes prompt was cancelled): leave the rest open. +/// The closing tab stayed open (either its prompt was cancelled or it returned to Welcome). pub fn cancel_close(app: &AppHandle, caller: &str) { let state = app.state::(); + let cancelled_batch = { + let mut batch = state.tab_closes.lock(); + if batch.as_ref().is_some_and(|b| b.pending.contains(caller)) { batch.take() } else { None } + }; + if let Some(batch) = cancelled_batch { + // A vetoed Close Other/Left/Right Tabs leaves the remaining tabs open too. + state.abort_batch(batch.pending.into_iter().filter(|l| l != caller)); + state.close_settled(caller); + return; + } state.close_settled(caller); - let mut batch = state.tab_closes.lock(); - if batch.as_ref().is_some_and(|b| b.pending.front().is_some_and(|l| l == caller)) { - *batch = None; + // For a red-button group close where this tab stayed open (e.g. returned to Welcome), + // select it so closing siblings disappear behind it without flashing. + if state.groups.lock().group(caller).is_some() + && let Some(window) = app.get_webview_window(caller) + { + windows::focus(&window); + } + if !state.has_other_pending_closes(caller) && !state.quitting() { + let app = app.clone(); + tauri::async_runtime::spawn(async move { + let _ = persist(&app).await; + }); } } -fn close_next(app: &AppHandle) { +/// Waits for the caller's interactive prompt turn in a parallel batch close and brings it forward. +/// Returns `false` if the batch was cancelled while waiting (the caller should stay open quietly). +pub async fn begin_prompt(app: &AppHandle, window: &WebviewWindow) -> bool { + let label = window.label(); let state = app.state::(); loop { - let next = { - let mut batch = state.tab_closes.lock(); - let Some(b) = batch.as_mut() else { return }; - match b.pending.front() { - Some(label) => Ok(label.clone()), - None => Err(batch.take().unwrap().keep), + let notified = state.close_notify.notified(); + tokio::pin!(notified); + notified.as_mut().enable(); + + match state.try_acquire_prompt(label) { + Ok(true) => { + windows::focus(window); + return true; } - }; - match next { - Ok(label) => { - if let Some(window) = app.get_webview_window(&label) { - windows::focus(&window); - if window.close().is_ok() { - return; - } - } - if let Some(b) = state.tab_closes.lock().as_mut() { - b.pending.pop_front(); - } + Ok(false) => { + notified.await; } - Err(keep) => { - if let Some(window) = app.get_webview_window(&keep) { - windows::focus(&window); - } - return; + Err(()) => { + state.take_aborted(label); + return false; } } } } +pub fn end_prompt(app: &AppHandle, caller: &str) { + app.state::().release_prompt(caller); +} + +/// Coordinates the final hide/destroy step across windows closing together. +/// Returns `false` if the batch was cancelled while waiting (the caller must stay open). +pub async fn ready_to_close(app: &AppHandle, window: &WebviewWindow) -> bool { + let label = window.label(); + let state = app.state::(); + if !state.mark_ready(label) { + return false; + } + + const BARRIER_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(3); + const POLL_STEP: std::time::Duration = std::time::Duration::from_millis(250); + let mut waited_idle = std::time::Duration::ZERO; + let mut last_tick = std::time::Instant::now(); + + loop { + let notified = state.close_notify.notified(); + tokio::pin!(notified); + notified.as_mut().enable(); + + if state.take_aborted(label) { + return false; + } + + let (cohort, keep_label) = close_cohort(app, &state, label); + let any_undecided = + cohort.iter().any(|peer| peer != label && app.get_webview_window(peer).is_some() && !state.is_ready(peer)); + + if !any_undecided { + finish_cohort_visuals(app, &state, label, &cohort, keep_label.as_deref()); + state.close_notify.notify_waiters(); + return true; + } + + match tokio::time::timeout(POLL_STEP, notified).await { + Ok(()) => { + waited_idle = std::time::Duration::ZERO; + last_tick = std::time::Instant::now(); + } + Err(_) => { + // Never time out while another tab is waiting on the user's answer to a dialog. + if state.has_prompt_holder() { + waited_idle = std::time::Duration::ZERO; + } else { + waited_idle += last_tick.elapsed(); + if waited_idle >= BARRIER_TIMEOUT { + let single = vec![label.to_owned()]; + if !state.claim_hide(&single).is_empty() && state.groups.lock().group(label).is_none() { + windows::hide_windows(vec![window.clone()]); + } + return true; + } + } + last_tick = std::time::Instant::now(); + } + } + } +} + +fn close_cohort(app: &AppHandle, state: &WindowsState, label: &str) -> (Vec, Option) { + if state.quitting() { + let pending = state.pending_closes(); + let mut cohort: Vec = windows::project_window_labels(app) + .into_iter() + .filter(|l| l == label || pending.iter().any(|p| p == l)) + .collect(); + if !cohort.iter().any(|l| l == label) { + cohort.push(label.to_owned()); + } + return (cohort, None); + } + if let Some((keep, pending)) = state + .tab_closes + .lock() + .as_ref() + .filter(|b| b.pending.contains(label)) + .map(|b| (b.keep.clone(), b.pending.iter().cloned().collect::>())) + { + return (pending, Some(keep)); + } + let pending = state.pending_closes(); + let group_members = state.groups.lock().group(label).map(|g| g.members.clone()); + if let Some(members) = group_members { + let mut cohort: Vec = + members.into_iter().filter(|m| m == label || pending.iter().any(|p| p == m)).collect(); + if !cohort.iter().any(|l| l == label) { + cohort.push(label.to_owned()); + } + return (cohort, None); + } + (vec![label.to_owned()], None) +} + +/// Applies the visual transition once every peer in `cohort` is ready to close: +/// - Whole closing window or whole closing tab group (or quit): hide all of them in a single frame. +/// - Partial tab group close (Close Other Tabs, single tab close, or keeper returning to Welcome): +/// ensure a surviving tab is selected so the closing tabs tear down invisibly behind it. +fn finish_cohort_visuals( + app: &AppHandle, + state: &WindowsState, + label: &str, + cohort: &[String], + keep_label: Option<&str>, +) { + if state.quitting() { + let to_hide = state.claim_hide(cohort); + let windows: Vec<_> = to_hide.into_iter().filter_map(|l| app.get_webview_window(&l)).collect(); + windows::hide_windows(windows); + return; + } + let group_snapshot = state.groups.lock().group(label).cloned(); + if let Some(group) = group_snapshot { + let cohort_set: HashSet<&str> = cohort.iter().map(String::as_str).collect(); + let all_closing = group.members.iter().all(|m| cohort_set.contains(m.as_str())); + if all_closing { + let to_hide = state.claim_hide(&group.members); + let windows: Vec<_> = to_hide.into_iter().filter_map(|l| app.get_webview_window(&l)).collect(); + windows::hide_windows(windows); + } else { + let survivor = keep_label + .filter(|k| !cohort_set.contains(*k)) + .map(str::to_owned) + .or_else(|| group.members.iter().find(|m| !cohort_set.contains(m.as_str())).cloned()); + // Only switch tabs if the currently visible tab is one of the closing ones. + if cohort_set.contains(group.selected.as_str()) + && let Some(survivor) = survivor + && !state.claim_hide(cohort).is_empty() + && let Some(window) = app.get_webview_window(&survivor) + { + windows::focus(&window); + } + } + } else { + let to_hide = state.claim_hide(cohort); + let windows: Vec<_> = to_hide.into_iter().filter_map(|l| app.get_webview_window(&l)).collect(); + windows::hide_windows(windows); + } +} + /// Window labels in creation order: `main`, then `project-1`, `project-2`, …. fn labels_in_order(app: &AppHandle) -> Vec { let mut labels: Vec = app.webview_windows().into_keys().collect(); diff --git a/src-tauri/src/windows.rs b/src-tauri/src/windows.rs index c5a5527f48..8bf9ce8eec 100644 --- a/src-tauri/src/windows.rs +++ b/src-tauri/src/windows.rs @@ -24,8 +24,9 @@ use ide_core::{IdeError, IdeResult}; use parking_lot::Mutex; use serde::{Deserialize, Serialize}; use specta::Type; -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; +use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use tauri::utils::config::{Color, WindowConfig}; use tauri::{AppHandle, Emitter, Manager, Theme, WebviewWindow, WebviewWindowBuilder}; @@ -320,15 +321,16 @@ pub struct WindowsState { cli: Mutex, /// Most recently focused window label (menu events go there). last_focused: Mutex>, - /// Set by Quit while windows close one by one. + /// Set by Quit while windows close in parallel. quitting: AtomicBool, /// The last closed project opted out of Welcome; macOS keeps its app in the Dock. #[cfg(target_os = "macos")] pub keep_alive: AtomicBool, - /// Windows asked to close whose guards have not finished. AppKit closes a whole tab group at - /// once, so its members ask together. - close_requests: Mutex>, - /// Project tabs closing one by one (Close Other Tabs and friends). + /// Coordinates parallel window/tab-group closes so clean tabs hide together in one frame + /// and interactive prompts still run one at a time. + close: Mutex, + pub close_notify: Arc, + /// Project tabs closing in parallel (Close Other Tabs and friends). pub tab_closes: Mutex>, /// Relaunch once the quit completes (after installing an update). restart: AtomicBool, @@ -355,20 +357,180 @@ pub(crate) struct AuxGeometry { pub maximized: bool, } +#[derive(Default)] +struct CloseState { + /// Windows asked to close whose guards have not finished. AppKit closes a whole tab group at + /// once, so its members ask together; Quit and Close Other Tabs also close members in parallel. + pending: Vec, + /// Members that passed their close guard and are waiting at the batch barrier before destroying. + ready: HashSet, + /// Members whose batch was cancelled while they waited; they stay open. + aborted: HashSet, + /// Windows already hidden as part of their closing cohort so hiding only runs once per batch. + hidden: HashSet, + /// Window currently showing an interactive close dialog (at most one across a batch). + prompt_holder: Option, +} + impl WindowsState { pub fn close_requested(&self, label: &str) { - let mut requests = self.close_requests.lock(); - if !requests.iter().any(|l| l == label) { - requests.push(label.to_owned()); + let mut close = self.close.lock(); + close.aborted.remove(label); + close.ready.remove(label); + close.hidden.remove(label); + if !close.pending.iter().any(|l| l == label) { + close.pending.push(label.to_owned()); } } pub fn close_settled(&self, label: &str) { - self.close_requests.lock().retain(|l| l != label); + { + let mut close = self.close.lock(); + close.pending.retain(|l| l != label); + close.ready.remove(label); + close.aborted.remove(label); + close.hidden.remove(label); + if close.prompt_holder.as_deref() == Some(label) { + close.prompt_holder = None; + } + } + self.close_notify.notify_waiters(); } pub fn pending_closes(&self) -> Vec { - self.close_requests.lock().clone() + self.close.lock().pending.clone() + } + + pub fn is_closing(&self, label: &str) -> bool { + let in_close = { + let close = self.close.lock(); + close.pending.iter().any(|l| l == label) || close.ready.contains(label) + }; + in_close || self.in_tab_close_batch(label) + } + + pub fn has_other_pending_closes(&self, exclude: &str) -> bool { + let other_pending = self.close.lock().pending.iter().any(|l| l != exclude); + other_pending || self.tab_closes.lock().as_ref().is_some_and(|b| b.has_other(exclude)) + } + + pub fn in_tab_close_batch(&self, label: &str) -> bool { + self.tab_closes.lock().as_ref().is_some_and(|b| b.contains(label)) + } + + /// Marks `label` ready to destroy. Returns `false` if its batch was already cancelled. + pub fn mark_ready(&self, label: &str) -> bool { + let ok = { + let mut close = self.close.lock(); + if close.aborted.remove(label) { + close.pending.retain(|l| l != label); + close.ready.remove(label); + close.hidden.remove(label); + if close.prompt_holder.as_deref() == Some(label) { + close.prompt_holder = None; + } + false + } else { + if close.prompt_holder.as_deref() == Some(label) { + close.prompt_holder = None; + } + close.ready.insert(label.to_owned()); + true + } + }; + self.close_notify.notify_waiters(); + ok + } + + pub fn is_ready(&self, label: &str) -> bool { + self.close.lock().ready.contains(label) + } + + pub fn take_aborted(&self, label: &str) -> bool { + let mut close = self.close.lock(); + if close.aborted.remove(label) { + close.pending.retain(|l| l != label); + close.ready.remove(label); + close.hidden.remove(label); + true + } else { + false + } + } + + /// Marks `labels` as hidden once and returns those newly claimed for hiding. + pub fn claim_hide(&self, labels: &[String]) -> Vec { + let mut close = self.close.lock(); + labels.iter().filter(|l| close.hidden.insert((*l).clone())).cloned().collect() + } + + /// Marks `labels` as aborted so peers waiting at the close barrier or prompt turn stay open. + pub fn abort_batch(&self, labels: impl IntoIterator) { + { + let mut close = self.close.lock(); + for label in labels { + close.ready.remove(&label); + close.hidden.remove(&label); + close.pending.retain(|l| l != &label); + close.aborted.insert(label); + } + close.prompt_holder = None; + } + self.close_notify.notify_waiters(); + } + + /// Aborts every in-flight close except `initiator` (used when cancelling Quit). + pub fn abort_all_closing(&self, initiator: Option<&str>) { + { + let mut close = self.close.lock(); + let mut targets: Vec = close.pending.drain(..).collect(); + for label in close.ready.drain() { + if !targets.iter().any(|l| l == &label) { + targets.push(label); + } + } + close.hidden.clear(); + close.prompt_holder = None; + for label in targets { + if initiator != Some(label.as_str()) { + close.aborted.insert(label); + } + } + } + self.close_notify.notify_waiters(); + } + + /// Tries to acquire the interactive prompt turn. `Err(())` means this close was aborted. + pub fn try_acquire_prompt(&self, label: &str) -> Result { + let mut close = self.close.lock(); + if close.aborted.contains(label) { + return Err(()); + } + if close.prompt_holder.is_none() || close.prompt_holder.as_deref() == Some(label) { + close.prompt_holder = Some(label.to_owned()); + Ok(true) + } else { + Ok(false) + } + } + + pub fn release_prompt(&self, label: &str) { + let released = { + let mut close = self.close.lock(); + if close.prompt_holder.as_deref() == Some(label) { + close.prompt_holder = None; + true + } else { + false + } + }; + if released { + self.close_notify.notify_waiters(); + } + } + + pub fn has_prompt_holder(&self) -> bool { + self.close.lock().prompt_holder.is_some() } pub fn set_launch(&self, label: &str, launch: Launch) { @@ -747,22 +909,68 @@ pub fn focus(window: &WebviewWindow) { let _ = window.set_focus(); } -/// Present one project's save prompt at a time, including hidden group members. -pub fn continue_quit(app: &AppHandle, closed: Option<&str>) { - if !app.state::().quitting() { +pub fn hide_windows(windows: Vec) { + #[cfg(target_os = "macos")] + crate::macos::hide_windows(windows); + #[cfg(not(target_os = "macos"))] + for window in windows { + let _ = window.hide(); + } +} + +/// Closes every project window in parallel without flipping focus across clean tabs. +/// Windows that need user confirmation acquire the prompt turn one at a time via `begin_prompt`. +pub fn start_quit(app: &AppHandle) { + let state = app.state::(); + let labels = project_window_labels(app); + if labels.is_empty() { + app.exit(0); return; } - let next = project_window_labels(app) - .into_iter() - .filter(|label| Some(label.as_str()) != closed) - .find_map(|label| app.get_webview_window(&label)); - if let Some(window) = next { - focus(&window); - if window.close().is_err() { - app.state::().set_quitting(false); + for label in &labels { + state.close_requested(label); + } + let mut any_sent = false; + for label in labels { + if let Some(window) = app.get_webview_window(&label) + && window.close().is_ok() + { + any_sent = true; + continue; } - } else { + state.close_settled(&label); + } + if !any_sent { + if project_window_labels(app).is_empty() { + app.exit(0); + } else { + state.set_quitting(false); + } + } +} + +/// Exits once every project window has finished closing during Quit. +pub fn continue_quit(app: &AppHandle, closed: Option<&str>) { + let state = app.state::(); + if !state.quitting() { + return; + } + let remaining: Vec = + project_window_labels(app).into_iter().filter(|label| Some(label.as_str()) != closed).collect(); + if remaining.is_empty() { app.exit(0); + return; + } + // Close any window that appeared after Quit began and was not yet asked to close. + for label in remaining { + if !state.is_closing(&label) + && let Some(window) = app.get_webview_window(&label) + { + state.close_requested(&label); + if window.close().is_err() { + state.close_settled(&label); + } + } } } @@ -3106,4 +3314,38 @@ mod tests { assert_eq!(menu_settings_launch("main", true, true, "file.settings", None), None); assert_eq!(menu_settings_launch("main", false, true, "file.openProject", None), None); } + + #[test] + fn parallel_close_coordination_tracks_ready_prompt_and_abort() { + let st = WindowsState::default(); + st.close_requested("main"); + st.close_requested("project-1"); + assert!(st.is_closing("main")); + assert!(st.has_other_pending_closes("main")); + + // Prompt turn allows only one holder at a time. + assert_eq!(st.try_acquire_prompt("main"), Ok(true)); + assert_eq!(st.try_acquire_prompt("project-1"), Ok(false)); + assert!(st.has_prompt_holder()); + + // Marking ready releases the prompt turn. + assert!(st.mark_ready("main")); + assert!(!st.has_prompt_holder()); + assert_eq!(st.try_acquire_prompt("project-1"), Ok(true)); + + // Cancelling the batch aborts waiting ready peers and clears the prompt holder. + st.abort_all_closing(Some("project-1")); + assert!(!st.has_prompt_holder()); + assert!(st.take_aborted("main")); + assert!(!st.is_closing("main")); + assert!(!st.take_aborted("project-1")); + + // A fresh close clears any stale aborted state and claims hide once per cohort. + st.close_requested("main"); + assert_eq!( + st.claim_hide(&["main".into(), "project-1".into()]), + vec!["main".to_string(), "project-1".to_string()] + ); + assert!(st.claim_hide(&["main".into(), "project-1".into()]).is_empty()); + } } diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index b979276c10..2875763af7 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -830,10 +830,12 @@ web_open always desktop bin web_serves_page trusted desktop bindings async web_unresolved_references always project_host bindings async web_url always project_host bindings async +window_begin_prompt always desktop bindings async window_close_context always desktop bindings sync window_complete_launch always desktop bindings sync window_cycle always desktop bindings sync window_drag_files always desktop bindings async +window_end_prompt always desktop bindings sync window_flash_taskbar always desktop bindings sync window_group_cancel_close always desktop bindings sync window_group_close always desktop bindings sync @@ -857,6 +859,7 @@ window_open_project always desktop bin window_open_projects always desktop bindings sync window_open_remote always desktop bindings async window_open_settings always desktop bindings async +window_ready_to_close always desktop bindings async window_set_smooth_scrolling always desktop bindings sync window_set_titlebar_height always desktop bindings sync window_start_drag always desktop bindings sync diff --git a/src/bindings.ts b/src/bindings.ts index 1933a4a544..c9897bf752 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -218,7 +218,7 @@ export const commands = { * Async: the process walk runs on the blocking pool, not the main thread. */ appMetrics: () => typedError(__TAURI_INVOKE("app_metrics")), - /** Quits: closes every window, each of which runs its own unsaved-changes check. */ + /** Quits: closes every window in parallel, each of which runs its own unsaved-changes check. */ appQuit: () => __TAURI_INVOKE("app_quit"), /** * Release notes of `version` from the update manifest (`latest.json`), read @@ -2281,6 +2281,11 @@ export const commands = { * HTML (Settings › File Types can make it so) is served as a page, whatever its extension. */ webUrl: (path: IpcPath) => typedError(__TAURI_INVOKE("web_url", { path })), + /** + * Acquires the interactive prompt turn for a batch close and brings this window forward. + * Returns `false` if the batch was cancelled while waiting. + */ + windowBeginPrompt: () => __TAURI_INVOKE("window_begin_prompt"), windowCloseContext: () => __TAURI_INVOKE("window_close_context"), /** Release the opening window's reservation after navigation or cancellation. */ windowCompleteLaunch: () => typedError(__TAURI_INVOKE("window_complete_launch")), @@ -2292,6 +2297,8 @@ export const commands = { * with whether a target took the files. */ windowDragFiles: (paths: string[]) => typedError(__TAURI_INVOKE("window_drag_files", { paths })), + /** Releases the interactive prompt turn held by this window. */ + windowEndPrompt: () => __TAURI_INVOKE("window_end_prompt"), /** * Flash (`true`) or stop flashing (`false`) this window's taskbar button, like IDEA when a * breakpoint is hit while the window is in the background (macOS bounces the dock icon, @@ -2371,6 +2378,11 @@ export const commands = { * `background` (`#rrggbb`) paints a new window until its page has loaded. */ windowOpenSettings: (page: string | null, newProjects: boolean, background: string | null) => typedError(__TAURI_INVOKE("window_open_settings", { page, newProjects, background })), + /** + * Signals that this window passed its close checks and waits for peers closing in the same + * batch/tab group so they hide together in one frame. Returns `false` if the batch was cancelled. + */ + windowReadyToClose: () => __TAURI_INVOKE("window_ready_to_close"), /** Appearance › Smooth scrolling for this window's web view (Linux only) */ windowSetSmoothScrolling: (enabled: boolean) => typedError(__TAURI_INVOKE("window_set_smooth_scrolling", { enabled })), /** Height of the web title bar in native logical pixels (CSS height × IDE zoom). */ @@ -4245,6 +4257,10 @@ export type CloseContext = { quitting: boolean, /** Number of open project windows (settings windows excluded), including the caller. */ windows: number, + /** Whether this window currently has auxiliary document windows that must settle first. */ + hasDocumentWindows: boolean, + /** Whether this close runs alongside other windows or on a background tab (prompts serialize and raise). */ + batch: boolean, }; export type CodeAction = { diff --git a/src/features/app/__tests__/windowClose.test.ts b/src/features/app/__tests__/windowClose.test.ts index 2a48166a79..329443cfdb 100644 --- a/src/features/app/__tests__/windowClose.test.ts +++ b/src/features/app/__tests__/windowClose.test.ts @@ -35,7 +35,15 @@ const flushSession = vi.fn(); beforeEach(() => { vi.spyOn(ipc, "isTauri").mockReturnValue(true); vi.spyOn(ipc, "onIdeEvent").mockReturnValue(() => {}); - vi.spyOn(ipc.commands, "windowCloseContext").mockResolvedValue({ quitting: false, windows: 1 }); + vi.spyOn(ipc.commands, "windowCloseContext").mockResolvedValue({ + quitting: false, + windows: 1, + hasDocumentWindows: false, + batch: false, + }); + vi.spyOn(ipc.commands, "windowBeginPrompt").mockResolvedValue(true); + vi.spyOn(ipc.commands, "windowEndPrompt").mockResolvedValue(undefined); + vi.spyOn(ipc.commands, "windowReadyToClose").mockResolvedValue(true); vi.spyOn(ipc.commands, "windowGroupCancelClose").mockResolvedValue(undefined); vi.spyOn(ipc.commands, "appCancelQuit").mockResolvedValue(undefined); vi.spyOn(ipc.commands, "closeProject").mockResolvedValue(undefined); @@ -89,7 +97,12 @@ describe("native window close", () => { }); it.each([1, 2])("closes one of %s windows when opted in", async (windows) => { - vi.mocked(ipc.commands.windowCloseContext).mockResolvedValue({ quitting: false, windows }); + vi.mocked(ipc.commands.windowCloseContext).mockResolvedValue({ + quitting: false, + windows, + hasDocumentWindows: false, + batch: false, + }); const prevented = await close({ closeWithoutWelcome: true, closeTabsWithWindow: true }); expect(prevented).not.toHaveBeenCalled(); expect(ipc.commands.closeProject).not.toHaveBeenCalled(); @@ -97,7 +110,12 @@ describe("native window close", () => { }); it("closes a nonlast window with defaults and keeps its saved tabs", async () => { - vi.mocked(ipc.commands.windowCloseContext).mockResolvedValue({ quitting: false, windows: 2 }); + vi.mocked(ipc.commands.windowCloseContext).mockResolvedValue({ + quitting: false, + windows: 2, + hasDocumentWindows: false, + batch: false, + }); const prevented = await close({}); expect(prevented).not.toHaveBeenCalled(); expect(ipc.commands.closeProject).not.toHaveBeenCalled(); @@ -126,7 +144,12 @@ describe("native window close", () => { }); it("stays open when an untitled buffer's Save As is cancelled", async () => { - vi.mocked(ipc.commands.windowCloseContext).mockResolvedValue({ quitting: false, windows: 2 }); + vi.mocked(ipc.commands.windowCloseContext).mockResolvedValue({ + quitting: false, + windows: 2, + hasDocumentWindows: false, + batch: false, + }); vi.mocked(services.maybeEditorService).mockReturnValue({ forgetSavedTabs: forget, keepSavedTabs: keep, @@ -159,7 +182,12 @@ describe("native window close", () => { os: "linux", commands: [], }); - vi.mocked(ipc.commands.windowCloseContext).mockResolvedValue({ quitting: false, windows: 2 }); + vi.mocked(ipc.commands.windowCloseContext).mockResolvedValue({ + quitting: false, + windows: 2, + hasDocumentWindows: false, + batch: false, + }); vi.mocked(deps.ask).mockResolvedValueOnce({ button: "keep", checked: false }); const terminate = vi.fn(async () => {}); deps.runningProcesses = vi.fn(async () => ["docker compose up"]); @@ -221,7 +249,12 @@ describe("quitting from outside the window", () => { }); it("leaves a window with nothing to ask where it is while the app quits", async () => { - vi.mocked(ipc.commands.windowCloseContext).mockResolvedValue({ quitting: true, windows: 2 }); + vi.mocked(ipc.commands.windowCloseContext).mockResolvedValue({ + quitting: true, + windows: 2, + hasDocumentWindows: false, + batch: true, + }); deps.runningProcesses = async () => []; const { d, asked } = recordingDeps("cancel"); useProject.setState({ @@ -234,10 +267,17 @@ describe("quitting from outside the window", () => { await native.close!({ preventDefault: vi.fn() }); expect(asked).toEqual([]); expect(native.order).toEqual([]); + expect(ipc.commands.windowBeginPrompt).not.toHaveBeenCalled(); + expect(ipc.commands.windowReadyToClose).toHaveBeenCalledOnce(); }); it("raises each window before the prompts a quit makes it show", async () => { - vi.mocked(ipc.commands.windowCloseContext).mockResolvedValue({ quitting: true, windows: 2 }); + vi.mocked(ipc.commands.windowCloseContext).mockResolvedValue({ + quitting: true, + windows: 2, + hasDocumentWindows: false, + batch: true, + }); deps.runningProcesses = async () => ["server.js"]; const { d } = recordingDeps("cancel"); useProject.setState({ @@ -249,6 +289,48 @@ describe("quitting from outside the window", () => { await vi.waitFor(() => expect(native.close).toBeDefined()); await native.close!({ preventDefault: vi.fn() }); expect(native.order.slice(0, 4)).toEqual(["unminimize", "show", "setFocus", "ask"]); + expect(ipc.commands.windowBeginPrompt).toHaveBeenCalledOnce(); + expect(ipc.commands.windowEndPrompt).toHaveBeenCalledOnce(); expect(ipc.commands.appCancelQuit).toHaveBeenCalledOnce(); }); + + it("restores saved tabs and stays open when a peer cancels the batch at the close barrier", async () => { + vi.mocked(ipc.commands.windowCloseContext).mockResolvedValue({ + quitting: true, + windows: 2, + hasDocumentWindows: false, + batch: true, + }); + vi.mocked(ipc.commands.windowReadyToClose).mockResolvedValueOnce(false); + const prevented = await close({ closeTabsWithWindow: true }); + expect(prevented).toHaveBeenCalledOnce(); + expect(forget).toHaveBeenCalledOnce(); + expect(keep).toHaveBeenCalledOnce(); + expect(ipc.commands.appCancelQuit).not.toHaveBeenCalled(); + }); + + it("skips prompting when a peer already cancelled the batch while waiting for the prompt turn", async () => { + vi.mocked(ipc.commands.windowCloseContext).mockResolvedValue({ + quitting: true, + windows: 2, + hasDocumentWindows: false, + batch: true, + }); + vi.mocked(ipc.commands.windowBeginPrompt).mockResolvedValueOnce(false); + deps.runningProcesses = async () => ["server.js"]; + const { d, asked } = recordingDeps("terminate"); + useProject.setState({ + project: { root: "/project", name: "project" }, + lightEdit: false, + settings: { general: {} }, + } as never); + uninstall = installCloseGuard(d); + await vi.waitFor(() => expect(native.close).toBeDefined()); + const preventDefault = vi.fn(); + await native.close!({ preventDefault }); + expect(preventDefault).toHaveBeenCalledOnce(); + expect(asked).toEqual([]); + expect(native.order).toEqual([]); + expect(ipc.commands.appCancelQuit).not.toHaveBeenCalled(); + }); }); diff --git a/src/features/app/closeGuard.ts b/src/features/app/closeGuard.ts index e35d35a294..c7e7f3b45f 100644 --- a/src/features/app/closeGuard.ts +++ b/src/features/app/closeGuard.ts @@ -248,8 +248,12 @@ async function onCloseRequested(deps: CloseDeps): Promise { closing = true; let forgot = false; let quitting = false; + let promptHeld = false; + let batchAborted = false; const cancel = async () => { - await (quitting ? commands.appCancelQuit() : commands.windowGroupCancelClose()); + if (!batchAborted) { + await (quitting ? commands.appCancelQuit() : commands.windowGroupCancelClose()); + } return false; }; const undoForget = () => { @@ -260,9 +264,27 @@ async function onCloseRequested(deps: CloseDeps): Promise { try { const ctx = await commands.windowCloseContext(); quitting = ctx.quitting; - // Each window of a quit asks about its own processes and unsaved changes, if it has any. - if (quitting) deps = raisingBeforeAsk(deps); - if (!(await closeDocumentWindows())) return await cancel(); + // In a quit or multi-tab close, windows check in parallel; only a window that needs to ask + // acquires the prompt turn and comes forward so prompts still run one at a time. + if (quitting || ctx.batch) { + const baseAsk = deps.ask; + deps = { + ...deps, + ask: async (request) => { + if (!promptHeld) { + const proceed = await commands.windowBeginPrompt(); + if (!proceed) { + batchAborted = true; + return { button: "cancel", checked: false }; + } + promptHeld = true; + } + await raiseWindowForPrompts(); + return baseAsk(request); + }, + }; + } + if (ctx.hasDocumentWindows !== false && !(await closeDocumentWindows())) return await cancel(); const s = useProject.getState(); const welcome = returnsToWelcome(quitting, ctx.windows, !!(s.project || s.lightEdit), s.settings); const remote = useRemote.getState(); @@ -316,6 +338,12 @@ async function onCloseRequested(deps: CloseDeps): Promise { forgot = false; return await cancel(); } + if (!(await commands.windowReadyToClose())) { + batchAborted = true; + undoForget(); + maybeEditorService()?.cancelClose?.(); + return false; + } return true; } catch (e) { undoForget(); @@ -324,6 +352,10 @@ async function onCloseRequested(deps: CloseDeps): Promise { deps.onSaveFailed(e); return false; } finally { + if (promptHeld) { + promptHeld = false; + void commands.windowEndPrompt().catch(() => {}); + } closing = false; } }