DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
fix(core): 清理档案里版本错配的核心包残留(修复引导页「未能保存设置」) (#776)
Mao Mr6c7832fefa62
diff --git a/src-tauri/src/service/core/runtime.rs b/src-tauri/src/service/core/runtime.rsindex 3578128f..31d22150 100644--- a/src-tauri/src/service/core/runtime.rs+++ b/src-tauri/src/service/core/runtime.rs@@ -20,10 +20,20 @@ use std::path::{Path, PathBuf};use std::process::{Command, Stdio};use std::time::{Duration, Instant};+#[cfg(windows)]+use std::os::windows::fs::FileTypeExt;+use tauri::AppHandle;use super::source::CoreSource;+/// 核心自有包所在的 scope。+const CORE_PACKAGE_SCOPE: &str = "@deepseek-ai";+/// 核心家族自身的包名前缀:`dsh` 与 `dsh-*`。+///+/// 同 scope 下的 cordis、cosmokit、schemastery 等共享框架库是插件可以合法依赖并+/// 锁定版本的对象(如 billion-context 锁 schemastery 3.18.4),不能按整个 scope 删除。+const CORE_PACKAGE_PREFIX: &str = "dsh";const NATIVE_REPAIR_TIMEOUT: Duration = Duration::from_secs(120);/// 原生模块重建(node-gyp 编译)可能远超安装耗时,单独放宽上限const NATIVE_REBUILD_TIMEOUT: Duration = Duration::from_secs(300);@@ -226,6 +236,12 @@ pub(crate) async fn prepare_active_runtime(app_handle: &AppHandle) -> Result<(),link_required_plugins(app_handle, &core_root)?;+ // 档案里的核心包残留必须在 dsh 启动前清掉:Node 从 profile 目录向上查找裸包时+ // 会先命中它,核心自带的正确版本反而被跳过。清理失败不影响后续原生探测。+ if let Err(e) = prune_stale_core_packages(app_handle, &core_root) {+ log::warn!("{e}");+ }+// 已核验过的运行时直接放行:跳过平台/架构探测与原生模块探测两个 node 子进程// (issue #766)。指纹失配、戳缺失或不可解析时一律走原探测路径;指纹本身不完整// (`None`)时既不比对也不落盘。@@ -347,6 +363,175 @@ pub(crate) async fn prepare_active_runtime(app_handle: &AppHandle) -> Result<(),))}+/// 清除档案里被旧版 dsh 投影进来、版本又与当前核心不一致的核心包。+///+/// 既有清理(上游 `removeLinkProjections` 与桌面端 `remove_legacy_profile_module_fallback`)+/// 都只认符号链接、且要求 `.dsh-module-fallback` 源目录仍然存在;用户「无视风险切换」+/// 升级核心时档案不重建,残留因此在 Node 的逐级查找里长期抢先命中,症状与病因脱钩。+fn prune_stale_core_packages(app_handle: &AppHandle, core_root: &Path) -> Result<(), String> {+ let profile = crate::service::plugin::profile_dir(app_handle);+ let Some(declared) = crate::service::plugin::declared_packages(app_handle) else {+ log::warn!(+ "CORE_PLUGIN_STALE_CORE_DECLARED_UNKNOWN: {} is unreadable, skipping cleanup",+ profile.display()+ );+ return Ok(());+ };+ prune_stale_core_entries(&profile, &core_root.join("node_modules"), &declared)+}++/// 逐个比对档案与锚点的同名核心包版本,清除版本错配且档案未声明的条目。+fn prune_stale_core_entries(+ profile_root: &Path,+ anchor_node_modules: &Path,+ declared: &HashSet<String>,+) -> Result<(), String> {+ let profile_node_modules = profile_root.join("node_modules");+ let scope = profile_node_modules.join(CORE_PACKAGE_SCOPE);+ let Some(scope_root) = containment_root(&scope, profile_root) else {+ return Ok(());+ };+ let entries = match std::fs::read_dir(&scope) {+ Ok(entries) => entries,+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),+ Err(e) => {+ return Err(format!(+ "CORE_PLUGIN_STALE_CORE_SCAN_FAILED: {}: {e}",+ scope.display()+ ))+ }+ };++ for entry in entries {+ let entry = entry.map_err(|e| {+ format!(+ "CORE_PLUGIN_STALE_CORE_SCAN_FAILED: {}: {e}",+ scope.display()+ )+ })?;+ let name = format!(+ "{CORE_PACKAGE_SCOPE}/{}",+ entry.file_name().to_string_lossy()+ );+ if !is_safe_package_name(&name) || declared.contains(&name) {+ continue;+ }+ if !is_core_family_package(&name) {+ continue;+ }+ let path = entry.path();+ if !entry_is_contained(&path, &scope_root) {+ log::warn!(+ "CORE_PLUGIN_STALE_CORE_OUT_OF_SCOPE: {} escapes {}, skipping",+ path.display(),+ scope.display()+ );+ continue;+ }+ let Some(profile_version) = read_package_version(&path.join("package.json")) else {+ continue;+ };+ let Some(anchor_version) =+ read_package_version(&anchor_node_modules.join(&name).join("package.json"))+ else {+ continue;+ };+ if profile_version == anchor_version {+ continue;+ }+ if let Err(e) = remove_core_package_residue(&path) {+ log::warn!("{e}");+ continue;+ }+ log::info!(+ "CORE_PLUGIN_STALE_CORE_PRUNED: {name} {profile_version} (profile) != {anchor_version} (anchor), removed"+ );+ }+ Ok(())+}++/// 解析 scope 的真实位置,并确认它既不是重定向入口、也仍留在档案目录内。+///+/// 包含关系以**档案目录**(而非 `node_modules`)为锚点:`node_modules` 自身若被+/// 重定向成一个外部目录,以它为根就等于把「档案之外」当成了内部。返回 `None` 时+/// 整轮跳过扫描——顺着重定向递归删除会把删除目标落到档案之外,这比「这一轮没+/// 清干净」严重得多。+fn containment_root(scope: &Path, profile_root: &Path) -> Option<PathBuf> {+ let metadata = std::fs::symlink_metadata(scope).ok()?;+ let file_type = metadata.file_type();+ #[cfg(windows)]+ let is_link = file_type.is_symlink() || file_type.is_symlink_dir();+ #[cfg(not(windows))]+ let is_link = file_type.is_symlink();+ if is_link {+ log::warn!(+ "CORE_PLUGIN_STALE_CORE_SCOPE_REDIRECTED: {} is a link, skipping cleanup",+ scope.display()+ );+ return None;+ }++ let root = std::fs::canonicalize(profile_root).ok()?;+ let real = std::fs::canonicalize(scope).ok()?;+ if !real.starts_with(&root) {+ log::warn!(+ "CORE_PLUGIN_STALE_CORE_SCOPE_ESCAPED: {} resolves to {}, skipping cleanup",+ scope.display(),+ real.display()+ );+ return None;+ }+ Some(real)+}++/// 符号链接/junction 条目只需删除入口本身,不会触及目标;真实目录必须解析后仍在 scope 内。+fn entry_is_contained(path: &Path, scope_root: &Path) -> bool {+ let Ok(metadata) = std::fs::symlink_metadata(path) else {+ return false;+ };+ let file_type = metadata.file_type();+ #[cfg(windows)]+ if file_type.is_symlink() || file_type.is_symlink_dir() {+ return true;+ }+ #[cfg(not(windows))]+ if file_type.is_symlink() {+ return true;+ }+ match std::fs::canonicalize(path) {+ Ok(real) => real.starts_with(scope_root),+ Err(_) => false,+ }+}++fn remove_core_package_residue(path: &Path) -> Result<(), String> {+ let metadata = std::fs::symlink_metadata(path).map_err(|e| {+ format!(+ "CORE_PLUGIN_STALE_CORE_REMOVE_FAILED: {}: {e}",+ path.display()+ )+ })?;+ let file_type = metadata.file_type();+ #[cfg(windows)]+ let is_link = file_type.is_symlink() || file_type.is_symlink_dir();+ #[cfg(not(windows))]+ let is_link = file_type.is_symlink();+ if is_link {+ return remove_link_only(path);+ }+ let result = if file_type.is_dir() {+ std::fs::remove_dir_all(path)+ } else {+ std::fs::remove_file(path)+ };+ result.map_err(|e| {+ format!(+ "CORE_PLUGIN_STALE_CORE_REMOVE_FAILED: {}: {e}",+ path.display()+ )+ })+}+/// 从活动 profile 与应用内置清单收集需要在核心根下解析的包,并逐个建立入口。fn link_required_plugins(app_handle: &AppHandle, core_root: &Path) -> Result<(), String> {let core_node_modules = core_root.join("node_modules");@@ -739,6 +924,23 @@ fn is_safe_package_name(name: &str) -> bool {&& valid_package_component(parts[1])}+/// 是否属于核心家族(`@deepseek-ai/dsh` 或 `@deepseek-ai/dsh-*`)。+///+/// `dshmarket` 这类第三方插件虽在同一 scope 下,但既不是核心自带包也不是要清理的+/// 残留,必须排除;共享框架库(cordis、cosmokit、schemastery 等)同理由前缀天然排除。+fn is_core_family_package(name: &str) -> bool {+ let Some(package) = name+ .strip_prefix(CORE_PACKAGE_SCOPE)+ .and_then(|rest| rest.strip_prefix('/'))+ else {+ return false;+ };+ package == CORE_PACKAGE_PREFIX+ || package+ .strip_prefix(CORE_PACKAGE_PREFIX)+ .is_some_and(|suffix| suffix.starts_with('-'))+}+fn valid_package_component(value: &str) -> bool {!value.is_empty()&& value != "."@@ -767,6 +969,15 @@ fn read_package_name(path: &Path) -> Result<Option<String>, String> {.map(str::to_owned))}+fn read_package_version(path: &Path) -> Option<String> {+ let raw = std::fs::read_to_string(path).ok()?;+ let value = serde_json::from_str::<serde_json::Value>(&raw).ok()?;+ value+ .get("version")+ .and_then(|value| value.as_str())+ .map(str::to_owned)+}+/// 结论戳文件路径:放在依赖根下。清空依赖目录(等价于重新装配)会一并清掉它。fn native_probe_stamp_path(app_handle: &AppHandle) -> PathBuf {crate::config::get_base_dir(app_handle).join(NATIVE_PROBE_STAMP_FILE)@@ -1754,4 +1965,221 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}++ /// 档案里未被声明、且版本与安装锚点不一致的核心包必须被清掉——这正是+ /// 「未能保存设置,请重试。」的成因(旧世代 dsh-settings 抢在核心之前被解析)。+ #[test]+ fn stale_undeclared_core_package_is_pruned() {+ let root = std::env::temp_dir().join(format!("dsh-stale-core-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&root);+ let profile_modules = root.join("profiles/tauri/node_modules");+ let anchor_modules = root.join("dependencies/dsh/node_modules");++ write_package_version(&profile_modules, "dsh-settings", "0.1.5-rc.2");+ write_package_version(&anchor_modules, "dsh-settings", "0.1.7-rc.2");++ prune_stale_core_entries(+ &root.join("profiles/tauri"),+ &anchor_modules,+ &HashSet::new(),+ )+ .unwrap();++ assert!(+ !profile_modules+ .join("@deepseek-ai/dsh-settings/package.json")+ .exists(),+ "mismatched undeclared core package must be removed from the profile"+ );+ assert!(+ anchor_modules+ .join("@deepseek-ai/dsh-settings/package.json")+ .is_file(),+ "the anchor copy must never be touched"+ );++ let _ = std::fs::remove_dir_all(&root);+ }++ /// 版本与锚点一致的核心包是 pnpm hoisted 平铺的合法传递依赖,必须原样保留;+ /// 档案自己声明过的核心包同样不能动(哪怕是版本不一致)。+ #[test]+ fn matching_or_declared_core_packages_are_kept() {+ let root = std::env::temp_dir().join(format!("dsh-stale-core-keep-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&root);+ let profile_modules = root.join("profiles/tauri/node_modules");+ let anchor_modules = root.join("dependencies/dsh/node_modules");++ write_package_version(&profile_modules, "dsh-settings", "0.1.7-rc.2");+ write_package_version(&anchor_modules, "dsh-settings", "0.1.7-rc.2");+ write_package_version(&profile_modules, "dsh-tools", "0.1.5-rc.2");+ write_package_version(&anchor_modules, "dsh-tools", "0.1.7-rc.2");+ // 非核心 scope 与无 package.json 的条目都不在判定范围内。+ write_package_version(&root.join("other"), "dsh-settings", "0.1.5-rc.2");+ std::fs::create_dir_all(profile_modules.join("@deepseek-ai/dsh-orphan")).unwrap();++ let declared = HashSet::from(["@deepseek-ai/dsh-tools".to_string()]);+ prune_stale_core_entries(&root.join("profiles/tauri"), &anchor_modules, &declared).unwrap();++ assert!(+ profile_modules+ .join("@deepseek-ai/dsh-settings/package.json")+ .is_file(),+ "version-matching core package must be kept"+ );+ assert!(+ profile_modules+ .join("@deepseek-ai/dsh-tools/package.json")+ .is_file(),+ "declared core package must be kept"+ );+ assert!(+ profile_modules.join("@deepseek-ai/dsh-orphan").is_dir(),+ "entry without a readable version must be left alone"+ );+ assert!(+ root.join("other/@deepseek-ai/dsh-settings/package.json")+ .is_file(),+ "only the @deepseek-ai scope is inspected"+ );++ let _ = std::fs::remove_dir_all(&root);+ }++ /// 同 scope 下的共享框架库(插件可合法锁版本)与第三方插件 `dshmarket` 都不能+ /// 按「版本错配」误删,否则会直接弄坏插件。+ #[test]+ fn shared_framework_libraries_and_third_party_plugins_are_kept() {+ let root =+ std::env::temp_dir().join(format!("dsh-stale-core-scope-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&root);+ let profile_modules = root.join("profiles/tauri/node_modules");+ let anchor_modules = root.join("dependencies/dsh/node_modules");++ for name in ["schemastery", "cosmokit", "cordis", "dshmarket"] {+ write_package_version(&profile_modules, name, "0.1.5-rc.2");+ write_package_version(&anchor_modules, name, "0.1.7-rc.2");+ }++ prune_stale_core_entries(+ &root.join("profiles/tauri"),+ &anchor_modules,+ &HashSet::new(),+ )+ .unwrap();++ for name in ["schemastery", "cosmokit", "cordis", "dshmarket"] {+ assert!(+ profile_modules+ .join(format!("@deepseek-ai/{name}/package.json"))+ .is_file(),+ "{name} is outside the core family and must be kept"+ );+ }++ let _ = std::fs::remove_dir_all(&root);+ }++ /// 符号链接形态(残留在 `.dsh-module-fallback` 已消失时正是这种)也必须能删掉,+ /// 且只删入口、不动源目录。+ #[cfg(unix)]+ #[test]+ fn stale_core_package_symlink_is_removed_without_touching_source() {+ let root = std::env::temp_dir().join(format!("dsh-stale-core-link-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&root);+ let profile_modules = root.join("profiles/tauri/node_modules");+ let anchor_modules = root.join("dependencies/dsh/node_modules");+ let source = root.join("fallback/@deepseek-ai/dsh-settings");+ std::fs::create_dir_all(&source).unwrap();+ std::fs::write(source.join("package.json"), r#"{"version":"0.1.5-rc.2"}"#).unwrap();+ std::fs::create_dir_all(profile_modules.join("@deepseek-ai")).unwrap();+ std::os::unix::fs::symlink(&source, profile_modules.join("@deepseek-ai/dsh-settings"))+ .unwrap();+ write_package_version(&anchor_modules, "dsh-settings", "0.1.7-rc.2");++ prune_stale_core_entries(+ &root.join("profiles/tauri"),+ &anchor_modules,+ &HashSet::new(),+ )+ .unwrap();++ assert!(+ !profile_modules.join("@deepseek-ai/dsh-settings").exists(),+ "stale link must be removed"+ );+ assert!(+ source.join("package.json").is_file(),+ "the link source must survive"+ );++ let _ = std::fs::remove_dir_all(&root);+ }++ /// scope 目录本身被重定向时,宁可整轮不清,也不能顺着链接删到档案之外。+ #[cfg(unix)]+ #[test]+ fn redirected_scope_is_skipped_entirely() {+ let root =+ std::env::temp_dir().join(format!("dsh-stale-core-redirect-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&root);+ let profile_modules = root.join("profiles/tauri/node_modules");+ let anchor_modules = root.join("dependencies/dsh/node_modules");+ let outside = root.join("outside/@deepseek-ai");+ write_package_version(&root.join("outside"), "dsh-settings", "0.1.5-rc.2");+ write_package_version(&anchor_modules, "dsh-settings", "0.1.7-rc.2");+ std::fs::create_dir_all(&profile_modules).unwrap();+ std::os::unix::fs::symlink(&outside, profile_modules.join("@deepseek-ai")).unwrap();++ prune_stale_core_entries(+ &root.join("profiles/tauri"),+ &anchor_modules,+ &HashSet::new(),+ )+ .unwrap();++ assert!(+ outside.join("dsh-settings/package.json").is_file(),+ "a redirected scope must never be pruned through"+ );++ let _ = std::fs::remove_dir_all(&root);+ }++ /// `node_modules` 自身被重定向成一个外部目录时,包含锚点必须是档案目录,+ /// 否则外部目录会被当成「档案内部」而遭删除。+ #[cfg(unix)]+ #[test]+ fn redirected_node_modules_is_skipped_entirely() {+ let root = std::env::temp_dir().join(format!("dsh-stale-core-nm-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&root);+ let profile = root.join("profiles/tauri");+ let anchor_modules = root.join("dependencies/dsh/node_modules");+ let outside_modules = root.join("outside/node_modules");+ write_package_version(&outside_modules, "dsh-settings", "0.1.5-rc.2");+ write_package_version(&anchor_modules, "dsh-settings", "0.1.7-rc.2");+ std::fs::create_dir_all(&profile).unwrap();+ std::os::unix::fs::symlink(&outside_modules, profile.join("node_modules")).unwrap();++ prune_stale_core_entries(&profile, &anchor_modules, &HashSet::new()).unwrap();++ assert!(+ outside_modules+ .join("@deepseek-ai/dsh-settings/package.json")+ .is_file(),+ "an external node_modules must never be pruned through"+ );++ let _ = std::fs::remove_dir_all(&root);+ }++ fn write_package_version(modules: &Path, name: &str, version: &str) {+ let dir = modules.join("@deepseek-ai").join(name);+ std::fs::create_dir_all(&dir).unwrap();+ std::fs::write(+ dir.join("package.json"),+ format!(r#"{{"name":"@deepseek-ai/{name}","version":"{version}"}}"#),+ )+ .unwrap();+ }}diff --git a/src-tauri/src/service/plugin/installed.rs b/src-tauri/src/service/plugin/installed.rsindex 1b6d1dcf..31a5afa2 100644--- a/src-tauri/src/service/plugin/installed.rs+++ b/src-tauri/src/service/plugin/installed.rs@@ -46,14 +46,18 @@ pub(crate) fn profile_dir(app_handle: &AppHandle) -> PathBuf {/// 供「插件是否已安装」的单点判定([`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();- };+ declared_packages(app_handle).unwrap_or_default()+}- let Ok(manifest) = serde_json::from_str::<ProfilePackageJson>(&content) else {- return HashSet::new();- };+/// 档案清单声明的包名;清单缺失、不可读或结构不合法时返回 `None`。+///+/// 与 [`list_installed`] 的区别是区分「确实没有声明任何包」与「读不到声明」:+/// 删除类操作必须把后者当未知状态处理,否则一次解析失败会让所有已声明的包+/// 变成「未声明」,进而被误删。+pub(crate) fn declared_packages(app_handle: &AppHandle) -> Option<HashSet<String>> {+ let manifest_path = profile_dir(app_handle).join("package.json");+ let content = std::fs::read_to_string(&manifest_path).ok()?;+ let manifest = serde_json::from_str::<ProfilePackageJson>(&content).ok()?;let mut set: HashSet<String> = manifest.dependencies.into_keys().collect();if let Some(dsh) = manifest.dsh {@@ -61,7 +65,7 @@ pub(crate) fn list_installed(app_handle: &AppHandle) -> HashSet<String> {set.extend(profile.bundles);}}- set+ Some(set)}/// 插件是否仍被 profile 清单(`dependencies` / `dsh.profile.bundles`)引用。diff --git a/src-tauri/src/service/plugin/mod.rs b/src-tauri/src/service/plugin/mod.rsindex baac2f65..5f8dcf9b 100644--- a/src-tauri/src/service/plugin/mod.rs+++ b/src-tauri/src/service/plugin/mod.rs@@ -58,7 +58,9 @@ pub use install::{allow_policy_versions, allow_version_exemptions, install, remove, update, IncompatibleVersion,PolicyBlockedVersion,};-pub(crate) use installed::{ensure_profile_npmrc, installed_name, list_installed, profile_dir};+pub(crate) use installed::{+ declared_packages, 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;diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.jsonindex 8d76b2f8..6c5904c8 100644--- a/src/i18n/locales/en-US.json+++ b/src/i18n/locales/en-US.json@@ -345,9 +345,9 @@"core.local_unsupported_toast": "Local core is too old","core.local_unsupported_hint": "Built-in plugins need dsh {{version}} or newer, so the bundled core is used instead. Update the local core before switching back to it.","core.breaking_title": "Breaking changes",- "core.breaking_desc": "{{from}} → {{to}} has breaking changes that may break this profile's plugins and settings. Switch to a matching profile.",+ "core.breaking_desc": "{{from}} → {{to}} has breaking changes that may break this profile's plugins and settings. Switch to a matching profile; keeping the old profile leaves stale core packages behind, which breaks saving settings and needs manual repair.","core.breaking_profile_label": "Profile name",- "core.breaking_ignore": "Switch anyway",+ "core.breaking_ignore": "Keep old profile","core.breaking_profile_failed": "Failed to switch profile — the core was not switched","app.dev_env": "Development","app.config": "Running",diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.jsonindex cdfcdea1..f67a7e47 100644--- a/src/i18n/locales/zh-CN.json+++ b/src/i18n/locales/zh-CN.json@@ -345,9 +345,9 @@"core.local_unsupported_toast": "本地核心版本过低","core.local_unsupported_hint": "内置插件需要 dsh {{version}} 及以上,已自动改用预打包核心。请先更新本地核心,再切换回它。","core.breaking_title": "破坏性更改",- "core.breaking_desc": "{{from}} → {{to}} 含破坏性更改,可能破坏当前档案的插件与设置。请切换到配套档案。",+ "core.breaking_desc": "{{from}} → {{to}} 含破坏性更改,可能破坏当前档案的插件与设置。请切换到配套档案;继续沿用旧档案会残留旧版核心包,导致设置无法保存,需手动修复该档案。","core.breaking_profile_label": "档案名称",- "core.breaking_ignore": "无视风险切换",+ "core.breaking_ignore": "仍沿用旧档案","core.breaking_profile_failed": "切换档案失败,核心未切换","app.dev_env": "开发环境","app.config": "运行配置",