All your AI agent sessions in one place — browse, search, resume. Rust + GPUI.
Rust
fix(linux): finish main-window shutdown with a bounded fallback (#54)
Bet48e1f58172050
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4dff21e..9e22d45 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,9 @@# Changelog+## Unreleased++- Fix: Closing the main window on Linux requests application shutdown, with a timeout fallback if shutdown stalls. Settings windows close independently, and pending window geometry is saved before quitting (#54, thanks @bet4it).+## [0.8.4] — 2026-09-25- Fix: Remote sync skips Unix sockets and FIFOs in agent directories, preventing long cache paths from causing `mkstempsock: Invalid argument` and a persistent Sync failed status on macOS (#47).diff --git a/crates/wake-core/src/adapters/parse_utils.rs b/crates/wake-core/src/adapters/parse_utils.rsindex 2209660..9839e96 100644--- a/crates/wake-core/src/adapters/parse_utils.rs+++ b/crates/wake-core/src/adapters/parse_utils.rs@@ -1126,7 +1126,10 @@ mod tests {let object = serde_json::json!({"exit_code": 0, "duration_ms": 12});let parsed = tool_result_parts(&object, true);assert!(parsed.images.is_empty());- assert_eq!(parsed.text, r#"{"duration_ms":12,"exit_code":0}"#);+ let expected: serde_json::Value =+ serde_json::from_str(r#"{"duration_ms":12,"exit_code":0}"#).unwrap();+ let actual: serde_json::Value = serde_json::from_str(&parsed.text).unwrap();+ assert_eq!(actual, expected);}#[test]diff --git a/crates/wake-core/src/watcher.rs b/crates/wake-core/src/watcher.rsindex f2d3be9..01cbcaf 100644--- a/crates/wake-core/src/watcher.rs+++ b/crates/wake-core/src/watcher.rs@@ -369,4 +369,28 @@ mod tests {let claimed = fx.store.claimed_keys().unwrap();assert!(!claimed.contains("claude-code:sdk-1"), "{claimed:?}");}++ #[test]+ fn dropping_watcher_joins_worker_and_releases_its_state() {+ let fx = Fixture::new();+ let adapters = Arc::new(fx.adapters);+ let watcher = start_watcher(adapters.clone(), fx.store.clone(), Arc::new(NullEvents))+ .expect("fixture must create a watcher");+ assert_eq!(+ watcher.watched_roots(),+ &std::collections::BTreeSet::from([fx.root])+ );++ // 在另一条线程 drop,让真正的死锁变成有界失败,而不是永远到不了耗时断言。+ let (tx, rx) = mpsc::channel();+ let dropper = std::thread::spawn(move || {+ drop(watcher);+ tx.send(()).unwrap();+ });+ rx.recv_timeout(Duration::from_secs(5))+ .expect("watcher drop must stop and join its worker");+ dropper.join().unwrap();+ assert_eq!(Arc::strong_count(&adapters), 1);+ assert_eq!(Arc::strong_count(&fx.store), 1);+ }}diff --git a/crates/wake/src/main.rs b/crates/wake/src/main.rsindex be1c1c1..c0b9f09 100644--- a/crates/wake/src/main.rs+++ b/crates/wake/src/main.rs@@ -97,6 +97,8 @@ fn open_main_window(cx: &mut App) -> anyhow::Result<WindowHandle<Root>> {.detach();theme::sync_appearance(Some(window), cx);+ window.on_window_should_close(cx, main_window::should_close);+let workbench = cx.new(|cx| Workbench::new(window, cx));window.focus(&workbench.read(cx).focus_handle(cx), cx);cx.new(|cx| {@@ -189,12 +191,12 @@ fn show_main_window_now(/// 窗口级操作(关/最小化/缩放/全屏)从全局监听器发起时,目标窗口正处在派发/// 这个 action 的 update 中(键位与菜单两条路都如此),被借出的窗口不能再次/// update——返回 Err 被 .ok() 吞掉就是"⌘W 没反应"。推迟到本轮 update 结束再动-fn with_active_window(cx: &mut App, f: impl FnOnce(&mut Window) + 'static) {+fn with_active_window(cx: &mut App, f: impl FnOnce(&mut Window, &mut App) + 'static) {let Some(w) = cx.active_window() else {return;};cx.defer(move |cx| {- w.update(cx, |_, window, _| f(window)).ok();+ w.update(cx, |_, window, cx| f(window, cx)).ok();});}@@ -316,7 +318,7 @@ fn main() {i18n::init();theme::sync_appearance(None, cx);- cx.on_action(|_: &Quit, cx| cx.quit());+ cx.on_action(|_: &Quit, cx| main_window::quit(cx));// 退出前把主窗几何落盘(节流写盘可能还没触发);Dock 的 Quit、注销关机// 都走这里,不只 ⌘Qcx.on_app_quit(|cx| {@@ -324,10 +326,12 @@ fn main() {async {}}).detach();- cx.on_action(|_: &CloseWindow, cx| with_active_window(cx, |w| w.remove_window()));- cx.on_action(|_: &Minimize, cx| with_active_window(cx, |w| w.minimize_window()));- cx.on_action(|_: &Zoom, cx| with_active_window(cx, |w| w.zoom_window()));- cx.on_action(|_: &ToggleFullScreen, cx| with_active_window(cx, |w| w.toggle_fullscreen()));+ cx.on_action(|_: &CloseWindow, cx| with_active_window(cx, main_window::close));+ cx.on_action(|_: &Minimize, cx| with_active_window(cx, |w, _| w.minimize_window()));+ cx.on_action(|_: &Zoom, cx| with_active_window(cx, |w, _| w.zoom_window()));+ cx.on_action(|_: &ToggleFullScreen, cx| {+ with_active_window(cx, |w, _| w.toggle_fullscreen())+ });cx.on_action(|_: &Hide, cx| cx.hide());cx.on_action(|_: &HideOthers, cx| cx.hide_other_apps());cx.on_action(|_: &ShowAll, cx| cx.unhide_other_apps());diff --git a/crates/wake/src/main_window.rs b/crates/wake/src/main_window.rsindex 81a8b89..cdfbb5e 100644--- a/crates/wake/src/main_window.rs+++ b/crates/wake/src/main_window.rs@@ -184,6 +184,59 @@ pub fn flush(cx: &mut App) {}}+/// Linux 的主窗关闭即退出;从属窗口以及其他平台仍走普通关窗。+/// 返回 false 保留主窗,交给事件循环退出后的 GPUI shutdown 统一释放,+/// 不在正在派发关闭事件的窗口回调里销毁它。+pub fn should_close(window: &mut Window, cx: &mut App) -> bool {+ let is_main = cx+ .try_global::<MainWindow>()+ .is_some_and(|main| AnyWindowHandle::from(main.0) == window.window_handle());+ if cfg!(target_os = "linux") && is_main {+ quit(cx);+ false+ } else {+ true+ }+}++/// 客户端标题栏和 CloseWindow 快捷键共用,与原生关闭请求采用相同策略。+pub fn close(window: &mut Window, cx: &mut App) {+ if should_close(window, cx) {+ window.remove_window();+ }+}++/// 先请求正常退出,让 on_app_quit、窗口释放和 watcher 的 join 有机会完成。+/// Linux 有关窗后一直挂起的反馈,独立线程只在退出超过期限时兜底,不把+/// 尚未定位的 Wayland/驱动/清理阻塞当作每次都要跳过析构的理由。+pub fn quit(cx: &mut App) {+ if cfg!(target_os = "linux") {+ flush(cx);+ arm_exit_timeout();+ }+ cx.quit();+}++const EXIT_TIMEOUT: Duration = Duration::from_secs(3);++fn arm_exit_timeout() {+ static ARMED: std::sync::Once = std::sync::Once::new();+ ARMED.call_once(|| {+ // 正常退出时 main 返回会结束整个进程,无需等待这个兜底线程。+ // 不能用 GPUI task:若主线程卡在析构或事件循环里,它也无法被调度。+ if let Err(error) = std::thread::Builder::new()+ .name("wake-exit-timeout".into())+ .spawn(|| {+ std::thread::sleep(EXIT_TIMEOUT);+ eprintln!("wake: shutdown exceeded {EXIT_TIMEOUT:?}; forcing exit");+ std::process::exit(0);+ })+ {+ eprintln!("wake: could not start exit timeout: {error}");+ }+ });+}+fn load() -> Option<SavedWindow> {serde_json::from_str(&prefs::read("window.json")?).ok()}@@ -262,3 +315,7 @@ pub fn centered_over_main(size: Size<Pixels>, cx: &mut App) -> (Bounds<Pixels>,None => (Bounds::centered(None, size, cx), None),}}++#[cfg(test)]+#[path = "main_window_tests.rs"]+mod tests;diff --git a/crates/wake/src/main_window_tests.rs b/crates/wake/src/main_window_tests.rsnew file mode 100644index 0000000..f5409ca--- /dev/null+++ b/crates/wake/src/main_window_tests.rs@@ -0,0 +1,197 @@+use super::{+ arm_exit_timeout, close, flush, quit, should_close, MainGeometry, MainWindow, SavedWindow,+};+use gpui::{+ div, point, px, size, App, AppContext, Bounds, Context, IntoElement, Render, Window,+ WindowHandle, WindowOptions,+};+use gpui_component::Root;+use std::path::{Path, PathBuf};+use std::process::{Command, Output, Stdio};+use std::time::{Duration, Instant};++// The real exit fallback must only run in a child: it must never kill the test runner.+fn child(mode: &str) -> (tempfile::TempDir, Output) {+ let dir = tempfile::tempdir().unwrap();+ let mut child = Command::new(std::env::current_exe().unwrap())+ .args(["--exact", "main_window::tests::exit_child", "--nocapture"])+ .env("WAKE_TEST_EXIT_MODE", mode)+ .env("WAKE_TEST_EXIT_DIR", dir.path())+ .env("HOME", dir.path())+ .env("WAKE_HOME", dir.path())+ .env("XDG_CONFIG_HOME", dir.path().join("config"))+ .env("XDG_DATA_HOME", dir.path().join("data"))+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .spawn()+ .unwrap();+ let start = Instant::now();+ while child.try_wait().unwrap().is_none() {+ if start.elapsed() > Duration::from_secs(15) {+ child.kill().ok();+ let output = child.wait_with_output().unwrap();+ panic!(+ "{mode} did not exit: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ }+ std::thread::sleep(Duration::from_millis(10));+ }+ let output = child.wait_with_output().unwrap();+ assert!(+ output.status.success(),+ "{mode}: {}\n{}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ );+ (dir, output)+}++#[cfg(not(target_os = "linux"))]+#[test]+fn exit_timeout_stops_a_stuck_process() {+ let (dir, output) = child("timeout");+ assert!(dir.path().join("started").is_file());+ assert!(String::from_utf8_lossy(&output.stderr).contains("forcing exit"));+}++// Linux uses its real headless platform and calloop, not GPUI's no-op TestPlatform::quit.+// This covers application lifecycle; compositor/GPU-specific hangs still need desktop testing.+#[cfg(target_os = "linux")]+#[test]+fn linux_window_close_and_quit_run_cleanup_with_a_bounded_fallback() {+ for mode in ["close", "native-close", "quit", "stalled-quit"] {+ let (dir, output) = child(mode);+ for marker in ["secondary-released", "main-survived", "quit-hook"] {+ assert!(+ dir.path().join(marker).is_file(),+ "{mode}: missing {marker}"+ );+ }+ let saved: SavedWindow = serde_json::from_slice(+ &std::fs::read(dir.path().join("config/wake/window.json")).unwrap(),+ )+ .unwrap();+ assert_eq!(saved.bounds.size, size(px(1234.), px(786.)));+ let timed_out = String::from_utf8_lossy(&output.stderr).contains("forcing exit");+ if mode == "stalled-quit" {+ assert!(timed_out);+ assert!(!dir.path().join("returned").exists());+ } else {+ assert!(!timed_out, "{mode} must finish without the fallback");+ for marker in ["main-released", "remaining-released", "returned"] {+ assert!(+ dir.path().join(marker).is_file(),+ "{mode}: missing {marker}"+ );+ }+ }+ }+}++#[test]+fn exit_child() {+ let Ok(mode) = std::env::var("WAKE_TEST_EXIT_MODE") else {+ return;+ };+ let dir = PathBuf::from(std::env::var_os("WAKE_TEST_EXIT_DIR").unwrap());+ if mode == "timeout" {+ std::fs::write(dir.join("started"), b"").unwrap();+ arm_exit_timeout();+ loop {+ std::thread::park();+ }+ }+ native_exit_child(mode, &dir);+}++struct ReleaseMarker(PathBuf);++impl Render for ReleaseMarker {+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {+ div()+ }+}++impl Drop for ReleaseMarker {+ fn drop(&mut self) {+ std::fs::write(&self.0, b"").unwrap();+ }+}++fn test_window(marker: PathBuf, cx: &mut App) -> WindowHandle<Root> {+ cx.open_window(WindowOptions::default(), |window, cx| {+ window.on_window_should_close(cx, should_close);+ let view = cx.new(|_| ReleaseMarker(marker));+ cx.new(|cx| Root::new(view, window, cx))+ })+ .unwrap()+}++// Compiled on every platform so local builds also type-check the Linux-only smoke test.+fn native_exit_child(mode: String, dir: &Path) {+ if !cfg!(target_os = "linux") {+ panic!("native lifecycle checks require Linux");+ }+ let app_dir = dir.to_path_buf();+ gpui_platform::headless()+ .with_assets(crate::assets::Assets)+ .run(move |cx| {+ gpui_component::init(cx);+ let main = test_window(app_dir.join("main-released"), cx);+ cx.set_global(MainWindow(main));+ let secondary = test_window(app_dir.join("secondary-released"), cx);+ let quit_dir = app_dir.clone();+ let stalled = mode == "stalled-quit";+ cx.on_app_quit(move |cx| {+ flush(cx);+ std::fs::write(quit_dir.join("quit-hook"), b"").unwrap();+ if stalled {+ loop {+ std::thread::park();+ }+ }+ async {}+ })+ .detach();++ cx.spawn(async move |cx| {+ cx.update(|cx| {+ secondary+ .update(cx, |_, window, cx| close(window, cx))+ .unwrap()+ });+ // Return to calloop: an accidental application quit from closing Settings+ // must prevent the next stage and fail the parent's marker assertions.+ cx.background_executor()+ .timer(Duration::from_millis(30))+ .await;+ cx.update(|cx| {+ assert_eq!(cx.windows().len(), 1);+ main.update(cx, |_, _, _| {}).unwrap();+ std::fs::write(app_dir.join("main-survived"), b"").unwrap();+ test_window(app_dir.join("remaining-released"), cx);+ // Model a pending debounced geometry update, before it has hit disk.+ let save_task = cx.spawn(async |_| {});+ cx.set_global(MainGeometry {+ saved: SavedWindow::default(),+ live: Some(Bounds {+ origin: point(px(20.), px(30.)),+ size: size(px(1234.), px(786.)),+ }),+ save_task: Some(save_task),+ });+ match mode.as_str() {+ "close" => main.update(cx, |_, window, cx| close(window, cx)).unwrap(),+ "native-close" => main+ .update(cx, |_, window, cx| assert!(!should_close(window, cx)))+ .unwrap(),+ "quit" | "stalled-quit" => quit(cx),+ _ => panic!("unknown exit mode: {mode}"),+ }+ });+ })+ .detach();+ });+ std::fs::write(dir.join("returned"), b"").unwrap();+}diff --git a/crates/wake/src/workbench.rs b/crates/wake/src/workbench.rsindex d9ff524..ab57ea7 100644--- a/crates/wake/src/workbench.rs+++ b/crates/wake/src/workbench.rs@@ -3063,6 +3063,7 @@ impl Workbench {}).detach();crate::theme::sync_appearance(Some(window), cx);+ window.on_window_should_close(cx, crate::main_window::should_close);let settings = cx.new(|cx| SettingsView::new(settings_workbench, window, cx));window.focus(&settings.read(cx).focus_handle(cx), cx);cx.new(|cx| Root::new(settings, window, cx))@@ -5541,7 +5542,11 @@ impl Workbench {// 压平 titlebar 靠 theme.rs 的 title_bar/title_bar_border token;主窗口// 使用 44px 高度,与详情顶部行共享同一垂直节奏。.when(show_titlebar, |this| {- this.child(TitleBar::new().h(WINDOW_TITLEBAR_HEIGHT))+ this.child(TitleBar::new().h(WINDOW_TITLEBAR_HEIGHT).on_close_window(+ |_, window, cx| {+ crate::main_window::close(window, cx);+ },+ ))}).child(div()