Skip to content

armgit / Wake

Public Imported from GitHub
0

All your AI agent sessions in one place — browse, search, resume. Rust + GPUI.

Rust

feat: remember window geometry, complete the menu bar, fix dialogs and bubbles

Corey Chiu047450eef6b0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 10641fa..a995d38 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,17 @@
## Unreleased
+- New: standard macOS Edit and Window menus, so Cut, Copy and Paste work inside system dialogs and Hide, Minimize, Zoom and Full Screen shortcuts do what they should
+- New: Window → Main Window brings the main window back when only Settings is left open
+- Fix: Close Window in the File menu and ⌘W reliably close the window
+- Fix: About, Settings and Check for Updates stay usable in the menu bar after the main window is closed
+- Fix: new sessions no longer go missing until the next refresh when macOS drops file change notifications
+- Fix: the Settings window now opens on the same screen as the Wake window instead of always on the primary display
+- New: Wake remembers which screen and position its window was on and opens there next time, including after a restart or a Dock reopen
+- Fix: your own messages in the conversation view no longer collapse into a one-character-wide column
+- Fix: the close button in the Add location and Edit location dialogs is visible again
+- Fix: clicking outside the Add location dialog or the search palette closes it again
+
## [0.3.5] — 2026-09-02
- New: Open in now offers Claude Desktop for Claude Code sessions and Codex Desktop for Codex sessions, jumping straight to that session in the desktop app
diff --git a/crates/wake-core/src/scanner.rs b/crates/wake-core/src/scanner.rs
index 3f6cc24..ee1decb 100644
--- a/crates/wake-core/src/scanner.rs
+++ b/crates/wake-core/src/scanner.rs
@@ -16,6 +16,10 @@ pub struct ScanProgress {
pub trait ScanEvents: Send + Sync {
fn on_progress(&self, p: &ScanProgress);
fn on_sessions_changed(&self);
+ /// 文件监听后端报告事件丢失(FSEvents 的 MustScanSubDirs / inotify 队列
+ /// 溢出):丢失期间的改动没人知道,需要一轮增量扫描兜底。默认忽略——
+ /// scan CLI 与测试不跑 watcher;GUI 接到后经现有扫描状态机排队
+ fn on_rescan_needed(&self) {}
}
pub struct NullEvents;
@@ -47,6 +51,14 @@ impl Drop for ScanFinale<'_> {
}
}
+/// 进程内同一时刻只跑一条扫描。GUI 里 Dock 重开主窗会新建 Workbench 并立刻
+/// 起一轮启动扫描,而上一个 Workbench 的扫描线程是脱管的(watcher 在 Drop 里
+/// join 了,扫描没有)——不排队就是两条扫描并发改写同一个库。门放在 run_scan
+/// 入口而不是某个调用方:任何起扫描的入口都自动被管住。锁是进程级而非 Store
+/// 级,要挡的正是两个 Store 实例开同一个库文件;扫描 panic 会毒化锁,
+/// into_inner 照常放行。排在后面的照常出终态事件,UI 只是多等一会儿
+static SCAN_GATE: std::sync::Mutex<()> = std::sync::Mutex::new(());
+
/// 全量/增量扫描。quickMeta 先行秒出列表,然后按 mtime 降序逐文件解析。
/// 阻塞执行——调用方放后台线程。进度与终态一律经 `events` 上报,终态由
/// `ScanFinale` 保证送达;返回的 `Result` 只用于调用方自己记日志。
@@ -56,6 +68,9 @@ pub fn run_scan(
events: &dyn ScanEvents,
full: bool,
) -> Result<()> {
+ let _gate = SCAN_GATE
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
let mut fin = ScanFinale {
events,
progress: ScanProgress {
diff --git a/crates/wake-core/src/watcher.rs b/crates/wake-core/src/watcher.rs
index ac6cd2a..dbdca09 100644
--- a/crates/wake-core/src/watcher.rs
+++ b/crates/wake-core/src/watcher.rs
@@ -149,7 +149,18 @@ pub fn start_watcher(
}
let mut parent_link_agents = HashSet::new();
- for ev in batch.into_iter().flatten() {
+ let mut rescan = false;
+ for ev in batch {
+ let Ok(ev) = ev.inspect_err(|e| eprintln!("watcher: notify error: {e}")) else {
+ continue;
+ };
+ // 后端丢过事件(FSEvents MustScanSubDirs / inotify Q_OVERFLOW):
+ // 这条不指向具体会话文件——macOS 挂的是出事的目录、Linux 干脆
+ // 无路径——按路径处理会被 file_ref 静默丢弃,改由整轮增量兜底
+ if ev.need_rescan() {
+ rescan = true;
+ continue;
+ }
for path in ev.paths {
let owner_ix = resolve_ix(&path);
if let Some(adapter) = owner_ix.and_then(|ix| adapters.get(ix)) {
@@ -191,6 +202,9 @@ pub fn start_watcher(
let agents: Vec<AgentId> = parent_link_agents.into_iter().collect();
refresh_parent_links(&adapters, &store, events.as_ref(), &agents);
}
+ if rescan {
+ events.on_rescan_needed();
+ }
}
});
diff --git a/crates/wake/assets/icons/x.svg b/crates/wake/assets/icons/close.svg
similarity index 100%
rename from crates/wake/assets/icons/x.svg
rename to crates/wake/assets/icons/close.svg
diff --git a/crates/wake/src/assets.rs b/crates/wake/src/assets.rs
index e12ed4b..42d6702 100644
--- a/crates/wake/src/assets.rs
+++ b/crates/wake/src/assets.rs
@@ -87,7 +87,7 @@ icons!(
"terminal",
"message-square",
"layers",
- "x",
+ "close",
"git-branch",
"refresh-cw",
"inbox",
diff --git a/crates/wake/src/main.rs b/crates/wake/src/main.rs
index a99be49..d455f54 100644
--- a/crates/wake/src/main.rs
+++ b/crates/wake/src/main.rs
@@ -8,6 +8,8 @@
mod assets;
mod format;
+mod main_window;
+mod prefs;
mod settings;
mod theme;
mod ui;
@@ -17,18 +19,32 @@ mod workbench;
use assets::Assets;
use gpui::*;
use gpui_component::Root;
+use main_window::MainWindow;
use workbench::{
OpenAbout, OpenSettings, OpenUpdates, PaletteDown, PaletteUp, RefreshSessions, ToggleSearch,
Workbench, KEY_CONTEXT, PALETTE_CONTEXT,
};
-actions!(wake_app, [Quit, CloseWindow]);
+actions!(
+ wake_app,
+ [
+ Quit,
+ CloseWindow,
+ Hide,
+ HideOthers,
+ ShowAll,
+ Minimize,
+ Zoom,
+ ToggleFullScreen,
+ ShowMainWindow
+ ]
+);
-// macOS:用户关掉最后一个窗后进程仍留 Dock,点 Dock 图标走 NSApplication 的
-// applicationShouldHandleReopen → gpui Platform::on_reopen。这里复用启动期
-// 的开窗配置,空窗重建、有窗只是把已存在的拉到前台,不重复实例
+/// 开主窗并登记句柄。启动、Dock 重开、Window → Main Window 共用
fn open_main_window(cx: &mut App) -> anyhow::Result<WindowHandle<Root>> {
- let bounds = Bounds::centered(None, size(px(1180.), px(760.)), cx);
+ // 上次关掉时在哪块屏、什么位置就开回哪;bounds 是所选屏幕内的相对坐标,
+ // 必须和 display_id 一起给(见 main_window 模块头)
+ let (window_bounds, display_id) = main_window::restore(cx);
// macOS:隐藏系统标题栏、内容顶到窗顶,traffic light 悬浮在侧栏上;
// Linux/Windows:标准系统标题栏(appears_transparent=false)。Windows
// 后端按此保留原生 caption(min/max/close、snap layouts、深色模式随
@@ -49,10 +65,11 @@ fn open_main_window(cx: &mut App) -> anyhow::Result<WindowHandle<Root>> {
traffic_light_position: None,
}
};
- cx.open_window(
+ let handle = cx.open_window(
WindowOptions {
titlebar: Some(titlebar),
- window_bounds: Some(WindowBounds::Windowed(bounds)),
+ window_bounds: Some(window_bounds),
+ display_id,
window_min_size: Some(size(px(940.), px(620.))),
// Linux 桌面按它归组窗口、匹配 .desktop(StartupWMClass=wake)
app_id: Some("wake".into()),
@@ -78,86 +95,243 @@ fn open_main_window(cx: &mut App) -> anyhow::Result<WindowHandle<Root>> {
let workbench = cx.new(|cx| Workbench::new(window, cx));
window.focus(&workbench.read(cx).focus_handle(cx), cx);
- cx.new(|cx| Root::new(workbench, window, cx))
+ cx.new(|cx| {
+ main_window::track(window, cx);
+ Root::new(workbench, window, cx)
+ })
},
- )
+ )?;
+ cx.set_global(MainWindow(handle));
+ Ok(handle)
}
-fn main() {
- let app = gpui_platform::application().with_assets(Assets);
- // macOS:用户关掉最后一个窗后进程仍留 Dock,点 Dock 图标走 NSApplication 的
- // applicationShouldHandleReopen → gpui Platform::on_reopen。空窗重建、
- // 有窗只是把已存在的拉到前台,不重复实例
- app.on_reopen(|cx| {
- if cx.windows().is_empty() {
- if let Err(e) = open_main_window(cx) {
- wake_core::services::terminal::show_fatal_alert(&format!(
- "Wake couldn't reopen its window: {e}"
- ));
- std::process::exit(1);
- }
+/// 开窗失败必须自己报:release 的 Windows 子系统没有 stderr,panic 消息无处
+/// 可去,用户看到的就是任务栏闪一下然后什么都没有(GPU/驱动起不来、RDP 会话
+/// 等都会走到这)。show_fatal_alert 会弹系统对话框,并始终先往 stderr 落一份
+///(2026-08-25 review)。`what` 是 "open"/"reopen",拼进提示语
+fn open_main_window_or_exit(cx: &mut App, what: &str) -> WindowHandle<Root> {
+ match open_main_window(cx) {
+ Ok(handle) => handle,
+ Err(e) => {
+ wake_core::services::terminal::show_fatal_alert(&format!(
+ "Wake couldn't {what} its window: {e}"
+ ));
+ std::process::exit(1);
}
+ }
+}
+
+/// 主窗还在就拉到前台并交出它的 Workbench;窗已关(update 失败)给 None。
+/// 必须在没有窗口被借出时调用——defer 里,或刚开完窗
+fn activate_main(handle: WindowHandle<Root>, cx: &mut App) -> Option<Entity<Workbench>> {
+ handle
+ .update(cx, |root, window, _| {
+ window.activate_window();
+ root.view().clone().downcast::<Workbench>().ok()
+ })
+ .ok()
+ .flatten()
+}
+
+/// 主窗还在就拉到前台,否则重建;随后在主窗的 Workbench 上执行 `then`(无窗时
+/// 菜单里点 Settings/About 就靠它转发)。整段推迟到下一轮前台任务里跑,两个
+/// 原因:①全局 action 监听器是在派发它的那扇窗口的 update 期间被调用的,此刻
+/// 该窗口已被借出,再 update 它必失败(gpui 不重入)——同步判断会把活着的主窗
+/// 误判成已关;②不能用 `cx.defer`:Dock 的 `on_reopen` 回调是裸 `borrow_mut`,
+/// 不在任何 `App::update` 里,defer 压进队列后没人 flush,无窗又无任务时会
+/// 一直挂着(2026-09-02 Codex review)。前台任务经 `AsyncApp::update` 执行,
+/// 那条路必然 flush,内层的 defer 也在同一轮里处理
+fn show_main_window(
+ cx: &mut App,
+ then: impl FnOnce(&mut Workbench, &mut Context<Workbench>) + 'static,
+) {
+ cx.spawn(async move |cx| {
+ cx.update(|cx| show_main_window_now(cx, then));
+ })
+ .detach();
+}
+
+/// `show_main_window` 的正文。要在 `App::update` 里、且没有窗口被借出时调用
+fn show_main_window_now(
+ cx: &mut App,
+ then: impl FnOnce(&mut Workbench, &mut Context<Workbench>) + 'static,
+) {
+ let handle = cx.try_global::<MainWindow>().map(|main| main.0);
+ if let Some(workbench) = handle.and_then(|handle| activate_main(handle, cx)) {
+ cx.activate(true);
+ workbench.update(cx, then);
+ return;
+ }
+ // 主窗已关。Settings 允许比主窗活得久(它持有 Workbench,事件泵跟
+ // entity 走),但那个 Workbench 的 list/input 订阅都绑在旧主窗上,挂进
+ // 新窗不会再收事件——所以设计上是:先关掉 Settings 让旧 Workbench
+ // 释放(watcher 随之 join),再建全新的主窗。开窗放到下一个 defer:
+ // 释放发生在两次 defer 之间的 release 阶段,同一轮里建会让新旧
+ // watcher 并存
+ for w in cx.windows() {
+ w.update(cx, |_, window, _| window.remove_window()).ok();
+ }
+ cx.defer(move |cx| {
+ let handle = open_main_window_or_exit(cx, "reopen");
cx.activate(true);
+ if let Some(workbench) = activate_main(handle, cx) {
+ workbench.update(cx, then);
+ }
+ });
+}
+
+/// 窗口级操作(关/最小化/缩放/全屏)从全局监听器发起时,目标窗口正处在派发
+/// 这个 action 的 update 中(键位与菜单两条路都如此),被借出的窗口不能再次
+/// update——返回 Err 被 .ok() 吞掉就是"⌘W 没反应"。推迟到本轮 update 结束再动
+fn with_active_window(cx: &mut App, f: impl FnOnce(&mut Window) + 'static) {
+ let Some(w) = cx.active_window() else {
+ return;
+ };
+ cx.defer(move |cx| {
+ w.update(cx, |_, window, _| f(window)).ok();
+ });
+}
+
+fn key_bindings() -> Vec<KeyBinding> {
+ // secondary = macOS 的 cmd、其他平台的 ctrl(gpui keystroke 内建别名)。
+ // macOS 标准的应用/窗口键位 gpui 不会自动处理,没有绑定就是死键;
+ // Linux/Windows 上 ctrl-h/ctrl-m 另有含义,不绑
+ let mut keys = vec![
+ KeyBinding::new(ui::SEARCH_KEYSTROKE, ToggleSearch, Some(KEY_CONTEXT)),
+ KeyBinding::new("secondary-r", RefreshSessions, Some(KEY_CONTEXT)),
+ KeyBinding::new("secondary-,", OpenSettings, None),
+ KeyBinding::new("secondary-q", Quit, None),
+ KeyBinding::new("secondary-w", CloseWindow, None),
+ // ⌘K 面板:焦点在搜索输入框,↑↓ 冒泡到面板容器挪选中
+ KeyBinding::new("up", PaletteUp, Some(PALETTE_CONTEXT)),
+ KeyBinding::new("down", PaletteDown, Some(PALETTE_CONTEXT)),
+ ];
+ if cfg!(target_os = "macos") {
+ keys.extend([
+ KeyBinding::new("secondary-h", Hide, None),
+ KeyBinding::new("secondary-alt-h", HideOthers, None),
+ KeyBinding::new("secondary-m", Minimize, None),
+ KeyBinding::new("ctrl-secondary-f", ToggleFullScreen, None),
+ ]);
+ }
+ keys
+}
+
+/// 菜单栏。gpui 只按这里给的生成,不补任何标准项——Edit/Window/Hide 一族在
+/// macOS 上必须自己给,否则对应快捷键全是死键
+fn app_menus() -> Vec<Menu> {
+ let mac = cfg!(target_os = "macos");
+ let wake: Vec<MenuItem> = [
+ Some(MenuItem::action("About Wake", OpenAbout)),
+ mac.then(|| MenuItem::action("Check for Updates…", OpenUpdates)),
+ Some(MenuItem::separator()),
+ Some(MenuItem::action("Settings…", OpenSettings)),
+ Some(MenuItem::separator()),
+ mac.then(|| MenuItem::action("Hide Wake", Hide)),
+ mac.then(|| MenuItem::action("Hide Others", HideOthers)),
+ mac.then(|| MenuItem::action("Show All", ShowAll)),
+ mac.then(MenuItem::separator),
+ Some(MenuItem::action("Quit Wake", Quit)),
+ ]
+ .into_iter()
+ .flatten()
+ .collect();
+ let file = vec![
+ MenuItem::action("Refresh Sessions", RefreshSessions),
+ MenuItem::separator(),
+ MenuItem::action("Close Window", CloseWindow),
+ ];
+ // os_action:菜单项挂原生 cut:/copy:/paste:/selectAll: 选择器。gpui 窗口
+ // 在前时由 gpui 接住、派发成右侧的 action(输入框消费);系统面板(目录
+ // 选择器)在前时走原生响应链——没有这组菜单项,面板里的 ⌘C/⌘V 无人应答
+ let edit = mac.then(|| Menu {
+ name: "Edit".into(),
+ items: vec![
+ MenuItem::os_action("Undo", gpui_component::input::Undo, OsAction::Undo),
+ MenuItem::os_action("Redo", gpui_component::input::Redo, OsAction::Redo),
+ MenuItem::separator(),
+ MenuItem::os_action("Cut", gpui_component::input::Cut, OsAction::Cut),
+ MenuItem::os_action("Copy", gpui_component::input::Copy, OsAction::Copy),
+ MenuItem::os_action("Paste", gpui_component::input::Paste, OsAction::Paste),
+ MenuItem::os_action(
+ "Select All",
+ gpui_component::input::SelectAll,
+ OsAction::SelectAll,
+ ),
+ ],
+ disabled: false,
+ });
+ // 名字必须是 "Window":gpui 据此把它登记为系统 windows menu,窗口列表由
+ // AppKit 自动追加在后面。只剩 Settings 时 Dock 点击不会触发 on_reopen
+ //(系统认为还有可见窗口),Main Window 是拉回主窗的唯一入口
+ let window = mac.then(|| Menu {
+ name: "Window".into(),
+ items: vec![
+ MenuItem::action("Minimize", Minimize),
+ MenuItem::action("Zoom", Zoom),
+ MenuItem::action("Toggle Full Screen", ToggleFullScreen),
+ MenuItem::separator(),
+ MenuItem::action("Main Window", ShowMainWindow),
+ ],
+ disabled: false,
});
+ [
+ Some(Menu {
+ name: "Wake".into(),
+ items: wake,
+ disabled: false,
+ }),
+ Some(Menu {
+ name: "File".into(),
+ items: file,
+ disabled: false,
+ }),
+ edit,
+ window,
+ ]
+ .into_iter()
+ .flatten()
+ .collect()
+}
+
+fn main() {
+ let app = gpui_platform::application().with_assets(Assets);
+ // macOS:用户关掉最后一个窗后进程仍留 Dock,点 Dock 图标走 NSApplication 的
+ // applicationShouldHandleReopen → gpui Platform::on_reopen(只在系统认为
+ // 没有可见窗口时触发)。与 Window → Main Window 同一条路
+ app.on_reopen(|cx| show_main_window(cx, |_, _| {}));
app.run(move |cx: &mut App| {
gpui_component::init(cx);
gpui_component::set_locale("en");
theme::sync_appearance(None, cx);
cx.on_action(|_: &Quit, cx| cx.quit());
- cx.on_action(|_: &CloseWindow, cx| {
- if let Some(w) = cx.active_window() {
- w.update(cx, |_, window, _| window.remove_window()).ok();
- }
- });
- // secondary = macOS 的 cmd、其他平台的 ctrl(gpui keystroke 内建别名)
- cx.bind_keys([
- KeyBinding::new(ui::SEARCH_KEYSTROKE, ToggleSearch, Some(KEY_CONTEXT)),
- KeyBinding::new("secondary-r", RefreshSessions, Some(KEY_CONTEXT)),
- KeyBinding::new("secondary-,", OpenSettings, None),
- KeyBinding::new("secondary-q", Quit, None),
- KeyBinding::new("secondary-w", CloseWindow, None),
- // ⌘K 面板:焦点在搜索输入框,↑↓ 冒泡到面板容器挪选中
- KeyBinding::new("up", PaletteUp, Some(PALETTE_CONTEXT)),
- KeyBinding::new("down", PaletteDown, Some(PALETTE_CONTEXT)),
- ]);
- let mut wake_menu_items = vec![MenuItem::action("About Wake", OpenAbout)];
- #[cfg(target_os = "macos")]
- wake_menu_items.push(MenuItem::action("Check for Updates…", OpenUpdates));
- wake_menu_items.extend([
- MenuItem::separator(),
- MenuItem::action("Settings…", OpenSettings),
- MenuItem::separator(),
- MenuItem::action("Quit Wake", Quit),
- ]);
- cx.set_menus(vec![
- Menu {
- name: "Wake".into(),
- items: wake_menu_items,
- disabled: false,
- },
- Menu {
- name: "File".into(),
- items: vec![
- MenuItem::action("Refresh Sessions", RefreshSessions),
- MenuItem::separator(),
- MenuItem::action("Close Window", CloseWindow),
- ],
- disabled: false,
- },
- ]);
+ // 退出前把主窗几何落盘(节流写盘可能还没触发);Dock 的 Quit、注销关机
+ // 都走这里,不只 ⌘Q
+ cx.on_app_quit(|cx| {
+ main_window::flush(cx);
+ 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(|_: &Hide, cx| cx.hide());
+ cx.on_action(|_: &HideOthers, cx| cx.hide_other_apps());
+ cx.on_action(|_: &ShowAll, cx| cx.unhide_other_apps());
+ cx.on_action(|_: &ShowMainWindow, cx| show_main_window(cx, |_, _| {}));
+ // 无窗时的菜单兜底:有窗时这些 action 由 Workbench/Settings 的视图
+ // 消费(元素级监听器默认截断传播,不会走到这);全部窗口关掉后菜单项
+ // 只认全局监听器,没有就置灰——先把主窗拉回来再转发
+ cx.on_action(|_: &OpenSettings, cx| show_main_window(cx, Workbench::open_settings));
+ cx.on_action(|_: &OpenAbout, cx| show_main_window(cx, Workbench::open_about));
+ cx.on_action(|_: &OpenUpdates, cx| show_main_window(cx, Workbench::open_updates));
- let window = open_main_window(cx);
- // 开窗失败必须自己报:release 的 Windows 子系统没有 stderr,panic
- // 消息无处可去,用户看到的就是任务栏闪一下然后什么都没有
- //(GPU/驱动起不来、RDP 会话等都会走到这)。show_fatal_alert 会弹
- // 系统对话框,并始终先往 stderr 落一份(2026-08-25 review)
- if let Err(e) = window {
- wake_core::services::terminal::show_fatal_alert(&format!(
- "Wake couldn't open its window: {e}"
- ));
- std::process::exit(1);
- }
+ cx.bind_keys(key_bindings());
+ cx.set_menus(app_menus());
+
+ open_main_window_or_exit(cx, "open");
cx.activate(true);
});
}
diff --git a/crates/wake/src/main_window.rs b/crates/wake/src/main_window.rs
new file mode 100644
index 0000000..fe41793
--- /dev/null
+++ b/crates/wake/src/main_window.rs
@@ -0,0 +1,265 @@
+//! 主窗口:句柄登记,以及几何的记忆与恢复(哪块屏、屏内位置、全屏/最大化)。
+//!
+//! 坐标约定(2026-09-02 双屏反馈定稿):macOS 上 gpui 的 `window.bounds()` 与开窗
+//! 的 `window_bounds` 都是**所在屏幕内的相对坐标**,屏幕由 `WindowOptions.display_id`
+//! 选定、留空落主屏;`PlatformDisplay::bounds()`/`visible_bounds()` 同样以屏幕
+//! 自身为原点。Windows/X11 上这几个 API 给的则是虚拟桌面的**全局坐标**,显示器
+//! 原点非零。所以落盘的是(屏幕 uuid,减去该屏原点后的相对 bounds):macOS 上
+//! 减零等于无操作,Windows 上显示器换了主屏或挪了位置时 uuid 仍命中、相对位置
+//! 照样恢复(Codex review)。开任何窗都要把目标屏的 display_id 一起传——只算
+//! 坐标不传屏幕,就是"设置窗跑到主屏"那个 bug。
+//!
+//! 两个平台差异(2026-09-02 Codex review):①落盘取 `inner_window_bounds()` 而非
+//! `window_bounds()`——Wayland/X11 客户端装饰下后者含 gpui-component 加的 20px 阴影
+//! inset,原样开窗会被 `set_client_inset` 再加一层,每次重启长 40px(Zed #22301 同病);
+//! macOS/Windows 两者相同。②macOS 后端从不报 `WindowBounds::Maximized`,Zoom 后仍是
+//! `Windowed` + 铺满可见区的 frame,要用 `is_maximized()` 补判,并且最大化/全屏时
+//! 保住上一次 windowed 的 bounds 落盘,恢复时先按它开窗再放大/全屏(gpui 开窗后自动
+//! 调 zoom/toggle_fullscreen),退出时才回得到原尺寸。
+use crate::prefs;
+use gpui::*;
+use gpui_component::Root;
+use serde::{Deserialize, Serialize};
+use std::time::Duration;
+
+/// 首次启动的主窗尺寸
+const MAIN_SIZE: Size<Pixels> = size(px(1180.), px(760.));
+
+/// 主窗句柄。无窗时的菜单兜底与 Window → Main Window 据此找主窗,从属窗口
+/// 据此取主窗几何
+pub struct MainWindow(pub WindowHandle<Root>);
+impl Global for MainWindow {}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
+enum Mode {
+ #[default]
+ Windowed,
+ Maximized,
+ Fullscreen,
+}
+
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+struct SavedWindow {
+ /// 屏内相对坐标;最大化/全屏时存的是进入前的 windowed bounds,恢复时先按它
+ /// 开窗再放大/切全屏,退出也回到原位
+ bounds: Bounds<Pixels>,
+ #[serde(default)]
+ mode: Mode,
+ /// `PlatformDisplay::uuid()`,跨重启稳定;None = 拿不到,恢复时落主屏
+ #[serde(default)]
+ display: Option<String>,
+}
+
+/// 进程内快照与落盘状态。关窗后 Dock/菜单重开、退出时落盘都读快照,不依赖
+/// 节流写盘是否已经落地
+#[derive(Default)]
+struct MainGeometry {
+ /// 已提交的快照;`bounds` 是 windowed 尺寸,最大化/全屏期间保持不变
+ saved: SavedWindow,
+ /// windowed 模式下最近一次事件的 frame,等节流任务到期、模式仍是 windowed 才提交成
+ /// `saved.bounds`。Zoom/全屏的入场动画每帧都按 windowed 报上来(尺寸还没铺满,
+ /// `is_maximized()` 尚为假),直接提交会把"差一点铺满"的中间帧当成恢复尺寸;
+ /// 延迟到到期时它已被最终的 Maximized/Fullscreen 盖掉(Codex review)
+ live: Option<Bounds<Pixels>>,
+ /// 节流落盘任务:在队 ⇔ 快照有未落盘的变化;在队就不再起新的,触发时读最新快照
+ save_task: Option<Task<()>>,
+}
+impl Global for MainGeometry {}
+
+impl MainGeometry {
+ /// 待提交的 windowed frame 并进快照后的样子
+ fn snapshot(&self) -> SavedWindow {
+ let mut saved = self.saved.clone();
+ if saved.mode == Mode::Windowed {
+ if let Some(live) = self.live {
+ saved.bounds = live;
+ }
+ }
+ saved
+ }
+
+ fn commit(&mut self) {
+ self.saved = self.snapshot();
+ self.live = None;
+ }
+}
+
+fn split(window_bounds: WindowBounds) -> (Bounds<Pixels>, Mode) {
+ match window_bounds {
+ WindowBounds::Windowed(b) => (b, Mode::Windowed),
+ WindowBounds::Maximized(b) => (b, Mode::Maximized),
+ WindowBounds::Fullscreen(b) => (b, Mode::Fullscreen),
+ }
+}
+
+/// 挂到主窗上:移动/缩放/全屏都更新快照并节流落盘。观察器按窗口登记,只挂主窗
+pub fn track(window: &mut Window, cx: &mut Context<Root>) {
+ // 开窗即记一次:启动后不挪窗直接 Zoom、或以 Maximized 启动由 gpui 自动 zoom 时,
+ // 最终那次回调才有"进 Zoom 前的尺寸"可保
+ observe(window, cx);
+ cx.observe_window_bounds(window, |_, window, cx| observe(window, cx))
+ .detach();
+}
+
+fn observe(window: &Window, cx: &mut App) {
+ // inner_window_bounds / is_maximized 的取舍见模块头
+ let (platform_bounds, platform_mode) = split(window.inner_window_bounds());
+ let mode = match platform_mode {
+ Mode::Windowed if window.is_maximized() => Mode::Maximized,
+ mode => mode,
+ };
+ let display = window.display(cx);
+ let uuid = display
+ .as_ref()
+ .and_then(|d| d.uuid().ok())
+ .map(|u| u.to_string());
+ // 落盘的是相对所在屏幕原点的坐标(见模块头)
+ let origin = display.map(|d| d.bounds().origin).unwrap_or_default();
+ let platform_bounds = platform_bounds - origin;
+ if !cx.has_global::<MainGeometry>() {
+ // 首次(开窗时 track 主动调的那次):直接成为快照,不排落盘——磁盘上就是刚恢复
+ // 出来的那份
+ cx.set_global(MainGeometry {
+ saved: SavedWindow {
+ bounds: platform_bounds,
+ mode,
+ display: uuid,
+ },
+ ..Default::default()
+ });
+ return;
+ }
+ let geometry = cx.global_mut::<MainGeometry>();
+ // 激活、换屏通知也会触发观察器,拖动时更是每帧一次:几何没变就什么都不做。
+ // 最大化/全屏时各平台给的 bounds 不一(macOS Zoom 给的是铺满后的 frame,X11 给的
+ // 是当前 bounds),一律不看,只认模式与屏幕
+ let unchanged = mode == geometry.saved.mode
+ && uuid == geometry.saved.display
+ && match mode {
+ Mode::Windowed => geometry
+ .live
+ .map_or(geometry.saved.bounds == platform_bounds, |live| {
+ live == platform_bounds
+ }),
+ _ => true,
+ };
+ if unchanged {
+ return;
+ }
+ geometry.saved.mode = mode;
+ geometry.saved.display = uuid;
+ if mode == Mode::Windowed {
+ geometry.live = Some(platform_bounds);
+ }
+ schedule_save(cx);
+}
+
+/// 一次移动只排一个任务:500ms 后写当时最新的快照,期间的事件只改快照
+fn schedule_save(cx: &mut App) {
+ if cx.global::<MainGeometry>().save_task.is_some() {
+ return;
+ }
+ let task = cx.spawn(async move |cx| {
+ cx.background_executor()
+ .timer(Duration::from_millis(500))
+ .await;
+ cx.update(flush);
+ });
+ cx.global_mut::<MainGeometry>().save_task = Some(task);
+}
+
+/// 有排队中的落盘任务才写(排队 ⇔ 快照有未落盘的变化):先提交待定的 windowed frame,
+/// 写完即出队。节流任务与退出前(on_app_quit)都走这里
+pub fn flush(cx: &mut App) {
+ if !cx.has_global::<MainGeometry>() {
+ return;
+ }
+ let geometry = cx.global_mut::<MainGeometry>();
+ if geometry.save_task.take().is_none() {
+ return;
+ }
+ geometry.commit();
+ if let Err(e) = save(&geometry.saved) {
+ eprintln!("failed to save window geometry: {e}");
+ }
+}
+
+fn load() -> Option<SavedWindow> {
+ let text = std::fs::read_to_string(prefs::path("window.json")).ok()?;
+ serde_json::from_str(&text).ok()
+}
+
+fn save(saved: &SavedWindow) -> std::io::Result<()> {
+ let bytes = serde_json::to_vec_pretty(saved).map_err(std::io::Error::other)?;
+ prefs::write(&prefs::path("window.json"), &bytes)
+}
+
+/// 把窗口夹进屏幕范围:尺寸先按屏幕封顶,再把原点限制在屏内
+fn fit_in(mut bounds: Bounds<Pixels>, screen: Bounds<Pixels>) -> Bounds<Pixels> {
+ bounds.size = bounds.size.min(&screen.size);
+ let max_origin = point(
+ screen.origin.x + screen.size.width - bounds.size.width,
+ screen.origin.y + screen.size.height - bounds.size.height,
+ );
+ bounds.origin = bounds.origin.clamp(&screen.origin, &max_origin);
+ bounds
+}
+
+/// 开主窗的参数:进程内快照(本次会话刚关掉的位置)> 上次落盘 > 主屏居中。
+/// 返回的 bounds 是所选屏幕内的相对坐标,必须与 display_id 一起交给 open_window。
+/// 按 uuid 找不回屏幕(显示器拔了)退回主屏;一律夹进可见区,换过分辨率也不会
+/// 开到屏外或压住 Dock
+pub fn restore(cx: &App) -> (WindowBounds, Option<DisplayId>) {
+ let fallback = || (WindowBounds::centered(MAIN_SIZE, cx), None);
+ let saved = cx.try_global::<MainGeometry>().map(MainGeometry::snapshot);
+ let Some(saved) = saved.or_else(load) else {
+ return fallback();
+ };
+ let display = saved
+ .display
+ .as_deref()
+ .and_then(|uuid| {
+ cx.displays()
+ .into_iter()
+ .find(|d| d.uuid().is_ok_and(|u| u.to_string() == uuid))
+ })
+ .or_else(|| cx.primary_display());
+ let Some(display) = display else {
+ return fallback();
+ };
+ // 相对坐标加回当前这块屏的原点,再夹进它的可见区
+ let bounds = fit_in(
+ saved.bounds + display.bounds().origin,
+ display.visible_bounds(),
+ );
+ let window_bounds = match saved.mode {
+ Mode::Windowed => WindowBounds::Windowed(bounds),
+ Mode::Maximized => WindowBounds::Maximized(bounds),
+ Mode::Fullscreen => WindowBounds::Fullscreen(bounds),
+ };
+ (window_bounds, Some(display.id()))
+}
+
+/// 从属窗口(Settings)的开窗参数:开在主窗所在屏幕、居中压在主窗上、夹进
+/// 可见区。主窗不在(理论上只有开窗失败)退回主屏居中。要在没有窗口被借出时
+/// 调用(defer 里)
+pub fn centered_over_main(size: Size<Pixels>, cx: &mut App) -> (Bounds<Pixels>, Option<DisplayId>) {
+ let anchor = cx
+ .try_global::<MainWindow>()
+ .map(|main| main.0)
+ .and_then(|handle| {
+ handle
+ .update(cx, |_, window, cx| (window.bounds(), window.display(cx)))
+ .ok()
+ });
+ match anchor {
+ Some((main, display)) => {
+ let mut bounds = Bounds::centered_at(main.center(), size);
+ if let Some(display) = &display {
+ bounds = fit_in(bounds, display.visible_bounds());
+ }
+ (bounds, display.map(|d| d.id()))
+ }
+ None => (Bounds::centered(None, size, cx), None),
+ }
+}
diff --git a/crates/wake/src/prefs.rs b/crates/wake/src/prefs.rs
new file mode 100644
index 0000000..d110a7a
--- /dev/null
+++ b/crates/wake/src/prefs.rs
@@ -0,0 +1,22 @@
+//! 不走 Store 的偏好文件:外观在开窗前就要读,主窗几何在 Workbench(与它的
+//! Store)建立之前就要用,都等不了库。统一目录、统一原子写法
+use std::path::{Path, PathBuf};
+
+/// `<config dir>/wake/<name>`
+pub fn path(name: &str) -> PathBuf {
+ dirs::config_dir()
+ .or_else(dirs::data_dir)
+ .unwrap_or_else(|| PathBuf::from("."))
+ .join("wake")
+ .join(name)
+}
+
+/// 建目录、先写临时文件再 rename——半截文件不会被下次启动读成坏内容
+pub fn write(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
+ if let Some(dir) = path.parent() {
+ std::fs::create_dir_all(dir)?;
+ }
+ let tmp = path.with_extension("tmp");
+ std::fs::write(&tmp, bytes)?;
+ std::fs::rename(tmp, path)
+}
diff --git a/crates/wake/src/settings.rs b/crates/wake/src/settings.rs
index eba2e99..df59b91 100644
--- a/crates/wake/src/settings.rs
+++ b/crates/wake/src/settings.rs
@@ -4,15 +4,16 @@ use gpui_component::button::{Button, ButtonCustomVariant, ButtonVariants as _};
use gpui_component::menu::{DropdownMenu as _, PopupMenuItem};
use gpui_component::switch::Switch;
use gpui_component::{
- h_flex, v_flex, ActiveTheme as _, Disableable as _, Icon, Root, Selectable as _, Sizable as _,
+ h_flex, v_flex, ActiveTheme as _, Disableable as _, Icon, Selectable as _, Sizable as _,
StyledExt as _, TitleBar, WindowExt as _,
};
use wake_core::models::AgentId;
use crate::ui::{
- BUTTON_SM_H, FONT_BODY, FONT_CAPTION, FONT_DISPLAY, FONT_HEADING, FONT_LABEL, FONT_TITLE,
- RADIUS_BUTTON, SHOW_IN_FM, SPACE_LG, SPACE_MD, SPACE_SM, SPACE_XL, SPACE_XS, SPACE_XXL,
+ overlay_layers, BUTTON_SM_H, FONT_BODY, FONT_CAPTION, FONT_DISPLAY, FONT_HEADING, FONT_LABEL,
+ FONT_TITLE, RADIUS_BUTTON, SHOW_IN_FM, SPACE_LG, SPACE_MD, SPACE_SM, SPACE_XL, SPACE_XS,
+ SPACE_XXL,
};
use crate::update::{self, UpdateStatus};
use crate::workbench::{DataSourceRow, OpenAbout, OpenSettings, OpenUpdates, Workbench};
@@ -1030,7 +1031,6 @@ impl Render for SettingsView {
.bg(background)
.text_color(foreground)
.child(h_flex().size_full().child(sidebar).child(content))
- .children(Root::render_dialog_layer(window, cx))
- .children(Root::render_notification_layer(window, cx))
+ .children(overlay_layers(window, cx))
}
}
diff --git a/crates/wake/src/theme.rs b/crates/wake/src/theme.rs
index 3668ee4..564c385 100644
--- a/crates/wake/src/theme.rs
+++ b/crates/wake/src/theme.rs
@@ -29,10 +29,7 @@ impl AppearancePreference {
}
fn appearance_path() -> std::path::PathBuf {
- let base = dirs::config_dir()
- .or_else(dirs::data_dir)
- .unwrap_or_else(|| std::path::PathBuf::from("."));
- base.join("wake").join("appearance")
+ crate::prefs::path("appearance")
}
pub fn appearance_preference() -> AppearancePreference {
@@ -56,11 +53,7 @@ pub fn set_appearance(
window: Option<&mut Window>,
cx: &mut App,
) -> std::io::Result<()> {
- let path = appearance_path();
- if let Some(parent) = path.parent() {
- std::fs::create_dir_all(parent)?;
- }
- std::fs::write(path, preference.as_str())?;
+ crate::prefs::write(&appearance_path(), preference.as_str().as_bytes())?;
apply_appearance(preference, window, cx);
Ok(())
}
diff --git a/crates/wake/src/ui.rs b/crates/wake/src/ui.rs
index a853804..f1ecf17 100644
--- a/crates/wake/src/ui.rs
+++ b/crates/wake/src/ui.rs
@@ -2,7 +2,13 @@
//! 规则:所有 UI 字号必须引用本模块常量,禁止裸 px 数字与 rem 工具类
//! (text_sm 等按 rem=14px 折算会产生 12.25px 这类幽灵值)。
//! 颜色只用三级:foreground(主文字)/muted_foreground(辅助)/primary(强调)。
-use gpui::{px, Hsla, Pixels, Styled};
+use std::collections::HashSet;
+
+use gpui::{
+ div, px, AnyElement, App, Global, Hsla, InteractiveElement as _, IntoElement, MouseButton,
+ Pixels, Styled, Window, WindowId,
+};
+use gpui_component::{dialog::Dialog, Root, WindowExt as _};
/// 产品展示名(About)——medium
pub const FONT_DISPLAY: Pixels = px(28.);
@@ -172,3 +178,70 @@ pub trait TextColored: Styled + Sized {
}
impl<T: Styled + Sized> TextColored for T {}
+
+/// Wake 主窗口的透明标题栏高度。28px 详情操作条上下各保留 8px。
+pub const WINDOW_TITLEBAR_HEIGHT: Pixels = px(44.);
+
+// ---- 弹窗「点面板外关闭」补丁 ----
+//
+// gpui-component fd3bc2b 的 Dialog 把遮罩点击监听器挂在一个零高度的包装 div 上,永远
+// hover 不到,`overlay_closable` 形同虚设(上游 df1d07b2「Restore the overlay behind an
+// open dialog」已修;升级到含修复的版本后删掉本段,两个入口退化成 `window.open_dialog`
+// 与 Root 的两层 overlay)。
+//
+// 原理:在窗口根节点、`Root::render_dialog_layer` 之后再挂一层全窗透明 sentinel。dialog
+// 的宿主是 deferred、最后才画:遮罩是普通 hitbox 不挡鼠标,popup 是 occlude——于是鼠标
+// 落在 popup 之外时 sentinel 才 hovered,它的 mouse_down 就是「点在面板外」。该不该关由
+// 弹窗表态:经 `open_closable_dialog` 打开的弹窗每帧在 builder 里登记本窗口,
+// `overlay_layers` 渲染完 dialog 层(builder 就在里面跑)立刻消费这个登记来决定挂不挂
+// sentinel——AlertDialog、已关闭的弹窗没有登记,面板外点击不关。不像上游那样豁免标题栏
+// 高度:弹窗开着时整窗被它的 occlude 层挡住、标题栏本来就拖不动,而弹窗顶边只在窗口高度
+// 1/10 处,豁免带会把「框外上方」整段吞掉(2026-09-02 用户实测)。
+
+/// 本帧登记过「可点面板外关闭」弹窗的窗口,`overlay_layers` 消费即清
+#[derive(Default)]
+struct ClosableDialogs(HashSet<WindowId>);
+impl Global for ClosableDialogs {}
+
+/// 打开可点面板外关闭的普通弹窗(确认类用 gpui-component 的 `open_alert_dialog`);
+/// Wake 里不要再裸调 `window.open_dialog`
+pub fn open_closable_dialog<F>(window: &mut Window, cx: &mut App, build: F)
+where
+ F: Fn(Dialog, &mut Window, &mut App) -> Dialog + 'static,
+{
+ window.open_dialog(cx, move |dialog, window, cx| {
+ let id = window.window_handle().window_id();
+ cx.default_global::<ClosableDialogs>().0.insert(id);
+ build(dialog, window, cx)
+ });
+}
+
+/// 窗口根节点内容之后的三层 overlay:dialog、notification、点面板外关闭的 sentinel,
+/// 顺序即契约(sentinel 必须在 dialog 层之后,才能盖在它的 occlude 层上面)
+pub fn overlay_layers(window: &mut Window, cx: &mut App) -> Vec<AnyElement> {
+ let dialogs = Root::render_dialog_layer(window, cx).map(IntoElement::into_any_element);
+ let notifications =
+ Root::render_notification_layer(window, cx).map(IntoElement::into_any_element);
+ let id = window.window_handle().window_id();
+ let sentinel = cx
+ .default_global::<ClosableDialogs>()
+ .0
+ .remove(&id)
+ .then(|| {
+ div()
+ .absolute()
+ .inset_0()
+ .on_any_mouse_down(|event, window, cx| {
+ if event.button != MouseButton::Left {
+ return;
+ }
+ cx.stop_propagation();
+ window.close_dialog(cx);
+ })
+ .into_any_element()
+ });
+ [dialogs, notifications, sentinel]
+ .into_iter()
+ .flatten()
+ .collect()
+}
diff --git a/crates/wake/src/workbench.rs b/crates/wake/src/workbench.rs
index a843602..72575a3 100644
--- a/crates/wake/src/workbench.rs
+++ b/crates/wake/src/workbench.rs
@@ -80,8 +80,6 @@ pub const PALETTE_CONTEXT: &str = "WakePalette";
const PALETTE_HEIGHT: Pixels = px(492.);
/// location 表单标签列宽(Agent/Folder 两行共用)
const FORM_LABEL_W: Pixels = px(52.);
-/// Wake 主窗口的透明标题栏高度。28px 详情操作条上下各保留 8px。
-const WINDOW_TITLEBAR_HEIGHT: Pixels = px(44.);
/// 左栏顶部由 44px 窗口控制区 + 44px 品牌行组成;中栏标题区共享总高度。
const LIBRARY_IDENTITY_HEIGHT: Pixels = px(88.);
/// 侧栏底部常态工具栏内容高;加上父容器 1px 顶部分隔线,总高 44px。
@@ -120,6 +118,8 @@ fn spawn_scan(
enum BgEvent {
Progress(ScanProgress),
Changed,
+ /// 监听后端丢过事件,需要一轮增量兜底
+ RescanNeeded,
}
struct ChannelEvents(futures::channel::mpsc::UnboundedSender<BgEvent>);
@@ -131,6 +131,9 @@ impl ScanEvents for ChannelEvents {
fn on_sessions_changed(&self) {
let _ = self.0.unbounded_send(BgEvent::Changed);
}
+ fn on_rescan_needed(&self) {
+ let _ = self.0.unbounded_send(BgEvent::RescanNeeded);
+ }
}
// ---------------- 会话列表 delegate ----------------
@@ -1643,6 +1646,103 @@ mod detail_selection_tests {
}
}
+ /// gpui-component fd3bc2b 的遮罩点击关闭是坏的,由 ui.rs 的 sentinel 补:经
+ /// open_closable_dialog 打开的弹窗面板内点不关、面板上方/下方点一下即关;裸
+ /// open_dialog 的(AlertDialog 一类没登记的)面板外点击不关
+ #[gpui::test]
+ fn dialog_closes_on_outside_click(cx: &mut TestAppContext) {
+ use crate::ui::{open_closable_dialog, overlay_layers};
+ use gpui_component::input::{Input, InputState};
+
+ struct Host;
+ impl Render for Host {
+ fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
+ div().size_full().children(overlay_layers(window, cx))
+ }
+ }
+ cx.update(|cx| {
+ gpui_component::init(cx);
+ // 入场动画一帧到位,不用按真实时钟等它落位
+ cx.set_reduce_motion(true);
+ });
+ let (_root, cx) = cx.add_window_view(|window, cx| {
+ let host = cx.new(|_| Host);
+ Root::new(host, window, cx)
+ });
+ let cx: &mut VisualTestContext = cx;
+ let draw = |cx: &mut VisualTestContext| {
+ cx.update(|w, cx| {
+ let _ = w.draw(cx);
+ });
+ cx.run_until_parked();
+ };
+ let click = |cx: &mut VisualTestContext, position| {
+ cx.simulate_click(position, Modifiers::default());
+ draw(cx);
+ };
+ let size = cx.update(|w, _| w.viewport_size());
+ // 面板居中、宽 400、顶边在视口高度 1/10 处
+ let inside = point(size.width / 2., size.height / 10. + px(60.));
+ // 面板上方(标题栏高度以内)与下方各取一点:上方曾被照抄上游的标题栏豁免吞掉
+ let above = point(px(20.), px(20.));
+ let below = point(px(20.), size.height - px(20.));
+
+ // 真实表单里有个会拿焦点的输入框,照样放一个
+ let input = cx.update(|window, cx| cx.new(|cx| InputState::new(window, cx)));
+ cx.update(|window, cx| {
+ open_closable_dialog(window, cx, move |dialog, _, _| {
+ dialog
+ .title("Probe")
+ .w(px(400.))
+ .child(div().h(px(120.)).child(Input::new(&input)))
+ });
+ });
+ draw(cx);
+ click(cx, inside);
+ click(cx, inside);
+ assert!(
+ cx.update(|w, cx| w.has_active_dialog(cx)),
+ "click inside the panel must not close the dialog"
+ );
+ click(cx, above);
+ assert!(
+ !cx.update(|w, cx| w.has_active_dialog(cx)),
+ "click above the panel must close the dialog"
+ );
+
+ cx.update(|window, cx| {
+ open_closable_dialog(window, cx, |dialog, _, _| {
+ dialog
+ .title("Probe")
+ .w(px(400.))
+ .child(div().h(px(120.)).child("body"))
+ });
+ });
+ draw(cx);
+ click(cx, below);
+ assert!(
+ !cx.update(|w, cx| w.has_active_dialog(cx)),
+ "click below the panel must close the dialog"
+ );
+
+ // 裸 open_dialog(AlertDialog 一类没登记的):面板外点击不关
+ cx.update(|window, cx| {
+ window.open_dialog(cx, |dialog, _, _| {
+ dialog
+ .title("Alert-like")
+ .w(px(400.))
+ .child(div().h(px(120.)).child("body"))
+ });
+ });
+ draw(cx);
+ click(cx, below);
+ assert!(
+ cx.update(|w, cx| w.has_active_dialog(cx)),
+ "an unregistered dialog must survive outside clicks"
+ );
+ cx.update(|window, cx| window.close_dialog(cx));
+ }
+
#[gpui::test]
#[allow(deprecated)]
fn window_selection_spans_text_views_inside_gpui_list(cx: &mut TestAppContext) {
@@ -2531,7 +2631,8 @@ impl Workbench {
}
workbench.update(cx, |this, _| this.settings_window = None);
}
- let bounds = Bounds::centered(None, size(px(820.), px(600.)), cx);
+ let (bounds, display_id) =
+ crate::main_window::centered_over_main(size(px(820.), px(600.)), cx);
let titlebar = if cfg!(target_os = "macos") {
TitlebarOptions {
title: None,
@@ -2551,6 +2652,7 @@ impl Workbench {
titlebar: Some(titlebar),
window_bounds: Some(WindowBounds::Windowed(bounds)),
window_min_size: Some(size(px(720.), px(520.))),
+ display_id,
app_id: Some("wake-settings".into()),
window_decorations: Some(WindowDecorations::Client),
..Default::default()
@@ -2679,7 +2781,7 @@ impl Workbench {
let entity = cx.entity();
let title: SharedString = title.into();
let ok_label: SharedString = ok_label.into();
- window.open_dialog(cx, move |dialog, _window, cx| {
+ open_closable_dialog(window, cx, move |dialog, _window, cx| {
let theme = cx.theme();
let dark = theme.mode.is_dark();
// 内容轴缩进 = small 按钮的水平内边距:字段行/标题/footer 以它为轴,
@@ -3255,6 +3357,12 @@ impl Workbench {
self.refresh(cx);
None
}
+ BgEvent::RescanNeeded => {
+ // 撞上进行中的扫描就排队,由终态事件补扫(kick_incremental_scan
+ // 自带这条状态机);连续多条 rescan 也只会排一次
+ self.kick_incremental_scan(cx);
+ None
+ }
}
}
@@ -3317,7 +3425,7 @@ impl Workbench {
let list = self.palette_list.clone();
let input = self.palette_input.clone();
let this = cx.entity();
- window.open_dialog(cx, move |dialog, window, cx| {
+ open_closable_dialog(window, cx, move |dialog, window, cx| {
let theme = cx.theme();
let has_query = input.read(cx).text().len() > 0;
// 输入框尺寸;清除钮的 suffix 补偿 margin 从它派生,改档自动跟随
@@ -3328,7 +3436,6 @@ impl Workbench {
// Dialog 默认内容 padding 24px 四边;水平 20,用户定稿(2026-08-18)
.px(SPACE_XL)
.close_button(false)
- .overlay_closable(true)
.child(
v_flex()
// ↑↓ 在 Input 内不被消费,冒泡到这里走 main.rs 的
@@ -3351,40 +3458,6 @@ impl Workbench {
// 不用手工重算列表高度
.h(PALETTE_HEIGHT)
.gap(SPACE_MD)
- .child(
- // gpui-component 0.5.1 的 Dialog 把遮罩关闭挂在冒泡
- // 阶段,而遮罩自身的 occlude 在当前 GPUI 版本会让该
- // 路径失效。用面板实际布局边界做窗口级捕获,确保任何
- // 面板外左键都能关闭;面板内输入、结果点击不受影响。
- canvas(
- |_, _, _| {},
- |content_bounds, _, window, _| {
- let dialog_bounds = Bounds {
- origin: point(
- content_bounds.origin.x - SPACE_XL,
- content_bounds.origin.y - px(24.),
- ),
- size: size(
- content_bounds.size.width + SPACE_XL * 2.,
- content_bounds.size.height + px(48.),
- ),
- };
- window.on_mouse_event(
- move |event: &MouseDownEvent, phase, window, cx| {
- if phase.capture()
- && event.button == MouseButton::Left
- && !dialog_bounds.contains(&event.position)
- {
- cx.stop_propagation();
- window.close_dialog(cx);
- }
- },
- );
- },
- )
- .absolute()
- .inset_0(),
- )
.child(
div()
.flex_shrink_0()
@@ -4970,7 +5043,7 @@ impl Workbench {
})
.on_click(close_button)
.child(
- icon("icons/x.svg")
+ icon("icons/close.svg")
.with_size(px(15.))
.text_color(gpui::white().opacity(0.86)),
),
@@ -5049,23 +5122,22 @@ impl Workbench {
} else {
bubble.px(px(14.)).py(SPACE_SM)
};
- if has_text || !shots.is_empty() {
- bubble = bubble.child(message_content(
- ix,
- m.seq,
- &m.text,
- &shots,
- FONT_MSG_USER,
- gpui::rems(0.5),
- dark,
- image_border,
- image_panel,
- image_muted,
- cx.entity(),
- window,
- cx,
- ));
- }
+ // 气泡靠内容撑宽,各段直接挂在气泡上、中间不加任何包装层
+ //(原因见 message_content 的文档注释)
+ bubble = bubble.children(message_content(
+ ix,
+ m.seq,
+ &m.text,
+ &shots,
+ FONT_MSG_USER,
+ gpui::rems(0.5),
+ dark,
+ image_border,
+ image_panel,
+ image_muted,
+ cx.entity(),
+ cx,
+ ));
h_flex()
.w_full()
.justify_end()
@@ -5089,26 +5161,30 @@ impl Workbench {
cx,
));
}
- if !m.text.is_empty() || !shots.is_empty() {
+ let parts = message_content(
+ ix,
+ m.seq,
+ &m.text,
+ &shots,
+ FONT_MSG_BODY,
+ gpui::rems(0.6),
+ dark,
+ image_border,
+ image_panel,
+ image_muted,
+ cx.entity(),
+ cx,
+ );
+ if !parts.is_empty() {
+ // 这一层只是正文的字号/行高作用域(thinking、工具簇各有自己的字阶,
+ // 不能提到 col 上);col 是 w_full 定宽列,不会走 max-content 探测,
+ // 与用户气泡"不加包装层"的约束不冲突
col = col.child(
- div()
+ v_flex()
+ .gap(SPACE_SM)
.text_size(FONT_MSG_BODY)
.line_height(relative(1.9))
- .child(message_content(
- ix,
- m.seq,
- &m.text,
- &shots,
- FONT_MSG_BODY,
- gpui::rems(0.6),
- dark,
- image_border,
- image_panel,
- image_muted,
- cx.entity(),
- window,
- cx,
- )),
+ .children(parts),
);
}
if !m.tool_calls.is_empty() {
@@ -6796,6 +6872,17 @@ fn zoom_shadow(y: Pixels, blur: Pixels, alpha: f32) -> gpui::BoxShadow {
}
}
+/// 把消息正文按图片插入点切成「markdown 段 / 图片条」序列,交给调用方的容器
+///(用户气泡 / 助手列)直接 `.children(..)` 承载,中间**不要加包装层**。
+///
+/// 已核实的机制:gpui 的 text 元素缓存上一次测量尺寸,之后凡是 wrap_width 为 None
+/// 的探测(MinContent/MaxContent)一律返回缓存值,不管那次是在多窄的定宽下量的
+///(gpui `elements/text.rs` 的缓存条件;上游只给 truncate 补了防中毒,wrap 没有)。
+/// 实测的触发点:靠内容撑宽的用户气泡(`max_w` 无 `w_full`)下再套一层
+/// `v_flex().min_w_0()` / `div().min_w_0()` 放 TextView,taffy 会先用 0 宽量文字,
+/// "一字一行"的尺寸进了缓存,气泡 max-content 宽度随之变 0,只剩 28px 内边距
+///(v0.3.5 回归,中英文都中招);各段直接挂在气泡上则中英文、图片、多段、代码块全正常。
+/// 上游若把该缓存改成按 wrap_width 分键,此约束即可解除。
#[allow(clippy::too_many_arguments)]
fn message_content(
message_index: usize,
@@ -6809,32 +6896,36 @@ fn message_content(
panel: Hsla,
muted: Hsla,
workbench: Entity<Workbench>,
- window: &mut Window,
cx: &mut App,
-) -> Div {
- let mut content = v_flex().min_w_0().gap(SPACE_SM);
+) -> Vec<AnyElement> {
+ let mut content = Vec::new();
let mut cursor = 0usize;
let mut image_index = 0usize;
- let mut text_part = 0usize;
- while image_index < slots.len() {
- let mut offset = slots[image_index].text_offset().min(text.len());
- while offset > cursor && !text.is_char_boundary(offset) {
- offset -= 1;
- }
- offset = offset.max(cursor);
+ // 每轮吃掉「下一组图片之前的文字」+ 该组图片;图片用尽后最后一轮吃掉尾段文字
+ loop {
+ let offset = slots
+ .get(image_index)
+ .map_or(text.len(), |slot| slot.text_offset().min(text.len()));
+ let offset = text.floor_char_boundary(offset).max(cursor);
let segment = text[cursor..offset].trim_matches('\n');
if !segment.trim().is_empty() {
- content = content.child(markdown_body(
- format!("dmsg-{seq}-part-{text_part}").into(),
- segment.to_string(),
- base,
- paragraph_gap,
- dark,
- window,
- cx,
- ));
- text_part += 1;
+ // 序号只要在本条消息内唯一且跨帧稳定即可,段数就够
+ let part = content.len();
+ content.push(
+ markdown_body(
+ format!("dmsg-{seq}-part-{part}").into(),
+ segment,
+ base,
+ paragraph_gap,
+ dark,
+ cx,
+ )
+ .into_any_element(),
+ );
+ }
+ if image_index >= slots.len() {
+ break;
}
let group_start = image_index;
@@ -6845,30 +6936,20 @@ fn message_content(
{
image_index += 1;
}
- content = content.child(image_strip(
- message_index,
- group_start,
- &slots[group_start..image_index],
- border,
- panel,
- muted,
- workbench.clone(),
- ));
+ content.push(
+ image_strip(
+ message_index,
+ group_start,
+ &slots[group_start..image_index],
+ border,
+ panel,
+ muted,
+ workbench.clone(),
+ )
+ .into_any_element(),
+ );
cursor = offset;
}
-
- let tail = text[cursor..].trim_matches('\n');
- if !tail.trim().is_empty() {
- content = content.child(markdown_body(
- format!("dmsg-{seq}-part-{text_part}").into(),
- tail.to_string(),
- base,
- paragraph_gap,
- dark,
- window,
- cx,
- ));
- }
content
}
@@ -7005,11 +7086,10 @@ fn centered_pill(text: impl Into<SharedString>, cx: &App) -> Div {
/// Wake 只覆写标题层级、代码块表面、语法配色和代码操作区。
fn markdown_body(
id: SharedString,
- text: String,
+ text: &str,
base: Pixels,
paragraph_gap: gpui::Rems,
dark: bool,
- _window: &mut Window,
cx: &mut App,
) -> TextView {
let theme = cx.theme();
@@ -7711,7 +7791,6 @@ impl Render for Workbench {
}),
)
.child(self.render_image_zoom(window, cx))
- .children(Root::render_dialog_layer(window, cx))
- .children(Root::render_notification_layer(window, cx))
+ .children(overlay_layers(window, cx))
}
}