Skip to content

DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.

feat: macOS accessory mode + configurable close-to-tray (Phase 01) (#238)

CoderStory89c8de17022f
diff --git a/src-tauri/src/bridge/config.rs b/src-tauri/src/bridge/config.rs
index d03bb92b..1e5471d0 100644
--- a/src-tauri/src/bridge/config.rs
+++ b/src-tauri/src/bridge/config.rs
@@ -60,12 +60,17 @@ pub async fn get_app_config(app_handle: AppHandle) -> Result<config::Setting, St
}
/// 更新桌面端配置
+///
+/// `close_action` 对应前端的 camelCase `closeAction`,命中关闭按钮时的行为
+/// (`tray` = 隐藏到托盘,`quit` = 退出应用);取值收敛由 `update_store_dat_setting`
+/// 内的 `normalize_close_action` 统一负责,此处不做二次校验以免白名单漂移。
#[tauri::command]
pub async fn update_app_config(
app_handle: AppHandle,
port: Option<u16>,
auto_start: Option<bool>,
cli_link_enabled: Option<bool>,
+ close_action: Option<String>,
) -> Result<config::Setting, String> {
if let Some(port) = port {
if port == 0 {
@@ -94,6 +99,9 @@ pub async fn update_app_config(
if let Some(enabled) = cli_link_enabled {
setting.cli_link_enabled = enabled;
}
+ if let Some(action) = close_action {
+ setting.close_action = action;
+ }
});
Ok(setting)
}
diff --git a/src-tauri/src/config/setting.rs b/src-tauri/src/config/setting.rs
index 56fb7561..e9ba9d25 100644
--- a/src-tauri/src/config/setting.rs
+++ b/src-tauri/src/config/setting.rs
@@ -1,7 +1,7 @@
use super::constants::*;
use serde::{Deserialize, Serialize};
use std::sync::{Mutex, OnceLock};
-use tauri::{AppHandle, Emitter};
+use tauri::{AppHandle, Emitter, Runtime};
use tauri_plugin_store::StoreExt;
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -50,6 +50,12 @@ pub struct Setting {
/// 归一化到受支持的 50%–200% 范围和 10% 步长。
#[serde(default = "default_zoom_factor")]
pub zoom_factor: f64,
+ /// 点击窗口关闭按钮时的行为:`tray` = 隐藏到托盘继续驻留,`quit` = 直接退出应用。
+ /// 只接受 `tray` / `quit` 两个字面量,读取与写入时均归一化,未知值回落 `tray`;
+ /// 字段刻意用 `String` 而非 enum——任一字段反序列化失败会让整个 `Setting` 回落
+ /// 默认,严格 enum 的一个意外值会连带清空端口/语言/档案等全部设置。
+ #[serde(default = "default_close_action")]
+ pub close_action: String,
}
pub const ZOOM_FACTOR_MIN: f64 = 0.5;
@@ -71,6 +77,22 @@ pub fn default_zoom_factor() -> f64 {
1.0
}
+/// 默认关闭行为:隐藏到托盘继续驻留(D-09)。
+pub fn default_close_action() -> String {
+ "tray".to_string()
+}
+
+/// 把外部或旧存储中的关闭行为收敛到白名单,未知值一律回落到默认行为。
+///
+/// 只做精确匹配:不做 `trim()`、不做大小写折叠——store 可被手工编辑、旧版本或其它
+/// 平台写入,宽松匹配会让 `"quit "` / `"TRAY"` 这类值以非预期形态进入下游判断。
+pub fn normalize_close_action(value: &str) -> String {
+ match value {
+ "tray" | "quit" => value.to_string(),
+ _ => default_close_action(),
+ }
+}
+
/// 将外部或旧存储中的缩放值限制到桌面端支持的稳定步长。
pub fn normalize_zoom_factor(value: f64) -> f64 {
if !value.is_finite() {
@@ -107,6 +129,7 @@ impl Default for Setting {
active_core: None,
manual_port: None,
zoom_factor: default_zoom_factor(),
+ close_action: default_close_action(),
}
}
}
@@ -130,7 +153,7 @@ fn setting_write_lock() -> &'static Mutex<()> {
LOCK.get_or_init(|| Mutex::new(()))
}
-fn read_store_dat_setting(app_handle: &AppHandle) -> Setting {
+fn read_store_dat_setting<R: Runtime>(app_handle: &AppHandle<R>) -> Setting {
let store = app_handle
.store(store_dat_file_name())
.expect("Failed to load store");
@@ -144,6 +167,7 @@ fn read_store_dat_setting(app_handle: &AppHandle) -> Setting {
.and_then(|v| serde_json::from_value(v).ok())
.unwrap_or_else(Setting::default);
setting.zoom_factor = normalize_zoom_factor(setting.zoom_factor);
+ setting.close_action = normalize_close_action(&setting.close_action);
setting
}
@@ -163,20 +187,21 @@ fn emit_setting(app_handle: &AppHandle, value: &serde_json::Value) {
.expect("Failed to emit event");
}
-fn preserve_persisted_zoom(mut replacement: Setting, persisted_zoom: f64) -> Setting {
- replacement.zoom_factor = normalize_zoom_factor(persisted_zoom);
+fn preserve_persisted_fields(mut replacement: Setting, current: &Setting) -> Setting {
+ replacement.zoom_factor = normalize_zoom_factor(current.zoom_factor);
+ replacement.close_action = normalize_close_action(&current.close_action);
replacement
}
-/// 兼容旧调用方的整对象写入,但始终保留锁内读到的最新缩放,避免长流程用陈旧
-/// `Setting` 覆盖刚刚由快捷键写入的值。
+/// 兼容旧调用方的整对象写入,但始终保留锁内读到的最新缩放与关窗动作,避免
+/// 长流程用陈旧 `Setting` 覆盖刚刚由快捷键 / 设置界面写入的值(丢更新)。
pub fn set_store_dat_setting(app_handle: &AppHandle, setting: Setting) {
let value = {
let _guard = setting_write_lock()
.lock()
.unwrap_or_else(|error| error.into_inner());
let current = read_store_dat_setting(app_handle);
- let setting = preserve_persisted_zoom(setting, current.zoom_factor);
+ let setting = preserve_persisted_fields(setting, &current);
write_store_dat_setting(app_handle, &setting)
};
emit_setting(app_handle, &value);
@@ -194,6 +219,8 @@ where
let mut setting = read_store_dat_setting(app_handle);
update(&mut setting);
setting.zoom_factor = normalize_zoom_factor(setting.zoom_factor);
+ // 落盘前的第二道闸:调用方(含前端 invoke)写入的不可信取值不以原始形态进 store
+ setting.close_action = normalize_close_action(&setting.close_action);
let value = write_store_dat_setting(app_handle, &setting);
(setting, value)
};
@@ -207,7 +234,9 @@ pub fn set_store_dat_zoom_factor(app_handle: &AppHandle, zoom_factor: f64) -> Se
})
}
-pub fn get_store_dat_setting(app_handle: &AppHandle) -> Setting {
+/// 泛型 `Runtime`:允许从非 Wry 具体化的窗口句柄(如工具函数的
+/// `WebviewWindow<R>`)读取设置;具体类型调用方不受影响。
+pub fn get_store_dat_setting<R: Runtime>(app_handle: &AppHandle<R>) -> Setting {
let _guard = setting_write_lock()
.lock()
.unwrap_or_else(|error| error.into_inner());
@@ -241,8 +270,8 @@ pub fn set_dsh_pkg_tag(app_handle: &AppHandle, tag: String) {
#[cfg(test)]
mod tests {
use super::{
- default_zoom_factor, normalize_zoom_factor, preserve_persisted_zoom, Setting,
- ZOOM_FACTOR_MAX, ZOOM_FACTOR_MIN,
+ default_close_action, default_zoom_factor, normalize_close_action, normalize_zoom_factor,
+ preserve_persisted_fields, Setting, ZOOM_FACTOR_MAX, ZOOM_FACTOR_MIN,
};
#[test]
@@ -275,12 +304,101 @@ mod tests {
}
#[test]
- fn legacy_full_setting_write_preserves_latest_zoom() {
+ fn legacy_full_setting_write_preserves_latest_fields() {
let mut stale = Setting::default();
stale.zoom_factor = 0.8;
+ stale.close_action = "quit".to_string();
+
+ let mut current = Setting::default();
+ current.zoom_factor = 1.6;
+ current.close_action = "tray".to_string();
- let merged = preserve_persisted_zoom(stale, 1.6);
+ let merged = preserve_persisted_fields(stale, &current);
assert_eq!(merged.zoom_factor, 1.6);
+ assert_eq!(
+ merged.close_action, "tray",
+ "整对象写入不得用陈旧值覆盖锁内读到的最新关窗动作"
+ );
+ }
+
+ #[test]
+ fn close_action_defaults_for_legacy_settings() {
+ let setting: Setting = serde_json::from_value(serde_json::json!({
+ "installed": true,
+ "port": 4099,
+ "auto_start": true,
+ "language": "en-US"
+ }))
+ .expect("legacy setting should deserialize");
+
+ assert_eq!(
+ setting.close_action,
+ default_close_action(),
+ "旧配置缺失 close_action 时应回落默认"
+ );
+ assert_eq!(
+ setting.port, 4099,
+ "缺失 close_action 不应影响其余字段"
+ );
+ }
+
+ #[test]
+ fn close_action_normalizes_unknown_values() {
+ assert_eq!(normalize_close_action("tray"), "tray");
+ assert_eq!(normalize_close_action("quit"), "quit");
+
+ for raw in ["", "TRAY", "bogus", "quit ", "tray;drop"] {
+ assert_eq!(
+ normalize_close_action(raw),
+ "tray",
+ "非法值 {raw} 应回落默认"
+ );
+ }
+
+ let setting: Setting = serde_json::from_value(serde_json::json!({
+ "installed": true,
+ "port": 4099,
+ "auto_start": true,
+ "language": "en-US",
+ "close_action": "bogus"
+ }))
+ .expect("tampered setting should deserialize");
+
+ assert_eq!(
+ normalize_close_action(&setting.close_action),
+ "tray",
+ "store 中的非法值应在读取路径被归一化"
+ );
+ assert_eq!(
+ setting.port, 4099,
+ "非法 close_action 不得触发 Setting 整体回落默认"
+ );
+ }
+
+ #[test]
+ fn close_action_default_is_tray() {
+ assert_eq!(
+ default_close_action(),
+ "tray",
+ "新用户默认关闭行为为隐藏到托盘"
+ );
+ assert_eq!(Setting::default().close_action, "tray");
+ }
+
+ #[test]
+ fn close_action_round_trip() {
+ let setting = Setting {
+ close_action: "quit".to_string(),
+ ..Default::default()
+ };
+ let json = serde_json::to_string(&setting).expect("setting should serialize");
+ let restored: Setting = serde_json::from_str(&json).expect("setting should deserialize");
+
+ assert_eq!(
+ normalize_close_action(&restored.close_action),
+ "quit",
+ "写入 store 再读回后关闭行为应保持不变"
+ );
}
}
diff --git a/src-tauri/src/desktop/activation.rs b/src-tauri/src/desktop/activation.rs
new file mode 100644
index 00000000..769e1357
--- /dev/null
+++ b/src-tauri/src/desktop/activation.rs
@@ -0,0 +1,222 @@
+//! macOS activation policy(应用级前台形态)切换。
+//!
+//! 窗口隐藏时切 `.accessory` 让 Dock 图标消失,恢复时切回 `.regular` 让 Dock
+//! 图标与菜单栏同步出现。策略是**应用级**状态而非窗口级,一次切换对全部屏幕的
+//! Dock 一并生效,因此本模块不做任何窗口级/屏幕级判断(多显示器无需特殊处理)。
+//!
+//! 关于 ⌘-Tab:本模块**不为 ⌘-Tab 留任何钩子**。`.accessory` 会把应用同时从
+//! Dock 与 ⌘-Tab 切换器移除,且 `tauri::RunEvent` 全枚举中没有「应用被切换为
+//! 前台」的事件可挂(D-18 取代 D-06 与 D-13 的 ⌘-Tab 部分)。驻留期间的前台
+//! 恢复路径只有:托盘左键 / 托盘菜单「打开面板」/ `RunEvent::Reopen`
+//! (启动台·Spotlight)/ release single-instance。
+
+/// 关闭窗口 = 隐藏到托盘(D-09 默认值,也是本阶段 CloseRequested 唯一传入的动作)。
+pub const CLOSE_ACTION_TRAY: &str = "tray";
+
+/// 关闭窗口 = 退出应用。
+pub const CLOSE_ACTION_QUIT: &str = "quit";
+
+#[cfg(target_os = "macos")]
+use std::sync::{Mutex, OnceLock};
+
+use tauri::{AppHandle, Runtime, WebviewWindow, Window};
+// macOS 侧需要 Manager(从窗口取回 AppHandle)与 ActivationPolicy 下发应用级策略
+#[cfg(target_os = "macos")]
+use tauri::{ActivationPolicy, Manager};
+
+/// 关窗时是否应切到 Accessory(隐藏 Dock)。
+///
+/// 抽成不依赖 `AppHandle` 的纯函数,才能在非 macOS / CI 上直接断言判定逻辑。
+/// 只认精确的 `tray`,未知或大小写不符的值一律返回 false —— 保守降级为「不切」,
+/// 宁可留着 Dock 图标,也不要把应用切进用户无法从 Dock 唤回的形态。
+///
+/// 调用方契约:builder 的 CloseRequested 在 quit 分支已提前 `exit(0)`,不会走
+/// 到 `on_window_hidden`,故本函数对 `quit` 的拒绝在生产中属防御深度 —— 未来
+/// 调用方无需自行 gate quit,直接传原始动作即可。
+#[cfg(any(target_os = "macos", test))]
+pub fn should_switch_to_accessory(is_fullscreen: bool, close_action: &str) -> bool {
+ // 全屏态切策略会让原生全屏空间闪一下 Dock,故等退出全屏后再补切(D-04)
+ !is_fullscreen && close_action == CLOSE_ACTION_TRAY
+}
+
+/// 进程内缓存的策略取值。
+///
+/// `tauri::ActivationPolicy` 是 `#[non_exhaustive]` 且不保证实现 `PartialEq`,
+/// 无法直接放进缓存比较,因此用本地枚举承载,只在真正调用前映射一次。
+#[cfg(target_os = "macos")]
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum PolicyState {
+ Regular,
+ Accessory,
+}
+
+/// 当前已生效的策略。`None` 表示尚未切换过(系统默认即 regular)。
+///
+/// 缓存的目的不是省一次调用,而是防抖动:每次 show/hide 都无条件调
+/// `set_activation_policy` 会让 Dock 图标反复增删并抢焦点。
+#[cfg(target_os = "macos")]
+static CURRENT_POLICY: OnceLock<Mutex<Option<PolicyState>>> = OnceLock::new();
+
+/// 全屏期间被推迟的 Accessory 切换(D-04),退出全屏后由 `Resized` 补做。
+#[cfg(target_os = "macos")]
+static PENDING_ACCESSORY: OnceLock<Mutex<bool>> = OnceLock::new();
+
+#[cfg(target_os = "macos")]
+fn pending_accessory_slot() -> &'static Mutex<bool> {
+ PENDING_ACCESSORY.get_or_init(|| Mutex::new(false))
+}
+
+/// 记录/清除「全屏期间推迟的切换」。
+#[cfg(target_os = "macos")]
+fn set_pending_accessory(pending: bool) {
+ *pending_accessory_slot()
+ .lock()
+ .unwrap_or_else(|error| error.into_inner()) = pending;
+}
+
+/// 取出并清除推迟标志,保证补做只发生一次(连续 Resized 幂等吸收)。
+#[cfg(target_os = "macos")]
+fn take_pending_accessory() -> bool {
+ let mut pending = pending_accessory_slot()
+ .lock()
+ .unwrap_or_else(|error| error.into_inner());
+ let was_pending = *pending;
+ *pending = false;
+ was_pending
+}
+
+/// 真正下发策略切换,命中缓存则直接返回。
+///
+/// 禁止 `.prohibited`:该取值下应用无法创建窗口也无法被拉回前台,会直接破坏
+/// 「从托盘恢复主窗口」这条成功标准,因此本模块只使用 regular / accessory 两者。
+#[cfg(target_os = "macos")]
+fn apply_policy<R: Runtime>(app: &AppHandle<R>, state: PolicyState) {
+ let mut cached = CURRENT_POLICY
+ .get_or_init(|| Mutex::new(None))
+ .lock()
+ .unwrap_or_else(|error| error.into_inner());
+ if *cached == Some(state) {
+ return;
+ }
+ let policy = match state {
+ PolicyState::Regular => ActivationPolicy::Regular,
+ PolicyState::Accessory => ActivationPolicy::Accessory,
+ };
+ match app.set_activation_policy(policy) {
+ Ok(()) => *cached = Some(state),
+ Err(error) => log::warn!("[activation] ACTIVATION_POLICY_FAILED: {error}"),
+ }
+}
+
+/// 窗口被隐藏后(CloseRequested 里 prevent_close + hide 之后)按需切 Accessory。
+///
+/// 全屏态不切,只挂推迟标志:此时切策略会让原生全屏空间里的 Dock 反复增删。
+/// 参数类型与 `.on_window_event` 闭包拿到的一致(窗口类型之间无自动转换路径),
+/// 因此调用点无需再做任何包装。
+///
+/// 非 macOS 平台整体编译为空实现,关窗隐藏的既有行为不变。
+#[cfg_attr(not(target_os = "macos"), allow(unused_variables))]
+pub fn on_window_hidden<R: Runtime>(window: &Window<R>, close_action: &str) {
+ #[cfg(target_os = "macos")]
+ {
+ let Ok(is_fullscreen) = window.is_fullscreen() else {
+ return;
+ };
+ if should_switch_to_accessory(is_fullscreen, close_action) {
+ apply_policy(window.app_handle(), PolicyState::Accessory);
+ return;
+ }
+ if is_fullscreen {
+ set_pending_accessory(true);
+ log::warn!("[activation] 全屏态关窗,推迟到退出全屏后再切 Accessory");
+ }
+ }
+}
+
+/// 退出全屏后补做被推迟的 Accessory 切换。
+///
+/// 退出全屏必伴随 `Resized`(`Moved` 不触发),全屏动画期间的连续 `Resized`
+/// 由「取出即清零」的 pending 标志幂等吸收。
+#[cfg_attr(not(target_os = "macos"), allow(unused_variables))]
+pub fn on_window_resized<R: Runtime>(window: &Window<R>) {
+ #[cfg(target_os = "macos")]
+ {
+ let Ok(false) = window.is_fullscreen() else {
+ return;
+ };
+ if take_pending_accessory() {
+ apply_policy(window.app_handle(), PolicyState::Accessory);
+ }
+ }
+}
+
+/// 恢复前台前切回 Regular:由 `utils::show_main_window` 在 `show()` 之前调用,
+/// 一次覆盖托盘菜单「打开面板」/ 托盘左键 / `RunEvent::Reopen` / single-instance
+/// 四条恢复路径。
+///
+/// 顺序是硬约束:Accessory 下 `window.show()` 有历史问题(tauri #5122),必须先
+/// 切回 regular 再 show。同时清掉全屏推迟标志 —— 恢复路径以「可见」为准,
+/// 最坏情况只是 Dock 到下次关窗时才消失,而不是永不隐藏。
+#[cfg_attr(not(target_os = "macos"), allow(unused_variables))]
+pub fn set_regular_policy<R: Runtime>(app: &AppHandle<R>) {
+ #[cfg(target_os = "macos")]
+ {
+ set_pending_accessory(false);
+ apply_policy(app, PolicyState::Regular);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{should_switch_to_accessory, CLOSE_ACTION_QUIT, CLOSE_ACTION_TRAY};
+
+ #[test]
+ fn close_action_constants_match_store_values() {
+ assert_eq!(CLOSE_ACTION_TRAY, "tray", "托盘驻留动作必须是 tray");
+ assert_eq!(CLOSE_ACTION_QUIT, "quit", "退出动作必须是 quit");
+ }
+
+ #[test]
+ fn closes_to_tray_hides_dock_when_not_fullscreen() {
+ assert!(
+ should_switch_to_accessory(false, CLOSE_ACTION_TRAY),
+ "普通关窗应当切 Accessory 隐藏 Dock"
+ );
+ }
+
+ #[test]
+ fn fullscreen_close_keeps_dock_until_exit_fullscreen() {
+ assert!(
+ !should_switch_to_accessory(true, CLOSE_ACTION_TRAY),
+ "全屏态关窗必须保持 regular,退出全屏后再补切"
+ );
+ }
+
+ #[test]
+ fn quit_action_never_switches_policy() {
+ assert!(
+ !should_switch_to_accessory(false, CLOSE_ACTION_QUIT),
+ "要退出的关窗不需要切 Accessory"
+ );
+ assert!(
+ !should_switch_to_accessory(true, CLOSE_ACTION_QUIT),
+ "全屏且要退出时同样不切 Accessory"
+ );
+ }
+
+ #[test]
+ fn unknown_close_action_keeps_dock_visible() {
+ assert!(
+ !should_switch_to_accessory(false, ""),
+ "空动作应保守降级为不切,Dock 保留"
+ );
+ assert!(
+ !should_switch_to_accessory(false, "TRAY"),
+ "大小写不一致的动作不识别,Dock 保留"
+ );
+ assert!(
+ !should_switch_to_accessory(false, "bogus"),
+ "未知动作应保守降级为不切,Dock 保留"
+ );
+ }
+}
diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rs
index 67c48975..bac4e31a 100644
--- a/src-tauri/src/desktop/builder.rs
+++ b/src-tauri/src/desktop/builder.rs
@@ -579,10 +579,48 @@ pub fn builder() -> tauri::Builder<tauri::Wry> {
}
_ => {}
})
- // 点击关闭按钮时隐藏到托盘而不是退出程序
+ // 关闭行为由设置项 `setting.close_action` 控制(D-08 / D-09):
+ // - quit:关窗即完整退出进程,不驻留托盘、不切 Accessory;
+ // - tray(默认):阻止关闭,应用级 hide(Cmd+H 语义)并切 Accessory 隐藏 Dock。
+ // 退出分支**故意不加** `#[cfg(target_os = "macos")]` 门控 —— 「关闭窗口=
+ // 退出应用」是用户可选项,语义上应当三平台一致,不是 macOS 专属;而
+ // `activation::on_window_hidden` 仅在 macOS 上有实现,故它保留 macOS 门控。
+ // 点击关闭按钮时按设置决定:隐藏到托盘驻留,还是完整退出程序
.on_window_event(|window, event| match event {
tauri::WindowEvent::CloseRequested { api, .. } => {
+ // get_store_dat_setting 内部已归一化,取值只可能是 tray 或 quit
+ let close_action =
+ crate::config::get_store_dat_setting(&window.app_handle()).close_action;
+ if close_action == crate::desktop::activation::CLOSE_ACTION_QUIT {
+ // 不 prevent_close、不 hide:直接退出。app.exit(0) 会走
+ // RunEvent::ExitRequested,既有的几何保存逻辑照常触发
+ window.app_handle().exit(0);
+ return;
+ }
api.prevent_close();
+ // macOS 上隐藏不能用窗口级 orderOut(window.hide()):应用隐藏
+ // 最后一个窗口后会被系统在 ~1.5s 后发 quit Apple Event 终止
+ // (macOS 26/27 对「无可见窗口」应用的回收行为)。正确顺序:
+ // 先切 Accessory(此时窗口仍可见,避免 Accessory 下 show 的
+ // tauri #5122 问题),再用应用级 hide(Cmd+H 语义)—— 系统不会
+ // 回收 hide: 隐藏的应用。恢复路径见 utils::show_main_window 的
+ // app.show()(unhide)配对。
+ #[cfg(target_os = "macos")]
+ {
+ crate::desktop::activation::on_window_hidden(window, &close_action);
+ if let Err(error) = window.app_handle().hide() {
+ // 应用级 hide 失败(理论不发生)时**保持窗口可见**:
+ // 窗口级 hide() 是 orderOut,会落入 macOS 26/27 对
+ // 「无可见窗口」应用的 ~1.5s quit 回收 —— 比可见窗口
+ // 更糟。可见窗口是严格更安全的降级态。
+ // hide 失败意味着应用仍停留在 Accessory(on_window_hidden
+ // 已提前切过去),可见窗口配合消失的 Dock/⌘-Tab 会让用户
+ // 无法将应用拉回前台,故这里必须切回 regular 恢复 Dock。
+ crate::desktop::activation::set_regular_policy(window.app_handle());
+ log::error!("[activation] APP_HIDE_FAILED: {error}");
+ }
+ }
+ #[cfg(not(target_os = "macos"))]
let _ = window.hide();
}
// 移动/缩放主窗口时记录几何,重启后据此恢复(见 config::window_state)
@@ -593,6 +631,9 @@ pub fn builder() -> tauri::Builder<tauri::Wry> {
crate::config::save_geometry(window);
#[cfg(target_os = "macos")]
sync_macos_fullscreen_menu(window);
+ // 退出全屏后补做全屏期间被推迟的 Accessory 切换
+ #[cfg(target_os = "macos")]
+ crate::desktop::activation::on_window_resized(window);
}
_ => {}
});
diff --git a/src-tauri/src/desktop/mod.rs b/src-tauri/src/desktop/mod.rs
index 08bab606..8848bb6f 100644
--- a/src-tauri/src/desktop/mod.rs
+++ b/src-tauri/src/desktop/mod.rs
@@ -1,3 +1,4 @@
+pub mod activation;
pub mod autostart;
pub mod builder;
pub mod compat;
diff --git a/src-tauri/src/utils/mod.rs b/src-tauri/src/utils/mod.rs
index b54a8445..7b059c76 100644
--- a/src-tauri/src/utils/mod.rs
+++ b/src-tauri/src/utils/mod.rs
@@ -77,6 +77,22 @@ pub fn show_window<R: Runtime>(window: &WebviewWindow<R>) {
/// 若窗口确实不存在(非预期路径),仅记录日志,不重建。
pub fn show_main_window<R: Runtime>(app: &AppHandle<R>) {
if let Some(window) = app.get_webview_window("main") {
+ // 关窗驻留用的是应用级 hide(NSApp hide:,见 builder 的 CloseRequested),
+ // 恢复前必须先 unhide 整个应用,否则 window.show() 在隐藏态应用上不可见。
+ #[cfg(target_os = "macos")]
+ if let Err(error) = app.show() {
+ log::warn!("[window] APP_SHOW_FAILED: {error}");
+ }
+ // Accessory 下 window.show() 有历史问题(tauri #5122),必须先切回
+ // regular 再 show;放在这里可一次覆盖托盘菜单「打开面板」、托盘左键、
+ // RunEvent::Reopen、release single-instance 四条恢复路径。
+ #[cfg(target_os = "macos")]
+ crate::desktop::activation::set_regular_policy(app);
+ // 恢复路径不改变全屏状态:全屏关窗后从托盘恢复,窗口依旧全屏。
+ // 不在此重新挂起 Accessory:窗口此时已可见,若挂起推迟标志,用户
+ // 退出全屏时 on_window_resized 会把可见应用切进 Accessory,导致 Dock
+ // 图标与 ⌘-Tab 在窗口仍打开时消失。Accessory 只在关窗驻留路径的
+ // hide 之后生效,前台可见态应保持 regular。
show_window(&window);
} else {
log::warn!("[window] main window not found, skip show");
diff --git a/src/components/config-close-action.tsx b/src/components/config-close-action.tsx
new file mode 100644
index 00000000..1864924d
--- /dev/null
+++ b/src/components/config-close-action.tsx
@@ -0,0 +1,67 @@
+import type { AppConfig } from '@/hooks/use-app-config'
+import { Description, ListBox, Select } from '@heroui/react'
+import { useMutation } from '@tanstack/react-query'
+import { invoke } from '@tauri-apps/api/core'
+import { useTranslation } from 'react-i18next'
+import { useAppConfig } from '@/hooks/use-app-config'
+import { toast } from '@/utils/toast'
+import { CLOSE_ACTION_OPTIONS, normalizeCloseAction } from '../utils/close-action'
+
+const CLOSE_ACTION_LABEL_KEYS = {
+ tray: 'ui.close_action_tray',
+ quit: 'ui.close_action_quit',
+}
+
+export function ConfigCloseAction() {
+ const { t } = useTranslation()
+ const { data: config, refetch, isFetching } = useAppConfig()
+ const { mutate: setCloseAction, isPending } = useMutation({
+ mutationFn: async (closeAction: string) => {
+ const next = normalizeCloseAction(closeAction)
+ await invoke<AppConfig>('update_app_config', { closeAction: next })
+ await refetch()
+ },
+ onError: (error: unknown) => {
+ console.error('[ConfigCloseAction] update failed:', error)
+ toast(t('messages.close_action_failed'), { variant: 'danger' })
+ },
+ })
+
+ return (
+ <div>
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-xs font-medium text-ink">{t('ui.close_action')}</span>
+ <Select
+ variant="secondary"
+ selectedKey={normalizeCloseAction(config?.close_action)}
+ onSelectionChange={key => setCloseAction(String(key))}
+ isDisabled={isFetching || isPending}
+ className="w-[140px]"
+ aria-label={t('ui.close_action')}
+ >
+ <Select.Trigger className="rounded-md min-h-8! h-8 py-0 items-center">
+ <Select.Value />
+ <Select.Indicator />
+ </Select.Trigger>
+ <Select.Popover className="rounded-md">
+ <ListBox>
+ {CLOSE_ACTION_OPTIONS.map(action => (
+ <ListBox.Item
+ className="rounded-md min-h-8!"
+ id={action}
+ key={action}
+ textValue={t(CLOSE_ACTION_LABEL_KEYS[action])}
+ >
+ {t(CLOSE_ACTION_LABEL_KEYS[action])}
+ </ListBox.Item>
+ ))}
+ </ListBox>
+ </Select.Popover>
+ </Select>
+ </div>
+ <Description className="text-[10px] text-muted/70">
+ {t('ui.close_action_hint')}
+ </Description>
+ </div>
+ )
+}
diff --git a/src/components/config-debug.tsx b/src/components/config-debug.tsx
index 7983e99d..3a0431e4 100644
--- a/src/components/config-debug.tsx
+++ b/src/components/config-debug.tsx
@@ -1,3 +1,4 @@
+import type { AppConfig } from '@/hooks/use-app-config'
import { ArrowRotateRight, ArrowUpRightFromSquare, ChevronRight, Copy, Folder, Power, TrashBin } from '@gravity-ui/icons'
import { Button, Chip, Description, Input, Link, ListBox, Select, Spinner, Surface, Switch } from '@heroui/react'
import { useMutation, useQuery } from '@tanstack/react-query'
@@ -7,9 +8,11 @@ import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { If } from 'react-if-lite'
import { useStore } from 'valtio-define'
+import { useAppConfig } from '@/hooks/use-app-config'
import { store } from '@/store'
import { writeClipboardText } from '@/utils/clipboard'
import { toast } from '@/utils/toast'
+import { ConfigCloseAction } from './config-close-action'
import { ConfigLaunchOnLogin } from './config-launch-on-login'
import { Info } from './info'
@@ -34,12 +37,6 @@ export interface CliLinkStatus {
bin_dir: string
shim_path: string
}
-export interface AppConfig {
- port: number
- auto_start: boolean
- cli_link_enabled: boolean
- zoom_factor: number
-}
export function ConfigDebug() {
const { t, i18n } = useTranslation()
@@ -73,10 +70,7 @@ export function ConfigDebug() {
}
}, [refreshInfo])
- const { data: config, refetch: refreshConfig } = useQuery({
- queryKey: ['config'],
- queryFn: () => invoke<AppConfig>('get_app_config'),
- })
+ const { data: config, refetch: refreshConfig } = useAppConfig()
const port = portInput ?? config?.port ?? 3080
const { data: cliStatus, refetch: refreshCliStatus } = useQuery({
@@ -301,6 +295,7 @@ export function ConfigDebug() {
<div className="border-t border-line/30" />
<div className="space-y-1.5">
<ConfigLaunchOnLogin />
+ <ConfigCloseAction />
<div>
<div className="flex items-center justify-between">
<span className="text-xs font-medium text-ink">{t('ui.cli_link_enabled')}</span>
diff --git a/src/components/config-dialog.tsx b/src/components/config-dialog.tsx
index 38a54e6d..cb01435f 100644
--- a/src/components/config-dialog.tsx
+++ b/src/components/config-dialog.tsx
@@ -1,5 +1,5 @@
import type { PropsWithOverlays } from '@overlastic/react'
-import { Cpu, PersonPencil, Puzzle, Wrench } from '@gravity-ui/icons'
+import { Cpu, LogoWindows, PersonPencil, Puzzle } from '@gravity-ui/icons'
import { useEventBus } from '@hairy/react-lib'
import { cn, Modal } from '@heroui/react'
import { useDisclosure } from '@overlastic/react'
@@ -22,13 +22,13 @@ export function ConfigDialog(props: ConfigDialogProps) {
const abnormalCount = plugins.filter(p => p.error != null).length
const navs = [
- { label: t('config.debug'), value: 'debug', icon: Wrench },
+ { label: t('config.application'), value: 'application', icon: LogoWindows },
{ label: t('config.profiles'), value: 'profiles', icon: PersonPencil },
{ label: t('config.plugins'), value: 'plugins', icon: Puzzle },
{ label: t('config.harness'), value: 'harness', icon: Cpu },
]
- const [activeTab, setActiveTab] = useState('debug')
+ const [activeTab, setActiveTab] = useState('application')
useEventBus('config:dialog:hidden').on(disclosure.cancel)
@@ -69,9 +69,9 @@ export function ConfigDialog(props: ConfigDialogProps) {
})}
</nav>
</aside>
- <div className="flex flex-col flex-1 overflow-auto min-h-0 max-h-[628px] pr-2.5">
+ <div className="flex flex-col flex-1 overflow-auto min-h-0 pr-2.5">
<Switch value={activeTab} as="div">
- <Case cond="debug">
+ <Case cond="application">
<ConfigDebug />
</Case>
<Case cond="profiles">
diff --git a/src/hooks/use-app-config.ts b/src/hooks/use-app-config.ts
new file mode 100644
index 00000000..5c97d40c
--- /dev/null
+++ b/src/hooks/use-app-config.ts
@@ -0,0 +1,19 @@
+import { useQuery } from '@tanstack/react-query'
+import { invoke } from '@tauri-apps/api/core'
+
+export interface AppConfig {
+ port: number
+ auto_start: boolean
+ cli_link_enabled: boolean
+ zoom_factor: number
+ close_action: string
+}
+
+/// 共享的 app 配置查询:config-close-action 与 config-debug 共用同一份
+/// queryKey/queryFn 定义,避免两处手写 useQuery 漂移(如一方加了 staleTime)。
+export function useAppConfig() {
+ return useQuery({
+ queryKey: ['config'],
+ queryFn: () => invoke<AppConfig>('get_app_config'),
+ })
+}
diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.json
index 7442a3a1..173079bf 100644
--- a/src/i18n/locales/en-US.json
+++ b/src/i18n/locales/en-US.json
@@ -91,6 +91,10 @@
"ui.zoom": "Zoom",
"ui.launch_on_login": "Launch app at login",
"ui.launch_on_login_hint": "Starts the desktop app after you sign in. Harness service startup is configured separately.",
+ "ui.close_action": "Close action",
+ "ui.close_action_hint": "What happens when you close the main window. “Hide to tray” keeps the app running in the background — click the tray icon to reopen it. On macOS, while in the background it does not appear in the ⌘-Tab app switcher.",
+ "ui.close_action_tray": "Hide to tray",
+ "ui.close_action_quit": "Quit app",
"ui.cli_link": "CLI Integration",
"ui.cli_link_enabled": "Enable dsh command",
"ui.cli_link_hint": "Run dsh --help in a new terminal",
@@ -120,6 +124,7 @@
"messages.port_restart_hint": "It takes effect after the service restarts. Restart now?",
"messages.zoom_failed": "Failed to update zoom",
"messages.launch_on_login_failed": "Failed to update launch at login",
+ "messages.close_action_failed": "Failed to update close action",
"messages.logs_cleared": "Logs cleared",
"nav.sidebar_expand": "Expand sidebar",
"nav.sidebar_collapse": "Collapse sidebar",
@@ -197,7 +202,7 @@
"core.local_missing_hint": "No local core detected. Install @deepseek-ai/dsh globally via npm/pnpm and the desktop will prefer it automatically.",
"app.dev_env": "Development",
"app.config": "Config",
- "config.debug": "Debug",
+ "config.application": "Application",
"config.profiles": "Profiles",
"config.plugins": "Plugins",
"config.harness": "Harness",
diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json
index 8515c664..789c1c2b 100644
--- a/src/i18n/locales/zh-CN.json
+++ b/src/i18n/locales/zh-CN.json
@@ -91,6 +91,10 @@
"ui.zoom": "界面缩放",
"ui.launch_on_login": "开机自启动",
"ui.launch_on_login_hint": "登录系统后启动桌面应用;Harness 服务的自动运行配置与此项相互独立。",
+ "ui.close_action": "关闭行为",
+ "ui.close_action_hint": "关闭主窗口时的行为;选择「隐藏到托盘」后应用继续在后台运行,可点击菜单栏托盘图标重新打开。macOS 上后台运行期间不会出现在 ⌘-Tab 应用切换器中。",
+ "ui.close_action_tray": "隐藏到托盘",
+ "ui.close_action_quit": "退出应用",
"ui.cli_link": "命令行集成",
"ui.cli_link_enabled": "启用 dsh 命令",
"ui.cli_link_hint": "在新终端中运行 dsh --help 查看用法",
@@ -120,6 +124,7 @@
"messages.port_restart_hint": "重启服务后生效,是否立即重启?",
"messages.zoom_failed": "界面缩放更新失败",
"messages.launch_on_login_failed": "更新开机自启动设置失败",
+ "messages.close_action_failed": "更新关闭行为设置失败",
"messages.logs_cleared": "日志已清空",
"nav.sidebar_expand": "展开侧边栏",
"nav.sidebar_collapse": "收起侧边栏",
@@ -197,7 +202,7 @@
"core.local_missing_hint": "未检测到本地核心。通过 npm/pnpm 全局安装 @deepseek-ai/dsh 后,桌面端将自动优先使用它。",
"app.dev_env": "开发环境",
"app.config": "配置",
- "config.debug": "调试",
+ "config.application": "应用",
"config.profiles": "档案",
"config.plugins": "插件",
"config.harness": "核心",
diff --git a/src/store/modules/harness/store.ts b/src/store/modules/harness/store.ts
index 97de6dda..5523c702 100644
--- a/src/store/modules/harness/store.ts
+++ b/src/store/modules/harness/store.ts
@@ -75,9 +75,11 @@ const restartFlight = new SingleFlight<void>()
const iframeReloadGate = new BoundedReloadGate(3)
let iframeRefreshTimer: ReturnType<typeof setTimeout> | undefined
-/** 构建带时间戳的 iframe URL,避免 WebView2 缓存旧页面。
+/**
+ * 构建带时间戳的 iframe URL,避免 WebView2 缓存旧页面。
* alpha 鉴权由启动前的桌面端 patch 处理,iframe 永远不携带启动 token;旧核心
- * 同样继续使用原有的缓存查询参数。 */
+ * 同样继续使用原有的缓存查询参数。
+ */
function generateTimestampedUrl(baseUrl: string): string {
const timestamp = Date.now()
const separator = baseUrl.includes('?') ? '&' : '?'
diff --git a/src/utils/close-action.ts b/src/utils/close-action.ts
new file mode 100644
index 00000000..7d1b84de
--- /dev/null
+++ b/src/utils/close-action.ts
@@ -0,0 +1,11 @@
+export type CloseAction = 'tray' | 'quit'
+
+export const CLOSE_ACTION_DEFAULT: CloseAction = 'tray'
+
+export const CLOSE_ACTION_OPTIONS = ['tray', 'quit'] as const satisfies readonly CloseAction[]
+
+// 只认 Rust 侧 `normalize_close_action` 白名单里的两个字面量,不做 trim / 大小写
+// 折叠,避免两端语义漂移;非法值的最终判定责任仍在后端,这里只是收敛下发值。
+export function normalizeCloseAction(value: unknown): CloseAction {
+ return value === 'quit' ? 'quit' : 'tray'
+}
diff --git a/test/close-action.test.ts b/test/close-action.test.ts
new file mode 100644
index 00000000..2319f2ac
--- /dev/null
+++ b/test/close-action.test.ts
@@ -0,0 +1,58 @@
+import { readFileSync } from 'node:fs'
+import { describe, expect, it } from 'vitest'
+import {
+ CLOSE_ACTION_DEFAULT,
+ CLOSE_ACTION_OPTIONS,
+ normalizeCloseAction,
+} from '../src/utils/close-action'
+
+describe('close action normalization', () => {
+ it('defaults to hiding in tray', () => {
+ expect(CLOSE_ACTION_DEFAULT).toBe('tray')
+ })
+
+ it('exposes exactly the tray and quit options', () => {
+ expect(CLOSE_ACTION_OPTIONS).toEqual(['tray', 'quit'])
+ })
+
+ it('keeps the two supported literal values', () => {
+ expect(normalizeCloseAction('tray')).toBe('tray')
+ expect(normalizeCloseAction('quit')).toBe('quit')
+ })
+
+ it('falls back to tray for anything outside the whitelist', () => {
+ expect(normalizeCloseAction(undefined)).toBe('tray')
+ expect(normalizeCloseAction(null)).toBe('tray')
+ expect(normalizeCloseAction('')).toBe('tray')
+ expect(normalizeCloseAction('TRAY')).toBe('tray')
+ expect(normalizeCloseAction('bogus')).toBe('tray')
+ expect(normalizeCloseAction({})).toBe('tray')
+ })
+})
+
+describe('config close action control contract', () => {
+ it('invokes update_app_config once with a camelCase closeAction payload', () => {
+ const source = readFileSync(new URL('../src/components/config-close-action.tsx', import.meta.url), 'utf8')
+
+ expect(source).toContain('export function ConfigCloseAction')
+ expect(source).toContain('invoke<AppConfig>(\'update_app_config\', { closeAction')
+ // 受控值始终经归一化,未加载到配置时回落 tray 而不是给 HeroUI 传 undefined
+ expect(source).toContain('selectedKey={normalizeCloseAction(')
+ })
+
+ it('surfaces failures as a danger toast without a success toast', () => {
+ const source = readFileSync(new URL('../src/components/config-close-action.tsx', import.meta.url), 'utf8')
+
+ expect(source).toContain('messages.close_action_failed')
+ expect(source).toContain('variant: \'danger\'')
+ expect(source).not.toContain('messages.close_action_saved')
+ })
+
+ it('stays within the shell conventions', () => {
+ const source = readFileSync(new URL('../src/components/config-close-action.tsx', import.meta.url), 'utf8')
+
+ expect(source).not.toContain('useCallback')
+ expect(source).not.toContain('useMemo')
+ expect(source).not.toContain('navigator.clipboard')
+ })
+})