Skip to content

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

fix(safe-mode): 启动前清除安全档案里的用户插件

hairyf3421bd8871fb
diff --git a/src-tauri/src/bridge/lifecycle.rs b/src-tauri/src/bridge/lifecycle.rs
index 7efa917d..c933954a 100644
--- a/src-tauri/src/bridge/lifecycle.rs
+++ b/src-tauri/src/bridge/lifecycle.rs
@@ -340,6 +340,11 @@ pub async fn restart_harness(app_handle: AppHandle) -> Result<(), String> {
/// 错误界面「安全模式」按钮的入口:安全档案只含 web 模板核心 bundles、不带
/// 用户插件/补丁层,启动失败的插件(如 pending waiting for service)被隔离,
/// 应用先恢复可用;用户在档案列表切回原档案即退出安全模式。
+///
+/// 档案目录一旦存在就绝不重建,因此里面可能残留此前被装进去的用户插件(内置插件
+/// 自愈与首次引导安装都作用于「当时的活动档案」);这些插件由启动前的清除流程卸载
+/// (见 `service::plugin::safe::purge_user_plugins_in_safe_profile`),本命令只负责
+/// 切档案——服务仍在运行时删除插件目录不安全,必须等重启后的 spawn 之前再清。
#[tauri::command]
pub async fn enter_safe_mode(app_handle: AppHandle) -> Result<(), String> {
crate::service::profile::ensure_safe_profile(&app_handle)?;
diff --git a/src-tauri/src/service/plugin/installed.rs b/src-tauri/src/service/plugin/installed.rs
index 901dec00..42061346 100644
--- a/src-tauri/src/service/plugin/installed.rs
+++ b/src-tauri/src/service/plugin/installed.rs
@@ -41,8 +41,11 @@ pub(crate) fn profile_dir(app_handle: &AppHandle) -> PathBuf {
)
}
-/// 已安装的插件 id 集合:通过强类型反序列化读取 package.json 的 `dependencies` 键与 `bundles` 列表
-fn list_installed(app_handle: &AppHandle) -> HashSet<String> {
+/// 已安装的插件 id 集合:通过强类型反序列化读取 package.json 的 `dependencies` 键与 `bundles` 列表。
+///
+/// 供「插件是否已安装」的单点判定([`is_installed`])与安全模式的用户插件清除
+/// ([`super::safe`])共用:后者需要的是全量清单,而非逐个 id 的探测。
+pub(crate) fn list_installed(app_handle: &AppHandle) -> HashSet<String> {
let manifest_path = profile_dir(app_handle).join("package.json");
let Ok(content) = std::fs::read_to_string(&manifest_path) else {
return HashSet::new();
diff --git a/src-tauri/src/service/plugin/mod.rs b/src-tauri/src/service/plugin/mod.rs
index c82995ad..2f43c52f 100644
--- a/src-tauri/src/service/plugin/mod.rs
+++ b/src-tauri/src/service/plugin/mod.rs
@@ -24,6 +24,8 @@
//! 以及启动时对 `resources/deprecated-plugins.json` 登记的社区插件自动卸载
//! - [`errors`]:插件错误记录(安装/升级/卸载失败 + 页面运行期上报,持久化)
//! - [`process`]:dsh 子进程启动与输出流逐行转发
+//! - [`recovery`]:插件异常定位与一键离线卸载
+//! - [`safe`]:安全档案启动前的用户插件清除(只留内置插件与核心包)
//! - [`cancel`]:Windows 下取消正在进行的安装
//! - [`watch`]:已安装插件文件监控(轮询指纹比对 + `dsh-plugins-updated` 事件推送)
@@ -36,6 +38,7 @@ mod internal;
mod preset;
mod process;
pub mod recovery;
+mod safe;
pub mod snapshot;
pub mod update;
pub mod verify;
@@ -46,7 +49,7 @@ pub use cancel::cancel;
pub(crate) use install::harness_prefer_bundled_pnpm;
pub(crate) use install::uninstall_deprecated_plugins;
pub use install::{install, remove, update};
-pub(crate) use installed::{ensure_profile_npmrc, installed_name, profile_dir};
+pub(crate) use installed::{ensure_profile_npmrc, installed_name, list_installed, profile_dir};
pub use installed::{list, PreinstallPlugin};
pub(crate) use internal::cancel as cancel_internal_plugins;
pub(crate) use internal::ensure as ensure_internal_plugins;
@@ -55,6 +58,7 @@ pub(crate) use preset::{
bundled_plugin_dir, current_preset_hash, load_presets, preinstall_pending,
remove_legacy_bundled_plugins,
};
+pub(crate) use safe::purge_user_plugins_in_safe_profile;
pub use disable::{disable, enable};
pub use recovery::{
detect as detect_recovery, uninstall as uninstall_recovery, PluginRecoveryInfo,
diff --git a/src-tauri/src/service/plugin/safe.rs b/src-tauri/src/service/plugin/safe.rs
new file mode 100644
index 00000000..fb801dec
--- /dev/null
+++ b/src-tauri/src/service/plugin/safe.rs
@@ -0,0 +1,185 @@
+//! 安全模式插件卫生:进入安全档案(`safe`)启动前清除该档案里的用户插件。
+//!
+//! 安全档案的契约是「只加载 web 模板核心 bundles、不带任何用户插件/补丁层」
+//! (见 [`crate::service::profile::ensure_safe_profile`])。但档案目录一旦存在就
+//! 绝不重建(用户可能反复进出安全模式,重建会一并丢掉档案内的其它状态),而
+//! 内置插件自愈([`super::internal`])与首次引导安装都作用于「当时的活动档案」
+//! ——于是安全档案里会累积用户插件。它们往往正是启动失败的元凶:不清理的话每次
+//! 进入安全模式都带着同一批插件重启,隔离形同虚设(用户看到的仍是同一个启动失败)。
+//!
+//! 因此桌面端在 spawn dsh 之前把安全档案里的用户插件卸干净,只保留两类:
+//! - **内置插件**(`internal: true`,如 dsh-tauri 系列):随安装包分发、由启动自愈
+//! 强制安装,桌面壳的核心功能依赖它们;
+//! - **核心/官方包**(`@deepseek-ai/*`):安全档案的模板本身
+//! (`@deepseek-ai/dsh-base` / `@deepseek-ai/dsh-web-app`)。
+//!
+//! 卸载走离线精准路径([`uninstall_recovery`]):不依赖 node/pnpm/窗口、不触网,
+//! 即使插件产物已损坏也能移除。调用时机必须是服务未启动时(改清单、删 node_modules
+//! 目录才安全),故由 launch 在 spawn 前调用。普通档案一律不动:用户的插件是用户资产。
+
+use std::collections::HashSet;
+use tauri::AppHandle;
+
+use super::recovery::is_actionable_plugin_ref;
+use super::{installed_name, list_installed, load_presets, uninstall_recovery};
+use crate::service::profile::{active_profile, SAFE_PROFILE};
+
+/// 计算安全档案里需要清除的用户插件包名(纯函数,便于单测)。
+///
+/// 命中条件:条目出现在 profile 清单(`dependencies` 键或 `dsh.profile.bundles`,
+/// 由 [`list_installed`] 给出)、可被卸载([`is_actionable_plugin_ref`] 排除
+/// 核心/官方 `@deepseek-ai/*` 与非法包名),且不属于内置插件。其余一律视为用户
+/// 插件——安全模式宁可多清(离线卸载对未安装条目是 no-op),也不留下任何可能
+/// 触发启动失败的插件。
+fn user_plugin_names(installed: &HashSet<String>, builtin: &HashSet<String>) -> Vec<String> {
+ let mut names: Vec<String> = installed
+ .iter()
+ .filter(|name| is_actionable_plugin_ref(name) && !builtin.contains(*name))
+ .cloned()
+ .collect();
+ // 排序只为日志与测试的确定性(卸载顺序与结果无关)。
+ names.sort();
+ names
+}
+
+/// 内置插件包名集合(以实际安装包名为准,见 [`installed_name`])。
+///
+/// 清单来自随包分发的 `resources/internal-plugins.json`,debug 下并入仓库根
+/// `packages/*` 发现的内置插件;内部属性由清单来源决定(见 `preset::load_presets`),
+/// 社区预设与内置插件在此处天然分流。
+fn builtin_plugin_names(app_handle: &AppHandle) -> HashSet<String> {
+ load_presets(app_handle)
+ .iter()
+ .filter(|plugin| plugin.internal)
+ .map(|plugin| installed_name(plugin).to_string())
+ .collect()
+}
+
+/// spawn dsh 之前调用:当前档案是安全档案时,清除其中全部用户插件。
+///
+/// 非安全档案直接返回(普通档案的插件是用户资产,绝不触碰)。单个插件卸载失败不
+/// 中断其余插件的清理,失败聚合为 Err 交调用方只记告警:清理不彻底顶多让安全模式
+/// 隔离效果打折,而阻断启动会让应用彻底不可用(与启动期其它自愈同一策略)。
+pub(crate) fn purge_user_plugins_in_safe_profile(app_handle: &AppHandle) -> Result<(), String> {
+ if active_profile(app_handle) != SAFE_PROFILE {
+ return Ok(());
+ }
+
+ let builtin = builtin_plugin_names(app_handle);
+ // 内置插件清单不可用(随包资源缺失/损坏)时无法区分内置插件与用户插件:此时
+ // 宁可什么都不清(维持现状),也不能把桌面壳依赖的内置插件当用户插件删掉。
+ // 清单缺失本身已由 `preset::load_manifest` 记录错误,插件面板与安装入口同样
+ // 已降级,安全模式在这一状态下退回「不清理」是唯一不会造成额外破坏的选择。
+ if builtin.is_empty() {
+ log::warn!(
+ "SAFE_MODE_PLUGIN_PURGE_SKIPPED: built-in plugin manifest unavailable, cannot tell user plugins apart"
+ );
+ return Ok(());
+ }
+
+ let names = user_plugin_names(&list_installed(app_handle), &builtin);
+ if names.is_empty() {
+ return Ok(());
+ }
+
+ log::info!(
+ "safe mode: removing {} user plugin(s) from the safe profile: {names:?}",
+ names.len()
+ );
+ let mut failures = Vec::new();
+ for name in &names {
+ match uninstall_recovery(app_handle, name) {
+ Ok(()) => log::info!("SAFE_MODE_PLUGIN_PURGE: removed {name}"),
+ Err(e) => {
+ log::warn!("SAFE_MODE_PLUGIN_PURGE_FAILED: {name}: {e}");
+ failures.push(format!("{name}: {e}"));
+ }
+ }
+ }
+
+ if failures.is_empty() {
+ Ok(())
+ } else {
+ Err(format!(
+ "SAFE_MODE_PLUGIN_PURGE_FAILED: {}",
+ failures.join("; ")
+ ))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::super::preset::PreinstallPluginInfo;
+ use super::*;
+ use std::path::PathBuf;
+
+ /// 读取随包清单里的实际安装包名(与 [`builtin_plugin_names`] 同一套解析,
+ /// 但不依赖 AppHandle:清单文件位于源码 `src-tauri/resources/`)。
+ fn manifest_package_names(file_name: &str) -> Vec<String> {
+ let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
+ .join("resources")
+ .join(file_name);
+ let raw = std::fs::read_to_string(path).expect("plugin manifest should exist");
+ serde_json::from_str::<Vec<PreinstallPluginInfo>>(&raw)
+ .expect("plugin manifest should be valid JSON")
+ .iter()
+ .map(|plugin| installed_name(plugin).to_string())
+ .collect()
+ }
+
+ fn names(items: &[&str]) -> HashSet<String> {
+ items.iter().map(|s| (*s).to_string()).collect()
+ }
+
+ #[test]
+ fn purges_user_plugins_but_keeps_core_and_builtin() {
+ let installed = names(&[
+ "@deepseek-ai/dsh-base",
+ "@deepseek-ai/dsh-web-app",
+ "dsh-tauri",
+ "dsh-tauri-ui",
+ "dshmarket",
+ "dsh-notification",
+ ]);
+ let builtin = names(&["dsh-tauri", "dsh-tauri-ui"]);
+
+ assert_eq!(
+ user_plugin_names(&installed, &builtin),
+ vec!["dsh-notification".to_string(), "dshmarket".to_string()]
+ );
+ }
+
+ #[test]
+ fn pristine_safe_profile_needs_no_purge() {
+ let installed = names(&["@deepseek-ai/dsh-base", "@deepseek-ai/dsh-web-app"]);
+ assert!(user_plugin_names(&installed, &HashSet::new()).is_empty());
+ }
+
+ #[test]
+ fn invalid_refs_are_never_targeted() {
+ // 非法包名(空、路径片段)不进入卸载清单:离线卸载以包名为键拼
+ // node_modules 路径,越界引用必须被 `is_actionable_plugin_ref` 挡下。
+ let installed = names(&["", "..", "foo/../../target", "with space", "dsh-ok"]);
+ assert_eq!(
+ user_plugin_names(&installed, &HashSet::new()),
+ vec!["dsh-ok".to_string()]
+ );
+ }
+
+ #[test]
+ fn shipped_internal_manifest_is_protected() {
+ // 随包内置插件清单(dsh-tauri 等)必须全部落在保留集里;社区预设
+ // (dshmarket 等)属于用户插件,进入清除清单。
+ let builtin = manifest_package_names("internal-plugins.json");
+ let presets = manifest_package_names("preset-plugins.json");
+ assert!(builtin.iter().any(|name| name == "dsh-tauri"));
+ assert!(presets.iter().any(|name| name == "dshmarket"));
+
+ let mut installed: HashSet<String> = builtin.iter().cloned().collect();
+ installed.extend(presets.iter().cloned());
+ let purged = user_plugin_names(&installed, &builtin.iter().cloned().collect());
+
+ assert!(!purged.iter().any(|name| builtin.contains(name)));
+ assert!(purged.contains(&"dshmarket".to_string()));
+ }
+}
diff --git a/src-tauri/src/service/workflow/launch.rs b/src-tauri/src/service/workflow/launch.rs
index 4525647f..d3f249e5 100644
--- a/src-tauri/src/service/workflow/launch.rs
+++ b/src-tauri/src/service/workflow/launch.rs
@@ -356,6 +356,19 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {
// 不阻断启动(回落 web 档案的老行为)。
crate::service::profile::ensure_first_run_desktop_profile(&app_handle);
+ // 安全模式:安全档案的契约是「只加载 web 模板核心 bundles、不带任何用户插件」,
+ // 但档案目录一旦存在就绝不重建(用户可能反复进出安全模式),而内置插件自愈与
+ // 首次引导安装都作用于「当时的活动档案」,于是安全档案里会累积用户插件——它们
+ // 往往正是启动失败的元凶,不清干净的话每次进入安全模式都带着同一批插件重启,
+ // 隔离形同虚设。必须在 spawn dsh 之前做(服务未运行时改清单、删 node_modules
+ // 目录才安全),且要早于下面的 win_inspector::apply:apply 依据「插件是否装入
+ // profile」决定挂载还是清理 patch 行,先清插件才能让遗留挂载行被正确剥离。
+ // 内置插件与核心包由被调方保留;非安全档案直接跳过。最佳努力:失败只告警,
+ // 不阻断启动(清理不彻底只是隔离效果打折,启动阻塞则让应用彻底不可用)。
+ if let Err(e) = crate::service::plugin::purge_user_plugins_in_safe_profile(&app_handle) {
+ log::warn!("safe mode user plugin purge failed: {e}");
+ }
+
// Linux 起步前探测 inotify 监视上限:harness 服务(dsh web)用 chokidar 递归
// 监视 profile 目录,上限过低会在启动一瞬间抛 ENOSPC 直接退出(issue #116)。
// 进程无法自我调高该参数,这里只做告警(启动日志 + 读取 run logs 中的环境信息),
diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.json
index 426778ed..281cd964 100644
--- a/src/i18n/locales/en-US.json
+++ b/src/i18n/locales/en-US.json
@@ -123,7 +123,7 @@
"buttons.copy": "Copy",
"buttons.copy_logs": "Copy Logs",
"buttons.safe_mode": "Safe Mode",
- "hints.safe_mode": "Restart with only the core bundles, isolating plugins that fail to start. Switch back to your profile in the sidebar to exit safe mode.",
+ "hints.safe_mode": "Restart with only the core bundles and built-in plugins, uninstalling any other plugin from that profile to isolate the ones that fail to start. Switch back to your profile in the sidebar to exit safe mode.",
"messages.copy_success": "URL copied to clipboard",
"messages.log_copied": "Logs copied to clipboard",
"messages.copy_failed": "Failed to copy URL",
diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json
index 05c94fc6..6a59cc0f 100644
--- a/src/i18n/locales/zh-CN.json
+++ b/src/i18n/locales/zh-CN.json
@@ -123,7 +123,7 @@
"buttons.copy": "复制",
"buttons.copy_logs": "复制日志",
"buttons.safe_mode": "安全模式",
- "hints.safe_mode": "仅加载核心组件重启,隔离启动失败的插件。在侧边栏切回原档案即可退出安全模式。",
+ "hints.safe_mode": "仅加载核心组件与内置插件重启,并卸载该档案中的其它插件以隔离启动失败。在侧边栏切回原档案即可退出安全模式。",
"messages.copy_success": "地址已复制到剪贴板",
"messages.log_copied": "日志已复制到剪贴板",
"messages.copy_failed": "复制地址失败",