DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
fix(service): address CodeRabbit review comments from #210 (#211)
Mao Mrc53562657a1a
diff --git a/src-tauri/resources/internal-plugins.json b/src-tauri/resources/internal-plugins.jsonindex a83f7408..110ad3f8 100644--- a/src-tauri/resources/internal-plugins.json+++ b/src-tauri/resources/internal-plugins.json@@ -38,13 +38,5 @@"description": "Skills and MCP management in the DeepSeek Harness desktop extension panel.","repoUrl": "https://github.com/dsh-tauri-desk/dsh-tauri-plugins/tree/main/packages/dsh-tauri-panel-extension","recommended": true- },- {- "id": "dsh-tauri-session",- "spec": "dsh-tauri-session",- "name": "DSH Tauri Session",- "description": "Session archive for the desktop: rewrites the workspace browser's 'delete workspace' action into 'archive workspace', and adds an 'Archived chats' settings page with search, sort, grouping, project filter and unarchive.",- "repoUrl": "https://github.com/dsh-tauri-desk/dsh-tauri-plugins/tree/main/packages/dsh-tauri-session",- "recommended": true}]diff --git a/src-tauri/src/service/cli/path/mod.rs b/src-tauri/src/service/cli/path/mod.rsindex 22c509cb..7ed0457f 100644--- a/src-tauri/src/service/cli/path/mod.rs+++ b/src-tauri/src/service/cli/path/mod.rs@@ -136,8 +136,12 @@ pub fn register_path(app_handle: &AppHandle) -> Result<(), String> {let bin_dir = get_bin_dir(app_handle);let bin_str = bin_dir.to_str()- .ok_or_else(|| "bin dir is not valid UTF-8".to_string())?;- let current = read_user_path().unwrap_or_default();+ .ok_or_else(|| "PATH_BIN_DIR_NOT_UTF8: bin dir is not valid UTF-8".to_string())?;+ // 注册表读取失败(None)时中止,绝不把失败当成空 PATH 写回(那会清空+ // 用户 PATH 其它条目);`Path` 值缺失(ERROR_FILE_NOT_FOUND)返回的+ // Some("") 才按空串处理。+ let current = read_user_path()+ .ok_or_else(|| "PATH_REG_READ_FAILED: failed to read user PATH".to_string())?;let new_value = if current.trim().is_empty() {bin_str.to_string()} else {diff --git a/src-tauri/src/service/cli/path/rc.rs b/src-tauri/src/service/cli/path/rc.rsindex 27d4600a..8ff2b09d 100644--- a/src-tauri/src/service/cli/path/rc.rs+++ b/src-tauri/src/service/cli/path/rc.rs@@ -28,7 +28,7 @@ pub(super) fn inject_shell_rc(app_handle: &AppHandle) -> Result<(), String> {let home = app_handle.path().home_dir()- .map_err(|_| "failed to resolve home directory".to_string())?;+ .map_err(|_| "RC_HOME_RESOLVE_FAILED: failed to resolve home directory".to_string())?;let block = format!("{RC_MARK_START}\nexport PATH=\"$HOME/.local/bin:$PATH\"\n{RC_MARK_END}\n");for name in RC_FILES {@@ -59,7 +59,7 @@ pub(super) fn strip_shell_rc(app_handle: &AppHandle) -> Result<(), String> {let home = app_handle.path().home_dir()- .map_err(|_| "failed to resolve home directory".to_string())?;+ .map_err(|_| "RC_HOME_RESOLVE_FAILED: failed to resolve home directory".to_string())?;for name in RC_FILES {let rc_path = home.join(name);let original = match fs::read_to_string(&rc_path) {diff --git a/src-tauri/src/service/cli/path/registry.rs b/src-tauri/src/service/cli/path/registry.rsindex 383c3b90..31be8fdc 100644--- a/src-tauri/src/service/cli/path/registry.rs+++ b/src-tauri/src/service/cli/path/registry.rs@@ -1,7 +1,7 @@//! Windows 注册表辅助:`HKCU\Environment\Path` 读写、`WM_SETTINGCHANGE` 广播//! 与 PATH token 展开/匹配。仅 Windows 编译(`mod registry` 已在 mod.rs 门控)。-/// Windows 下 shim 根目录名(`%LOCALAPPDATA%\<此目录>\bin`)+/// 将 Rust 字符串转为 Win32 API 需要的 NUL 结尾 UTF-16 缓冲#[inline]pub(super) fn to_wide_null(s: &str) -> Vec<u16> {s.encode_utf16().chain(std::iter::once(0)).collect()@@ -87,7 +87,9 @@ pub(super) fn write_user_path(new_value: &str) -> Result<(), String> {&mut hkey,);if ret != 0 {- return Err(format!("failed to open HKCU\\Environment (error {ret})"));+ return Err(format!(+ "REG_OPEN_FAILED: failed to open HKCU\\Environment (error {ret})"+ ));}let value_name = to_wide_null("Path");@@ -119,7 +121,7 @@ pub(super) fn write_user_path(new_value: &str) -> Result<(), String> {if ret != 0 {return Err(format!(- "failed to write HKCU\\Environment\\Path (error {ret})"+ "REG_WRITE_FAILED: failed to write HKCU\\Environment\\Path (error {ret})"));}Ok(())diff --git a/src-tauri/src/service/cli/shim/write.rs b/src-tauri/src/service/cli/shim/write.rsindex a2d9213f..ea48cdba 100644--- a/src-tauri/src/service/cli/shim/write.rs+++ b/src-tauri/src/service/cli/shim/write.rs@@ -44,13 +44,20 @@ fn is_dangling_symlink(path: &Path) -> bool {}}-/// 判断路径是否为本应用生成的 shim(内容含生成标记)。+/// 判断路径是否为本应用生成的 shim(生成标记出现在文件头部固定位置)。////// 用于在本地 dsh 探测中区分"本应用 shim"与"用户自行放置的同名文件":/// 前者应被排除(它转发到捆绑 dsh,不构成用户本地核心),后者应被识别。+///+/// 标记只在前两行匹配:所有生成的 shim 都在头部第一行(cmd 是 @echo off+/// 后的第二行)写 #/rem DeepSeek Harness Desktop - ...;用户文件即使正文+/// 提到同样的短语(如 README 引用)也不应被误判为本应用 shim。pub fn is_generated_shim(path: &Path) -> bool {match std::fs::read_to_string(path) {- Ok(content) => content.contains(GENERATED_MARKER),+ Ok(content) => content+ .lines()+ .take(2)+ .any(|line| line.contains(GENERATED_MARKER)),Err(_) => false,}}@@ -66,8 +73,12 @@ fn write_shim_file(target: &Path, content: &str) -> Result<(), String> {"Removing dangling symlink {:?} before writing shim (its target is gone)",target);- fs::remove_file(target)- .map_err(|e| format!("remove dangling symlink {} failed: {e}", target.display()))?;+ fs::remove_file(target).map_err(|e| {+ format!(+ "SHIM_REMOVE_LINK_FAILED: remove dangling symlink {} failed: {e}",+ target.display()+ )+ })?;}if target.exists() && is_foreign_file(target) {log::warn!(@@ -76,7 +87,8 @@ fn write_shim_file(target: &Path, content: &str) -> Result<(), String> {);return Ok(());}- fs::write(target, content).map_err(|e| format!("write {} failed: {e}", target.display()))+ fs::write(target, content)+ .map_err(|e| format!("SHIM_WRITE_FAILED: write {} failed: {e}", target.display()))}/// 主 `dsh` shim 路径下是否保留了用户自行安装的同名文件(用于状态展示)。@@ -102,7 +114,8 @@ pub fn user_dsh_preserved(bin_dir: &Path) -> bool {/// 同名 `dsh`/`pnpm` 一律保留不动,避免覆盖用户自己的安装与配置。pub fn write_shims(app_handle: &AppHandle, bin_dir: &Path) -> Result<(), String> {let app_dir = config::get_base_dir(app_handle);- fs::create_dir_all(bin_dir).map_err(|e| format!("create bin dir failed: {e}"))?;+ fs::create_dir_all(bin_dir)+ .map_err(|e| format!("SHIM_MKDIR_FAILED: create bin dir failed: {e}"))?;// 写入单个 shim:若目标已存在且非本应用生成,则跳过不覆盖(保留用户文件)。macro_rules! write_if_ours {@@ -154,7 +167,7 @@ pub fn write_shims(app_handle: &AppHandle, bin_dir: &Path) -> Result<(), String>if path.is_file() && !is_foreign_file(&path) {use std::os::unix::fs::PermissionsExt;fs::set_permissions(&path, fs::Permissions::from_mode(0o755))- .map_err(|e| format!("chmod shim failed: {e}"))?;+ .map_err(|e| format!("SHIM_CHMOD_FAILED: chmod shim failed: {e}"))?;}}}@@ -271,6 +284,27 @@ mod tests {let _ = std::fs::remove_dir_all(&dir);}+ /// 用户文件只在正文提到生成短语(非头部)→ 仍视为 foreign,不得覆盖+ #[test]+ fn generated_phrase_outside_header_is_not_generated_shim() {+ let dir =+ std::env::temp_dir().join(format!("dsh-shim-header-marker-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ let target = dir.join(if cfg!(windows) { "dsh.cmd" } else { "dsh" });+ // 前两行不是标记(用户脚本),正文(第三行)却提到"DeepSeek Harness Desktop - "+ std::fs::write(+ &target,+ "@echo off\necho user shim\necho see DeepSeek Harness Desktop - readme note here\n",+ )+ .unwrap();+ assert!(+ is_foreign_file(&target),+ "phrase outside the header must not mark a user file as generated"+ );+ let _ = std::fs::remove_dir_all(&dir);+ }+/// 本应用生成的 shim → 覆盖自愈内容#[test]fn write_shim_file_overwrites_generated_shim() {diff --git a/src-tauri/src/service/download/github.rs b/src-tauri/src/service/download/github.rsindex 1ce0ef1a..78e53e7d 100644--- a/src-tauri/src/service/download/github.rs+++ b/src-tauri/src/service/download/github.rs@@ -299,20 +299,32 @@ pub async fn fetch_dsh_pkg_asset(tag: &str) -> Result<LatestDshPkg, String> {.ok_or_else(|| "Missing DSH asset filename".to_string())?.to_string();- // 1. 优先 API 拉该 tag 的 release(含资产 + 可信摘要)- let release = github_api_get(+ // 1. 优先 API 拉该 tag 的 release(含资产 + 可信摘要);API 失败/限流或响应+ // 不可解析时不整体失败:资产 URL 回退到平台确定性推导(latest 地址的+ // tag 位替换)、摘要走 expanded_assets HTML(github.com,不受未认证限流+ // 约束),保证按版本下载不因一次 API 错误而中断。+ let json: Option<serde_json::Value> = match github_api_get(&client,&format!("{DSH_PKG_GITHUB_API}/releases/tags/{tag}"),).await- .map_err(|e| format!("Release {tag} request failed: {e}"))?;- let json: serde_json::Value = release- .json()- .await- .map_err(|e| format!("Failed to parse release {tag} response: {e}"))?;+ {+ Ok(release) => match release.json().await {+ Ok(json) => Some(json),+ Err(e) => {+ log::warn!("Failed to parse release {tag} response: {e}");+ None+ }+ },+ Err(e) => {+ log::warn!("Release {tag} request failed ({e}), using deterministic asset URL");+ None+ }+ };let asset = json- .get("assets")+ .as_ref()+ .and_then(|json| json.get("assets")).and_then(|value| value.as_array()).and_then(|assets| {assets.iter().find(|asset| {@@ -439,7 +451,16 @@ pub fn resolve_update(// 不能先看 commit 相等就跳过:dsh 仓库的 rc 发布可能重打同一 git commit// (build-id 不同但 underlying commit 相同),此时 commit 不是可分辨信号,// 只有 tag 里的版本号才能正确识别 rc.8 之于 rc.7 是更新。- if installed != latest_version {+ // 版本号按语义化比较:字符串序会把 rc.9 误判为大于 rc.10('9' > '1')。+ let same_version = match (+ semver::Version::parse(installed).ok(),+ semver::Version::parse(&latest_version).ok(),+ ) {+ (Some(installed), Some(latest)) => installed == latest,+ // 任一无法解析 → 回退字符串比较(保持旧行为)+ _ => installed == latest_version,+ };+ if !same_version {return UpdateCheck::UpdateAvailable;}// 版本相同 → 确认是否「同一发布」再判免打扰:记录与最新 release 对应@@ -447,16 +468,25 @@ pub fn resolve_update(if record_matches_latest_release(record_commit, record_tag, latest) {return UpdateCheck::UpToDate;}- // 文件已经是“最新版本”,此时需要甄别记录是否滞后+ // 文件已经是“最新版本”,此时需要甄别记录是否滞后(同样按语义化版本比较)+ let record_behind_latest = |record_version: &str| -> bool {+ match (+ semver::Version::parse(record_version).ok(),+ semver::Version::parse(&latest_version).ok(),+ ) {+ (Some(record), Some(latest)) => record < latest,+ _ => record_version < latest_version.as_str(),+ }+ };match record_tag.and_then(parse_version_from_tag) {- Some(record_version) if record_version < latest_version => UpdateCheck::HealUpToDate,+ Some(record_version) if record_behind_latest(&record_version) => UpdateCheck::HealUpToDate,Some(_) => UpdateCheck::UpdateAvailable,None => match legacy_tags.iter().find(|(_, commit)| Some(commit.as_str()) == record_commit){Some((tag, _)) => match parse_version_from_tag(tag) {- Some(record_version) if record_version < latest_version => {+ Some(record_version) if record_behind_latest(&record_version) => {UpdateCheck::HealUpToDate}// 反查到的版本与最新版本相同(或解析失败)→ 视为同版本热修@@ -759,4 +789,22 @@ mod tests {);assert_eq!(decision, UpdateCheck::UpdateAvailable);}++ #[test]+ fn resolve_rc9_record_behind_rc10_heals() {+ // 回归(CodeRabbit):字符串序会把 rc.9 判为大于 rc.10('9' > '1'),+ // 从而把「记录滞后于 rc.10」误判成同版本热修。语义化比较应识别为滞后。+ let latest = latest(+ "dsh-0.1.0-rc.10-40000000000",+ "aabbccddeeff00112233445566778899aabbccdd",+ );+ let decision = resolve_update(+ Some("112233445566778899aabbccddeeff0011223344"),+ Some("dsh-0.1.0-rc.9-39000000000"),+ Some("0.1.0-rc.10"),+ &latest,+ &[],+ );+ assert_eq!(decision, UpdateCheck::HealUpToDate);+ }}diff --git a/src-tauri/src/service/download/installable.rs b/src-tauri/src/service/download/installable.rsindex a310aee8..c2be6ee5 100644--- a/src-tauri/src/service/download/installable.rs+++ b/src-tauri/src/service/download/installable.rs@@ -3,8 +3,19 @@ use async_trait::async_trait;use std::path::PathBuf;use tauri::AppHandle;+/// 安装任务的类型标识:下载源选择、完整性校验与版本记录都按它分支,+/// 而不是按任务在 `tasks` 向量里的位置索引(重排向量不应改变行为)。+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum InstallKind {+ Node,+ Dsh,+ Pnpm,+ Git,+}+#[async_trait]pub trait Installable: Send + Sync {+ fn kind(&self) -> InstallKind;fn title(&self) -> &str;fn check_installed(&self, app: &AppHandle) -> bool;fn get_download_url(&self) -> Result<String, String>;@@ -16,6 +27,9 @@ pub struct Nodejs;#[async_trait]impl Installable for Nodejs {+ fn kind(&self) -> InstallKind {+ InstallKind::Node+ }fn title(&self) -> &str {"运行环境"}@@ -42,6 +56,9 @@ pub struct Dsh;#[async_trait]impl Installable for Dsh {+ fn kind(&self) -> InstallKind {+ InstallKind::Dsh+ }fn title(&self) -> &str {"Harness 核心"}@@ -61,6 +78,9 @@ pub struct Pnpm;#[async_trait]impl Installable for Pnpm {+ fn kind(&self) -> InstallKind {+ InstallKind::Pnpm+ }fn title(&self) -> &str {"pnpm 包管理器"}@@ -87,6 +107,9 @@ pub struct Git;#[cfg(windows)]#[async_trait]impl Installable for Git {+ fn kind(&self) -> InstallKind {+ InstallKind::Git+ }fn title(&self) -> &str {"Git 环境"}diff --git a/src-tauri/src/service/download/mod.rs b/src-tauri/src/service/download/mod.rsindex c15f82d1..b57e5023 100644--- a/src-tauri/src/service/download/mod.rs+++ b/src-tauri/src/service/download/mod.rs@@ -17,7 +17,7 @@ pub use github::{pub(crate) use core::{remove_dir_with_retry, rename_with_retry};#[cfg(windows)]pub use installable::Git;-pub use installable::{Dsh, Installable, Nodejs, Pnpm};+pub use installable::{Dsh, InstallKind, Installable, Nodejs, Pnpm};pub use progress::ProgressTracker;// GitHub API 限流冷却器:任何访问 api.github.com 的服务都应收敛到这一个入口pub use utils::github_api;diff --git a/src-tauri/src/service/patch/session.rs b/src-tauri/src/service/patch/session.rsindex a50c6191..230659fe 100644--- a/src-tauri/src/service/patch/session.rs+++ b/src-tauri/src/service/patch/session.rs@@ -1,7 +1,8 @@-//! Adds the missing public SessionStore removal primitive to the bundled DSH.+//! 为捆绑的 DSH 补齐缺失的公开 SessionStore 移除原语。//!-//! The upstream store already owns the exact detach lifecycle; this patch only-//! exposes a narrow id-based facade for desktop plugins to use safely.+//! 上游 store 已持有完整的 detach 生命周期;本补丁只暴露一个窄的、按 id 的+//! 门面(facade),供桌面端插件安全地执行真正的内存内销毁,而不是让被删会话+//! 残留在未分组状态。use crate::utils::{patch_dsh, PatchOutcome};diff --git a/src-tauri/src/service/plugin/install/artifact.rs b/src-tauri/src/service/plugin/install/artifact.rsindex 9a3f22e0..88ca73ee 100644--- a/src-tauri/src/service/plugin/install/artifact.rs+++ b/src-tauri/src/service/plugin/install/artifact.rs@@ -75,13 +75,12 @@ fn silent_install_failure_detail(missing: &[(String, PathBuf)], command_output:)}-/// 构建 `dsh plugin` 子进程的环境变量:隔离 $DSH_HOME、关闭遥测与颜色、-/// 注入预检解析出的 node 路径(`DSH_NODE`,shim 优先采用,见 shim.rs)、-/// PATH 前置 shim、node 与桌面端自动配置的 Git 目录;用户 pnpm 过旧时强制-/// 捆绑版(见 ensure_pnpm)。-///-/// 供本模块的安装/升级/卸载与 [`super::verify`] 的完整性修复共用:子进程(dsh-+/// 解析插件包声明的主入口(与 cordis 加载器实际读取的字段一致):+/// 优先 `dsh.plugin.json` 的 `main`(加载器入口,见 loader 报错路径),+/// 回落 `package.json` 的 `main` / `exports["."]`(字符串简写 → 对象+/// `default` → `import` → `require`)。+/// 仅负责解析声明,不校验产物是否存在;入口越界(`../` 逃逸/绝对路径)+/// 或无可解析入口时返回 None。fn declared_main_entry(pkg_dir: &Path) -> Option<PathBuf> {/// 拼接声明入口并拒绝越界:绝对路径会被 `join` 整体替换基路径,`../`/// 逃逸在 `starts_with` 的词法比较下不会被解析——两者都会让核验目标指向@@ -316,8 +315,7 @@ mod tests {assert!(!detail.contains("produced no output"));}- /// 验证最终重试无输出时,早期尝试产生的诊断不会被覆盖丢失。-+ /// 构造独立的临时插件包目录(含 `package.json`),供入口解析用例使用。fn tmp_pkg_dir(name: &str) -> PathBuf {let dir =std::env::temp_dir().join(format!("dsh-entry-test-{name}-{}", std::process::id()));diff --git a/src-tauri/src/service/plugin/install/diagnose.rs b/src-tauri/src/service/plugin/install/diagnose.rsindex dbcd6351..826e9875 100644--- a/src-tauri/src/service/plugin/install/diagnose.rs+++ b/src-tauri/src/service/plugin/install/diagnose.rs@@ -2,9 +2,7 @@//! (HTTPS→SSH 回退提示),并从输出中挑选可展示的错误消息(ANSI 清洗、//! 命中错误标记的行优先、截断)。-/// 从 dsh/pnpm 失败输出中提取可展示的错误消息:优先 git 传输层提示;-/// 否则挑出命中错误标记的行(最多 8 行),没有则取输出尾部,ANSI 清洗后-/// 截断到 2000 字符。+/// 给非空诊断文本加 `: ` 前缀,便于直接拼进错误消息(空文本返回空串)。pub(super) fn diagnostic_suffix(detail: &str) -> String {if detail.is_empty() {String::new()@@ -13,6 +11,9 @@ pub(super) fn diagnostic_suffix(detail: &str) -> String {}}+/// 从 dsh/pnpm 失败输出中提取可展示的错误消息:优先 git 传输层提示;+/// 否则挑出命中错误标记的行(最多 8 行),没有则取输出尾部,ANSI 清洗后+/// 截断到 2000 字符。pub(super) fn pick_error_message(output: &str, hint: Option<&str>) -> String {if let Some(hint) = hint {return hint.to_string();diff --git a/src-tauri/src/service/plugin/install/env.rs b/src-tauri/src/service/plugin/install/env.rsindex 67368990..815bf947 100644--- a/src-tauri/src/service/plugin/install/env.rs+++ b/src-tauri/src/service/plugin/install/env.rs@@ -131,10 +131,10 @@ fn git_https_isolation_env(app_handle: &AppHandle) -> HashMap<String, String> {/// 解析插件子进程将使用的 git 可执行文件:Windows 用桌面端已选 Git(系统 Git 或/// 捆绑 MinGit,见 [`config::get_git_cmd_dir`],与注入子进程 PATH 的目录一致),/// Unix 直接用 PATH 上的 `git`。-fn plugin_git_binary(app_handle: &AppHandle) -> Option<PathBuf> {+fn plugin_git_binary(_app_handle: &AppHandle) -> Option<PathBuf> {#[cfg(windows)]{- config::get_git_cmd_dir(app_handle).map(|dir| dir.join("git.exe"))+ config::get_git_cmd_dir(_app_handle).map(|dir| dir.join("git.exe"))}#[cfg(not(windows))]{diff --git a/src-tauri/src/service/plugin/install/mod.rs b/src-tauri/src/service/plugin/install/mod.rsindex 8f605f94..5ac9d9ca 100644--- a/src-tauri/src/service/plugin/install/mod.rs+++ b/src-tauri/src/service/plugin/install/mod.rs@@ -244,7 +244,8 @@ async fn install_with_cancel(line: format!("[network] {network_hint}"),},);- return Err(format!("NETWORK_ERROR: {network_hint}"));+ // network_hint 已带 NETWORK_ERROR: 前缀,直接返回避免双重前缀+ return Err(network_hint.to_string());}if let Some(hint) = hint {log::warn!("git transport failure detected during plugin install: {hint}");diff --git a/src-tauri/src/service/plugin/install/pnpm.rs b/src-tauri/src/service/plugin/install/pnpm.rsindex ef89d7ab..27843b22 100644--- a/src-tauri/src/service/plugin/install/pnpm.rs+++ b/src-tauri/src/service/plugin/install/pnpm.rs@@ -634,13 +634,10 @@ pub(crate) fn bundled_pnpm_major(app_handle: &AppHandle) -> Option<u32> {.ok()}-/// 从 pnpm 失败输出中解析需写入构建放行白名单的包名/键集合。-///-/// 兼容 pnpm 10 与 11 的两套输出形式(两者对 git 托管插件 prepare 门禁的提示不同):-/// - pnpm 11(捆绑版)提示 `allowBuilds:\n <key>: true`(map 形式),原样采纳 `<key>`;-/// - pnpm 10(旧 store 复用用户版)提示 `onlyBuiltDependencies:\n - "<name>"`-/// (list 形式)与报错文本里的包名,二者归并取包名;-+/// 服务启动阶段的 `DSH_PREFER_BUNDLED_PNPM` 决策:store 主版本已知时只在捆绑版+/// 匹配且用户版不匹配时强制捆绑版(否则用户版会 `ERR_PNPM_UNEXPECTED_STORE`);+/// store 未知时用户 pnpm ≥ 10 优先,否则强制捆绑版。启动阶段绝不触发下载,+/// 捆绑版未安装即返回 false(交由用户 pnpm)。pub(crate) fn harness_prefer_bundled_pnpm(app_handle: &AppHandle) -> bool {let store_major = profile_store_major(app_handle);let user_major = user_pnpm_major_version(app_handle);diff --git a/src-tauri/src/service/plugin/install/single.rs b/src-tauri/src/service/plugin/install/single.rsindex 719bd8ff..5ad3d2bb 100644--- a/src-tauri/src/service/plugin/install/single.rs+++ b/src-tauri/src/service/plugin/install/single.rs@@ -67,6 +67,11 @@ pub async fn remove(app_handle: &AppHandle, id: &str) -> Result<(), String> {"dsh plugin remove {outcome} but {id} is still referenced by profile manifest; forcing offline uninstall");uninstall_recovery(app_handle, id)?;+ // 离线兜底成功:插件已真正从 profile 移除,清除历史错误,避免前端+ // 残留异常标记(best-effort)。+ if let Err(e) = errors::clear(app_handle, id) {+ log::warn!("failed to clear plugin error for {id}: {e}");+ }} else {// 受保护包:命令失败则如实上报(不要把失败误报为成功),成功则仅告警。command_result?;@@ -129,7 +134,10 @@ pub(crate) async fn uninstall_deprecated_plugins(app_handle: &AppHandle) -> Resuif failures.is_empty() {Ok(())} else {- Err(failures.join("; "))+ Err(format!(+ "DEPRECATED_PLUGIN_UNINSTALL_FAILED: {}",+ failures.join("; ")+ ))}}diff --git a/src-tauri/src/service/plugin/install/spec.rs b/src-tauri/src/service/plugin/install/spec.rsindex 88f7ed2e..23064786 100644--- a/src-tauri/src/service/plugin/install/spec.rs+++ b/src-tauri/src/service/plugin/install/spec.rs@@ -21,7 +21,8 @@ pub(super) fn bundled_dir_of(}/// 解析某预设的安装 spec(纯函数,便于单测):内置插件固定为随包捆绑目录的-/// `file:` 本地依赖(路径正确性由 [`crate::service::plugin::internal::ensure`] 启动自愈核对);+/// `link:` 本地依赖(pnpm 对 `file:` 的盘符绝对路径会按相对解析,故用 `link:`;+/// 路径正确性由 [`crate::service::plugin::internal::ensure`] 启动自愈核对);/// 普通插件沿用清单声明。////// 捆绑目录缺失时返回错误:内置插件缺失意味着构建期 prebuild 未执行或产物被diff --git a/src-tauri/src/service/plugin/internal/manifest.rs b/src-tauri/src/service/plugin/internal/manifest.rsindex 4d896a2f..46c3c6ae 100644--- a/src-tauri/src/service/plugin/internal/manifest.rs+++ b/src-tauri/src/service/plugin/internal/manifest.rs@@ -62,10 +62,7 @@ pub(super) fn write_profile_manifest(let _ = std::fs::remove_file(&temp);return Err(format!("INTERNAL_PLUGIN_MANIFEST_WRITE_FAILED: {e}"));}- log::info!(- "Removed stale internal plugin declarations from profile manifest: {}",- path.display()- );+ log::info!("Profile manifest rewritten: {}", path.display());Ok(())}diff --git a/src-tauri/src/service/plugin/recovery/extract.rs b/src-tauri/src/service/plugin/recovery/extract.rsindex 33ebd643..cef40108 100644--- a/src-tauri/src/service/plugin/recovery/extract.rs+++ b/src-tauri/src/service/plugin/recovery/extract.rs@@ -2,13 +2,13 @@use regex::Regex;use std::collections::HashSet;+use std::sync::LazyLock;use super::is_actionable_plugin_ref;-/// 从日志文本中提取插件引用(多个错误特征的正则,去重)。-pub(super) fn extract_plugin_refs(text: &str) -> Vec<String> {- let mut refs = HashSet::new();- let patterns = [+/// 插件引用提取模式(编译一次复用,避免每次 `detect` 都重新编译正则)。+static PLUGIN_REF_PATTERNS: LazyLock<Vec<Regex>> = LazyLock::new(|| {+ [// failed to apply/import loader entry <name> (<pkg>)r#"failed to (?:apply|import) loader entry[^\n]*\(([^)]+)\)"#,// cannot resolve profile bundle "<pkg>"@@ -17,24 +17,40 @@ pub(super) fn extract_plugin_refs(text: &str) -> Vec<String> {r#"profile bundle\s+["']?([^"'\n]+)["']?\s+declares no dsh\.bundle"#,// plugin(s) failed to load: <pkg>r#"plugins? failed to load:\s*([A-Za-z0-9@/_.\-]+)"#,- ];- for pattern in patterns {- if let Ok(re) = Regex::new(pattern) {- for cap in re.captures_iter(text) {- if let Some(m) = cap.get(1) {- let cand = m.as_str().trim();- if is_actionable_plugin_ref(cand) {- refs.insert(cand.to_string());- }+ ]+ .iter()+ .map(|p| Regex::new(p).expect("static plugin ref pattern"))+ .collect()+});++/// 「Failed to load plugins」错误卡片定位(紧随其后的若干行通常是包名)。+static RE_FAILED_TO_LOAD_PLUGINS: LazyLock<Regex> =+ LazyLock::new(|| Regex::new(r"(?m)^Failed to load plugins\s*$").expect("literal"));++/// 重复前缀路由(classify_reason 用)。+static RE_DUP_PREFIX_ROUTE: LazyLock<Regex> =+ LazyLock::new(|| Regex::new(r#"duplicate prefix route\s+["']([^"']+)["']"#).expect("literal"));++/// 无法解析 profile bundle(classify_reason 用)。+static RE_CANNOT_RESOLVE_BUNDLE: LazyLock<Regex> = LazyLock::new(|| {+ Regex::new(r#"cannot resolve profile bundle\s+["']?([^"'\n]+)["']?"#).expect("literal")+});++/// 从日志文本中提取插件引用(多个错误特征的正则,去重)。+pub(super) fn extract_plugin_refs(text: &str) -> Vec<String> {+ let mut refs = HashSet::new();+ for re in PLUGIN_REF_PATTERNS.iter() {+ for cap in re.captures_iter(text) {+ if let Some(m) = cap.get(1) {+ let cand = m.as_str().trim();+ if is_actionable_plugin_ref(cand) {+ refs.insert(cand.to_string());}}}}// 「Failed to load plugins」错误卡片:紧随其后的若干行通常是包名。- for m in Regex::new(r"(?m)^Failed to load plugins\s*$")- .expect("literal")- .find_iter(text)- {+ for m in RE_FAILED_TO_LOAD_PLUGINS.find_iter(text) {let rest = &text[m.end()..];for line in rest.lines().take(12) {let cand = line.trim().trim_end_matches(['.', ',', ' ']);@@ -68,21 +84,18 @@ pub(super) fn extract_slot_conflict(text: &str) -> Option<String> {/// 对日志文本分类失败原因,返回(判别键, 动态详情)。pub(super) fn classify_reason(text: &str) -> (String, String) {- let dup_route = Regex::new(r#"duplicate prefix route\s+["']([^"']+)["']"#).expect("literal");- if let Some(c) = dup_route.captures(text) {+ if let Some(c) = RE_DUP_PREFIX_ROUTE.captures(text) {let route = c.get(1).map(|m| m.as_str().to_string()).unwrap_or_default();return ("duplicate_route".into(), route);}if let Some(entry) = extract_duplicate_loader_entry(text) {return ("duplicate_loader_entry".into(), entry);}- if let Some(re) = Regex::new(r#"cannot resolve profile bundle\s+["']?([^"'\n]+)["']?"#).ok() {- if let Some(c) = re.captures(text) {- return (- "cannot_resolve_bundle".into(),- c.get(1).map(|m| m.as_str().to_string()).unwrap_or_default(),- );- }+ if let Some(c) = RE_CANNOT_RESOLVE_BUNDLE.captures(text) {+ return (+ "cannot_resolve_bundle".into(),+ c.get(1).map(|m| m.as_str().to_string()).unwrap_or_default(),+ );}if text.contains("declares no dsh.bundle") {let pkg = extract_plugin_refs(text)diff --git a/src-tauri/src/service/plugin/recovery/mod.rs b/src-tauri/src/service/plugin/recovery/mod.rsindex e65760a0..f66e81d4 100644--- a/src-tauri/src/service/plugin/recovery/mod.rs+++ b/src-tauri/src/service/plugin/recovery/mod.rs@@ -43,10 +43,11 @@ pub(crate) const RECOVERY_REQUIRED_EVENT: &str = "plugin-recovery-required";/// 卸载。若把它列入保护名单,用户从插件面板点「卸载」时,`dsh plugin remove`/// 因 dshmarket 属于 in-box bundle(`pnpm remove` 不动它)会返回成功但插件仍在,/// 桌面端又因 protection 跳过离线卸载兜底,最终「提示成功但插件仍在」。+///+/// `@deepseek-ai/dsh-base` / `@deepseek-ai/dsh-web-app` 等核心包都被+/// `@deepseek-ai/` 前缀覆盖,无需逐个点名。fn is_core_package(name: &str) -> bool {- name == "@deepseek-ai/dsh-base"- || name == "@deepseek-ai/dsh-web-app"- || name.starts_with("@deepseek-ai/")+ name.starts_with("@deepseek-ai/")}/// 是否为合法的 npm 包名(可带 scope)。用于过滤日志里提取到的候选引用。diff --git a/src-tauri/src/service/plugin/recovery/ownership.rs b/src-tauri/src/service/plugin/recovery/ownership.rsindex 2dcda94e..4f0b3729 100644--- a/src-tauri/src/service/plugin/recovery/ownership.rs+++ b/src-tauri/src/service/plugin/recovery/ownership.rs@@ -143,14 +143,26 @@ fn plugin_declares_loader_entry(profile: &Path, plugin: &str, entry_id: &str) ->}/// 判断某个根插件的文件是否包含给定槽位名。+///+/// `package.json` 不做整文件子串匹配:description / 依赖名里出现槽位短名+/// (如 `sidebar`)会造成误归属;只解析它并在 `dsh` 声明段里递归匹配槽位,+/// 无 `dsh` 段即不命中。其余文件保持内容匹配。fn plugin_matches_slot(profile: &Path, plugin: &str, slot: &str) -> bool {let dir = profile.join("node_modules").join(plugin);+ if let Ok(content) = fs::read_to_string(dir.join("package.json")) {+ if let Ok(manifest) = serde_json::from_str::<serde_json::Value>(&content) {+ if let Some(dsh) = manifest.get("dsh") {+ if value_contains_slot(dsh, slot) {+ return true;+ }+ }+ }+ }for file in ["cordis.patch.yml","client.js","lib/client.js","dist/client.js",- "package.json","index.js","lib/index.js","dist/index.js",@@ -164,6 +176,16 @@ fn plugin_matches_slot(profile: &Path, plugin: &str, slot: &str) -> bool {false}+/// `dsh` 声明段里是否包含槽位名(递归扫描所有字符串值)。+fn value_contains_slot(value: &serde_json::Value, slot: &str) -> bool {+ match value {+ serde_json::Value::String(s) => s.contains(slot),+ serde_json::Value::Array(items) => items.iter().any(|v| value_contains_slot(v, slot)),+ serde_json::Value::Object(map) => map.values().any(|v| value_contains_slot(v, slot)),+ _ => false,+ }+}+/// 提供某槽位的官方 UI 客户端包(用于槽位冲突归属)。fn packages_providing_slot(profile: &Path, slot: &str) -> Vec<String> {let scope = profile.join("node_modules").join("@deepseek-ai");diff --git a/src-tauri/src/service/plugin/recovery/uninstall.rs b/src-tauri/src/service/plugin/recovery/uninstall.rsindex eebdcb1d..dbdaff0e 100644--- a/src-tauri/src/service/plugin/recovery/uninstall.rs+++ b/src-tauri/src/service/plugin/recovery/uninstall.rs@@ -35,7 +35,8 @@ pub(super) fn remove_plugin_from_manifest(manifest: &mut serde_json::Value, id:modified}-/// 删除插件入口:符号链接或 junction 只删除入口本身,普通目录递归删除。+/// 删除插件入口:符号链接或 junction 只删除入口本身;普通目录递归删除,+/// 普通文件用 `remove_file`(`remove_dir_all` 对文件会报 ENOTDIR)。fn remove_plugin_entry(entry: &Path) -> std::io::Result<()> {let file_type = fs::symlink_metadata(entry)?.file_type();#[cfg(windows)]@@ -45,7 +46,10 @@ fn remove_plugin_entry(entry: &Path) -> std::io::Result<()> {if file_type.is_symlink() {return fs::remove_file(entry);}- fs::remove_dir_all(entry)+ if file_type.is_dir() {+ return fs::remove_dir_all(entry);+ }+ fs::remove_file(entry)}/// 删除 `node_modules/<id>`;scoped 目录删除后若 scope 空则一并清理。diff --git a/src-tauri/src/service/workflow/install.rs b/src-tauri/src/service/workflow/install.rsindex 059e104e..64e0e2ad 100644--- a/src-tauri/src/service/workflow/install.rs+++ b/src-tauri/src/service/workflow/install.rs@@ -17,7 +17,7 @@ pub async fn install(mut dsh_latest: Option<download::LatestDshPkg>,) -> Result<bool, String> {log::info!("Starting installation process");- // dsh 任务(index==1)实际下载解压时置 true+ // dsh 任务实际下载解压时置 truelet mut dsh_updated = false;// 安装前先停止本应用持有的 Harness 服务:运行中的 node 进程会把@@ -60,13 +60,14 @@ pub async fn install(log::info!("Task list created, {} tasks total", tasks.len());for (index, task) in tasks.iter().enumerate() {+ let kind = task.kind();log::debug!("Processing task {}/{}", index + 1, tasks.len());// 已安装但版本/commit 与最新 release 不一致时强制重新下载。// 版本优先(与 resolve_update 的判定完全一致):dsh 的 rc 发布会复用// 同一 git commit(record_commit 不变),只比 commit 会把 rc.8 之于// rc.7 误判为"已最新"而跳过下载——日志表现为"All installation tasks// completed"但实际什么都没下载,重启后仍是旧版,且前端丢掉更新提示。- let outdated = index == 1+ let outdated = kind == download::InstallKind::Dsh&& dsh_latest.as_ref().is_some_and(|info| {let installed_version = config::get_dsh_version(app_handle);let latest_version = download::parse_version_from_tag(&info.tag);@@ -112,7 +113,7 @@ pub async fn install(// (mac 首次启动常见)仍能拿到真实下载地址,避免整次安装被瞬时失败卡死。// dsh 核心默认先走 GitHub 官方直连,失败自动切换 ghfast.top 镜像兜底// (下载层会在界面上告知用户);其余任务保持单一官方源。- let (urls, name) = if index == 1 {+ let (urls, name) = if kind == download::InstallKind::Dsh {let urls = config::get_dsh_download_urls()?;let name = urls.first()@@ -132,9 +133,11 @@ pub async fn install(log::debug!("File name: {}", name);let buffer = download::download_file_from_sources(&tracker, urls).await?;log::info!("Download completed, file size: {} bytes", buffer.len());- let expected_digest = match index {- 0 => download::fetch_node_sha256(task.get_download_url()?.as_str()).await?,- 1 => {+ let expected_digest = match kind {+ download::InstallKind::Node => {+ download::fetch_node_sha256(task.get_download_url()?.as_str()).await?+ }+ download::InstallKind::Dsh => {// dsh 的 SHA-256 digest 只能来自 GitHub release asset 元数据// (安全设计,见 dsh_INTEGRITY_UNAVAILABLE)。首次安装时该元数据// 可能因 api.github.com 限流/网络抖动而缺失(mac 首次启动常见,@@ -173,10 +176,15 @@ pub async fn install("DSH_INTEGRITY_UNAVAILABLE: trusted release digest is required".to_string()})?}- 2 => config::PNPM_SHA256.to_string(),+ download::InstallKind::Pnpm => config::PNPM_SHA256.to_string(),#[cfg(windows)]- 3 => config::get_mingit_sha256()?.to_string(),- _ => return Err("INSTALL_TASK_INVALID: unknown install task".to_string()),+ download::InstallKind::Git => config::get_mingit_sha256()?.to_string(),+ #[cfg(not(windows))]+ download::InstallKind::Git => {+ return Err(+ "INSTALL_TASK_INVALID: Git task not supported on this platform".to_string(),+ )+ }};download::verify_sha256(&buffer, &expected_digest)?;log::info!("Download integrity verified for task {}", index + 1);@@ -194,7 +202,7 @@ pub async fn install(tracker.end_phase();// 记录本次安装对应的 release tag 与 commit,供下次启动比对- if index == 1 {+ if kind == download::InstallKind::Dsh {dsh_updated = true;if let Some(info) = &dsh_latest {config::set_dsh_pkg_commit(app_handle, info.commit.clone());diff --git a/src-tauri/src/service/workflow/launch.rs b/src-tauri/src/service/workflow/launch.rsindex 03270166..46643701 100644--- a/src-tauri/src/service/workflow/launch.rs+++ b/src-tauri/src/service/workflow/launch.rs@@ -250,7 +250,8 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {// 构造环境变量:隔离的 $DSH_HOME + 隐私默认(关闭遥测)let dsh_home = config::get_dsh_data_path(&app_handle);- fs::create_dir_all(&dsh_home).map_err(|e| format!("create dsh home failed: {e}"))?;+ fs::create_dir_all(&dsh_home)+ .map_err(|e| format!("DSH_HOME_MKDIR_FAILED: create dsh home failed: {e}"))?;// Linux 起步前探测 inotify 监视上限:harness 服务(dsh web)用 chokidar 递归// 监视 profile 目录,上限过低会在启动一瞬间抛 ENOSPC 直接退出(issue #116)。@@ -398,7 +399,7 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {// `dsh-web.log.1` / `dsh-web.log.2`,避免单文件随多次启动无限增长。let log_path = config::get_service_log_path(&app_handle);fs::create_dir_all(log_path.parent().unwrap_or(std::path::Path::new(".")))- .map_err(|e| format!("create log dir failed: {e}"))?;+ .map_err(|e| format!("LOG_DIR_MKDIR_FAILED: create log dir failed: {e}"))?;rotate_service_log(&log_path, 3);// rc.8 起 `dsh web` 默认在系统浏览器打开 UI;桌面端内嵌 WebView,不需要diff --git a/src-tauri/src/service/workflow/process.rs b/src-tauri/src/service/workflow/process.rsindex 5ac7f708..b0295e37 100644--- a/src-tauri/src/service/workflow/process.rs+++ b/src-tauri/src/service/workflow/process.rs@@ -54,8 +54,8 @@ pub(super) fn set_owned_process_with_handle(pid: u32, handle: usize) {*guard = Some(OwnedProcess { pid, handle });}-/// 原子取出持有的进程(PID+句柄一起)。Whoever takes it is responsible for-/// closing the Windows handle. 无条件取出(停止/退出路径)。+/// 原子取出持有的进程(PID+句柄一起)。取走者负责关闭 Windows 句柄;+/// 无条件取出(停止/退出路径)。fn take_owned_process() -> Option<OwnedProcess> {owned_process_lock().lock()@@ -95,11 +95,13 @@ impl Drop for LaunchGuard {}}+/// 是否持有 Harness 进程。与其它访问器一致:锁被毒化(panic 残留)时取回+/// 毒化守卫继续读取,而不是把「已登记进程」误报为「无」。pub fn has_owned_process() -> bool {owned_process_lock().lock()- .map(|g| g.is_some())- .unwrap_or(false)+ .unwrap_or_else(|e| e.into_inner())+ .is_some()}/// 处理「持有的 dsh 进程退出」这一事实(由退出监视线程与健康检查 tick 共用):@@ -288,9 +290,11 @@ pub fn terminate_stale_harness_processes(app_handle: &tauri::AppHandle) {};// 进程名过滤保证 PowerShell 自身(其命令行同样包含该路径)不被误杀;// 路径中的单引号按 PS 字符串字面量规则转义,避免用户目录含 `'` 时语法错误。+ // 与 is_harness_command_line 一致,额外要求服务参数(--host 127.0.0.1+ // 与 --port),避免误伤用户并行执行的 `dsh plugin` 等短命令。let escaped = dsh_bin.replace('\'', "''");let script = format!(- "Get-CimInstance Win32_Process -Filter \"Name = 'node.exe'\" | Where-Object {{ $_.CommandLine -like '*{escaped}*' }} | Select-Object -ExpandProperty ProcessId"+ "Get-CimInstance Win32_Process -Filter \"Name = 'node.exe'\" | Where-Object {{ $_.CommandLine -like '*{escaped}*' -and $_.CommandLine -like '*--host 127.0.0.1*' -and $_.CommandLine -like '*--port*' }} | Select-Object -ExpandProperty ProcessId");let Ok(output) = Command::new("powershell").args(["-NoProfile", "-NonInteractive", "-Command", &script])diff --git a/src-tauri/src/service/workflow/sweep.rs b/src-tauri/src/service/workflow/sweep.rsindex 3ef40c6c..49c7c77b 100644--- a/src-tauri/src/service/workflow/sweep.rs+++ b/src-tauri/src/service/workflow/sweep.rs@@ -86,7 +86,8 @@ fn port_owner_pid(port: u16) -> Option<u32> {.output().ok()?;let text = String::from_utf8_lossy(&output.stdout);- let needle = format!(":{port} ");+ // `fields[1]` 来自 split_whitespace,已无尾随空格:needle 只带端口后缀+ let needle = format!(":{port}");for line in text.lines() {let fields: Vec<&str> = line.split_whitespace().collect();if fields.len() < 5 || fields[0] != "TCP" {