DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
fix(plugin): repair broken preset plugin installs and unblock uninstall (fix #90)
hairyf27a8ea20dafa
diff --git a/.env.example b/.env.examplenew file mode 100644index 00000000..13f6b7c3--- /dev/null+++ b/.env.example@@ -0,0 +1,11 @@+# 开发模式内置插件源码根目录(仅 debug 构建生效,见 src-tauri 中+# service::plugin::preset::bundled_plugin_dir)+#+# 指向本地插件源码根目录:对 preset-plugins.json 中 internal 为 true 的每个插件,+# 运行时自动查找 <dir>/<id> —— 命中则以本地源码目录为 file: 安装目标+# (pnpm 目录联接 = 热更新:改源码 → 重启服务即生效,无需提交子插件 git、+# 无需跑 prebuild);设置但缺该 id 则跳过(不回落随包目录)。+#+# 本文件为模板:复制为 .env 并填入你的路径(.env 已被 .gitignore 忽略)。+# 置空或删除本键 = 关闭覆盖,回落到随包分发的 resources/preset-plugins/<id>。+DEV_INTERNAL_PLUGINS_DIR=\ No newline at end of filediff --git a/.gitignore b/.gitignoreindex d20443f5..59e913a9 100644--- a/.gitignore+++ b/.gitignore@@ -3,11 +3,13 @@ distsrc-tauri/targetsrc-tauri/gensrc-tauri/resources/node+src-tauri/resources/preset-plugins/*.log.DS_Store.idea.vscode*.local+.env.tmpskills.serena\ No newline at end of filediff --git a/package.json b/package.jsonindex 0379f452..e49007fa 100644--- a/package.json+++ b/package.json@@ -7,6 +7,7 @@"description": "Desktop application for DeepSeek Harness (dsh) — one-click local install and launch, no Node.js setup required.","scripts": {"dev": "vite",+ "prebuild": "node --experimental-strip-types scripts/prebuild.ts","build": "tsc && vite build","preview": "vite preview","tauri": "tauri",diff --git a/scripts/prebuild.ts b/scripts/prebuild.tsnew file mode 100644index 00000000..e73326a3--- /dev/null+++ b/scripts/prebuild.ts@@ -0,0 +1,145 @@+/**+ * prebuild:把 `src-tauri/resources/preset-plugins.json` 中标记 `internal: true`+ * 的插件从上游仓库克隆、安装依赖并构建,产物拷入+ * `src-tauri/resources/preset-plugins/<id>/`(随 `bundle.resources` 随安装包分发)。+ *+ * 由 `pnpm build` 的 prebuild 生命周期自动触发(tauri 的 `beforeBuildCommand` 为+ * `pnpm build`,pnpm 先执行 `prebuild` 脚本)。应用启动时(service::plugin::internal)+ * 会核对内置插件是否已安装、安装路径是否仍指向该捆绑目录,未满足即强制重装。+ *+ * 约束:仅用 Node 内置模块(零新增依赖);需要 git 与 pnpm 在 PATH 上;+ * 构建机器需可访问 GitHub 与 npm registry。本文件是「可擦除」TypeScript,+ * Node ≥22.6(--experimental-strip-types)或 ≥23.6(默认启用类型剥离)可直接执行。+ */+import { spawnSync } from 'node:child_process'+import {+ cpSync,+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ readdirSync,+ rmSync,+} from 'node:fs'+import { tmpdir } from 'node:os'+import { join, resolve } from 'node:path'++interface PresetPlugin {+ id: string+ spec: string+ internal?: boolean+}++const REPO_ROOT = resolve(import.meta.dirname, '..')+const PRESET_FILE = join(REPO_ROOT, 'src-tauri', 'resources', 'preset-plugins.json')+const BUNDLE_ROOT = join(REPO_ROOT, 'src-tauri', 'resources', 'preset-plugins')+const GIT_URL_RE = /^github:([^#/]+\/[^#/]+)(?:#.*)?$/++function die(message: string): never {+ console.error(`[prebuild] ${message}`)+ process.exit(1)+}++/** 同步执行命令,非零退出码即终止构建(内置插件缺失是发布缺陷,必须响亮失败)。 */+function run(program: string, args: readonly string[], cwd: string): void {+ console.log(`[prebuild] $ ${program} ${args.join(' ')}`)+ const result = spawnSync(program, [...args], {+ cwd,+ stdio: 'inherit',+ shell: process.platform === 'win32',+ })+ if (result.error !== undefined) {+ die(`${program} 启动失败: ${result.error.message}`)+ }+ if (result.status !== 0) {+ die(`${program} ${args.join(' ')} 退出码 ${result.status}`)+ }+}++/** `github:owner/repo[#ref]` → 可克隆的 https URL(忽略 ref,拉默认分支最新)。 */+function githubUrl(spec: string): string {+ const match = GIT_URL_RE.exec(spec)+ if (match === null) {+ die(`internal 插件 spec 必须是 github:owner/repo 形式,当前为: ${spec}`)+ }+ const repo = match[1].replace(/\.git$/, '')+ return `https://github.com/${repo}.git`+}++/**+ * 拷贝构建产物:优先 `files` 白名单(只发运行必需:lib/、patch 文件、README),+ * 缺失白名单时拷贝整目录但排除 node_modules/.git 等开发噪声;+ * `package.json` 恒在(它是 `pnpm add file:<dir>` 的包名/入口来源)。+ */+function collectBundle(preset: PresetPlugin, clone: string): void {+ const dest = join(BUNDLE_ROOT, preset.id)+ mkdirSync(dest, { recursive: true })++ const manifest = JSON.parse(readFileSync(join(clone, 'package.json'), 'utf8')) as Record<string, unknown>+ const rawFiles = manifest.files+ const files = Array.isArray(rawFiles)+ ? rawFiles.filter((f): f is string => typeof f === 'string')+ : undefined+ const skip = new Set(['node_modules', '.git', '.gitignore', '.npmrc'])+ const entries = files !== undefined && files.length > 0+ ? files+ : readdirSync(clone).filter(name => !skip.has(name) && !name.endsWith('.tsbuildinfo'))++ for (const name of entries) {+ const src = join(clone, name)+ if (!existsSync(src)) {+ die(`${preset.id}: 白名单产物缺失 ${src}`)+ }+ cpSync(src, join(dest, name), { recursive: true })+ }+ // 拷贝后置,确保即使白名单里没有 package.json 它也一定存在+ cpSync(join(clone, 'package.json'), join(dest, 'package.json'))+}++/** 构建单个 internal 插件:克隆 → 装依赖 → 构建 → 拷贝产物。 */+function buildPlugin(preset: PresetPlugin): void {+ const dest = join(BUNDLE_ROOT, preset.id)+ rmSync(dest, { recursive: true, force: true })++ const temp = mkdtempSync(join(tmpdir(), `dsh-internal-${preset.id}-`))+ const clone = join(temp, preset.id)+ run('git', ['clone', '--depth', '1', '--quiet', githubUrl(preset.spec), clone], temp)++ const revision = spawnSync('git', ['-C', clone, 'rev-parse', '--short', 'HEAD'], { encoding: 'utf8' })+ if (revision.status === 0) {+ console.log(`[prebuild] ${preset.id}: 来源修订 ${revision.stdout.trim()}`)+ }++ // 注意:pnpm ≥10 默认拦截依赖的构建脚本(esbuild/原生模块需在插件仓库+ // 的 pnpm-workspace.yaml 配 onlyBuiltDependencies 放行);纯 JS/TS 插件不受影响。+ run('pnpm', ['install'], clone)+ const manifest = JSON.parse(readFileSync(join(clone, 'package.json'), 'utf8')) as {+ scripts?: Record<string, string>+ }+ if (manifest.scripts?.build !== undefined) {+ run('pnpm', ['run', 'build'], clone)+ }++ collectBundle(preset, clone)+ rmSync(temp, { recursive: true, force: true })+ console.log(`[prebuild] ${preset.id}: 产物已就绪 → ${dest}`)+}++function main(): void {+ if (!existsSync(PRESET_FILE)) {+ die(`未找到预设清单 ${PRESET_FILE}`)+ }+ const presets = JSON.parse(readFileSync(PRESET_FILE, 'utf8')) as PresetPlugin[]+ const internal = presets.filter(preset => preset.internal === true)+ if (internal.length === 0) {+ console.log('[prebuild] 预设清单无 internal 插件,跳过')+ return+ }+ console.log(`[prebuild] 拉取 ${internal.length} 个 internal 插件: ${internal.map(p => p.id).join(', ')}`)+ for (const preset of internal) {+ buildPlugin(preset)+ }+ console.log(`[prebuild] 完成 → ${BUNDLE_ROOT}`)+}++main()\ No newline at end of filediff --git a/src-tauri/resources/preset-plugins.json b/src-tauri/resources/preset-plugins.jsonindex f11082e5..6391216b 100644--- a/src-tauri/resources/preset-plugins.json+++ b/src-tauri/resources/preset-plugins.json@@ -13,6 +13,7 @@{"id": "dsh-tauri","spec": "github:hairyf/dsh-tauri",+ "internal": true,"name": "DSH Tauri","description": "Message bridge for the DeepSeek Harness desktop shell","repoUrl": "https://github.com/hairyf/dsh-tauri",diff --git a/src-tauri/src/service/plugin/install.rs b/src-tauri/src/service/plugin/install.rsindex 1ab5eb05..43ef3e5e 100644--- a/src-tauri/src/service/plugin/install.rs+++ b/src-tauri/src/service/plugin/install.rs@@ -25,7 +25,7 @@ use tauri::{AppHandle, Emitter, Manager, WebviewWindow};use super::errors;use super::installed::{is_installed, profile_dir};-use super::preset::load_presets;+use super::preset::{bundled_plugin_dir, file_dep_spec, load_presets, PreinstallPluginInfo};use super::process::{run_plugin_process, PreinstallLogPayload, PREINSTALL_LOG_EVENT};use super::recovery::is_actionable_plugin_ref;use super::uninstall_recovery;@@ -50,21 +50,23 @@ pub async fn install(app_handle: &AppHandle, ids: &[String]) -> Result<(), Strin// 单次读取预设并构建查找表,提升算法效率至 O(N)let presets = load_presets(app_handle);- let preset_map: HashMap<&str, &str> = presets+ let preset_map: HashMap<&str, &PreinstallPluginInfo> = presets.iter()- .map(|p| (p.id.as_str(), p.spec.as_str()))+ .map(|p| (p.id.as_str(), p)).collect();let mut specs = Vec::with_capacity(ids.len());for id in ids {- let spec = preset_map+ let preset = preset_map.get(id.as_str()).ok_or_else(|| format!("PREINSTALL_INVALID_ID: {id}"))?;- // 统一把 `github:user/repo` 规范为显式 `git+https://...`,绕开 pnpm 对+ // 内置插件改为从随包分发的捆绑目录安装(`file:` 本地依赖,见+ // preset::file_dep_spec),其余沿用清单声明的 spec;随后统一把+ // `github:user/repo` 规范为显式 `git+https://...`,绕开 pnpm 对// GitHub 简写「HTTPS 探测失败即回退 SSH」的已知缺陷(pnpm issue// #3948 / #7243 / #13276):公开仓库一旦落进 git+ssh,在没有 SSH 配置// 的桌面机上必然 `Host key verification failed` / `Permission denied (publickey)`。- specs.push(normalize_git_spec(spec));+ specs.push(normalize_git_spec(&preset_spec_for_install(preset, bundled_dir_of(app_handle, preset))?));}// 确保 pnpm/dsh shim 存在@@ -191,9 +193,42 @@ pub async fn install(app_handle: &AppHandle, ids: &[String]) -> Result<(), StrinOk(())}+/// 内置插件才需要解析捆绑目录(普通插件无此概念),避免无谓的资源探测+fn bundled_dir_of(app_handle: &AppHandle, preset: &PreinstallPluginInfo) -> Option<PathBuf> {+ if !preset.internal {+ return None;+ }+ bundled_plugin_dir(app_handle, &preset.id)+}++/// 解析某预设的安装 spec(纯函数,便于单测):内置插件固定为随包捆绑目录的+/// `file:` 本地依赖(路径正确性由 [`super::internal::ensure`] 启动自愈核对);+/// 普通插件沿用清单声明。+///+/// 捆绑目录缺失时返回错误:内置插件缺失意味着构建期 prebuild 未执行或产物被+/// 删,属发布缺陷而非用户侧的普通安装失败,错误前缀便于区分。+fn preset_spec_for_install(+ preset: &PreinstallPluginInfo,+ bundled_dir: Option<PathBuf>,+) -> Result<String, String> {+ if !preset.internal {+ return Ok(preset.spec.clone());+ }+ let dir = bundled_dir.ok_or_else(|| {+ format!(+ "BUNDLED_PLUGIN_MISSING: no bundled dir for internal plugin {} (run scripts/prebuild.ts at build time)",+ preset.id+ )+ })?;+ Ok(file_dep_spec(&dir))+}+/// 构建 `dsh plugin` 子进程的环境变量:隔离 $DSH_HOME、关闭遥测与颜色,/// PATH 前置 shim 目录与 node 目录;用户 pnpm 过旧时强制捆绑版(见 ensure_pnpm)。-fn build_plugin_envs(app_handle: &AppHandle, prefer_bundled_pnpm: bool) -> HashMap<String, String> {+///+/// 供本模块的安装/升级/卸载与 [`super::verify`] 的完整性修复共用:子进程(dsh+/// 或 pnpm)都按同一套桌面端环境策略运行,保证 $DSH_HOME / PATH 布局一致。+pub(crate) fn build_plugin_envs(app_handle: &AppHandle, prefer_bundled_pnpm: bool) -> HashMap<String, String> {let node = config::get_node_binary_path(app_handle);let bin_dir = cli::get_bin_dir(app_handle);let mut envs = HashMap::from([@@ -287,22 +322,30 @@ pub async fn update(app_handle: &AppHandle, id: &str) -> Result<(), String> {/// 卸载单个插件:`dsh plugin --profile <当前档案> remove <id>`pub async fn remove(app_handle: &AppHandle, id: &str) -> Result<(), String> {- run_single_plugin_command(app_handle, id, "remove", &["remove".to_string(), id.to_string()])- .await?;+ let command_result =+ run_single_plugin_command(app_handle, id, "remove", &["remove".to_string(), id.to_string()])+ .await;// `dsh plugin remove` 以子进程退出码为准,可能出现「命令成功但插件仍在」的- // 边界(如 bundle 层残留、pnpm 静默失败):核验 profile 清单,若插件仍被引用- // 则回落到离线卸载(直接改清单 + 删目录 + 清 lockfile),确保插件真正移除+ // 边界(如 bundle 层残留、pnpm 静默失败);node_modules / lockfile 损坏时+ // (典型:安装只写入了 profile 清单而产物缺失,见 issue #90)pnpm 甚至会+ // 直接失败。两种情形统一核验 profile 清单:只要插件仍被引用就回落离线卸载+ // (直接改清单 + 删目录 + 清 lockfile),确保插件真正移除// (参考 dsh-market 的「卸载后核验」约定:确认插件离开 profile 才算成功)。if is_installed(app_handle, id) {// 第三方可卸载插件才允许离线兜底;核心/官方等受保护包即使残留也不强删- // (`uninstall_recovery` 对它们会拒绝),仅记录告警,避免把已成功的卸载- // 误报为失败。+ // (`uninstall_recovery` 对它们会拒绝)。if is_actionable_plugin_ref(id) {+ let outcome = match &command_result {+ Ok(()) => "reported success".to_string(),+ Err(e) => format!("failed: {e}"),+ };log::warn!(- "dsh plugin remove reported success but {id} is still referenced by profile manifest; forcing offline uninstall"+ "dsh plugin remove {outcome} but {id} is still referenced by profile manifest; forcing offline uninstall");uninstall_recovery(app_handle, id)?;} else {+ // 受保护包:命令失败则如实上报(不要把失败误报为成功),成功则仅告警。+ command_result?;log::warn!("dsh plugin remove reported success but protected package {id} is still referenced by profile manifest; skipping offline uninstall");@@ -547,7 +590,9 @@ async fn ensure_pnpm(app_handle: &AppHandle, window: &WebviewWindow) -> Result<b/// 用户 pnpm 主版本号(解析 `pnpm --version` 首个点分字段);不存在或不可运行/// (corepack shim 在 Node 24 上 ERR_INVALID_THIS 崩溃等)返回 None。-fn user_pnpm_major_version(app_handle: &AppHandle) -> Option<u32> {+///+/// 供 [`ensure_pnpm`] 选版与 [`super::verify`] 的修复选版共用(store 主版本匹配)。+pub(crate) fn user_pnpm_major_version(app_handle: &AppHandle) -> Option<u32> {let pnpm = cli::find_user_pnpm(app_handle)?;// 打包版是 GUI 进程(无控制台):直接运行 pnpm(控制台子系统)会新建一个// 可见的黑色 cmd 窗口。`harness_prefer_bundled_pnpm` 在每次服务启动都会调本@@ -574,7 +619,8 @@ fn user_pnpm_major_version(app_handle: &AppHandle) -> Option<u32> {/// pnpm 10 与 11 的 store 布局互不兼容:用与 store 主版本不一致的 pnpm 更新/// 已装插件会 `ERR_PNPM_UNEXPECTED_STORE` 退出。档案尚未安装过依赖(没有/// node_modules)时返回 `None`,由调用方走"全新档案"逻辑。-fn profile_store_major(app_handle: &AppHandle) -> Option<u32> {+/// 供 [`ensure_pnpm`] 选版与 [`super::verify`] 的修复选版共用。+pub(crate) fn profile_store_major(app_handle: &AppHandle) -> Option<u32> {let modules_yaml = profile_dir(app_handle).join("node_modules").join(".modules.yaml");@@ -598,7 +644,9 @@ fn parse_store_major_from_modules_yaml(content: &str) -> Option<u32> {/// 捆绑版 pnpm 的主版本(读 `dependencies/pnpm/package.json` 的 version 字段);/// 未安装或清单缺失返回 None。-fn bundled_pnpm_major(app_handle: &AppHandle) -> Option<u32> {+///+/// 供 [`ensure_pnpm`] 选版与 [`super::verify`] 的修复选版共用(store 主版本匹配)。+pub(crate) fn bundled_pnpm_major(app_handle: &AppHandle) -> Option<u32> {let manifest = config::get_pnpm_install_path(app_handle).join("package.json");let content = std::fs::read_to_string(manifest).ok()?;let value: serde_json::Value = serde_json::from_str(&content).ok()?;@@ -922,7 +970,59 @@ pub(crate) fn harness_prefer_bundled_pnpm(app_handle: &AppHandle) -> bool {#[cfg(test)]mod tests {- use super::{apply_allow_build_keys, collapse_allow_builds_duplicates, extract_allow_line_key, git_transport_hint, normalize_git_spec, parse_allowlist_keys, parse_store_major_from_modules_yaml};+ use std::path::PathBuf;+ use super::{apply_allow_build_keys, collapse_allow_builds_duplicates, extract_allow_line_key, git_transport_hint, normalize_git_spec, parse_allowlist_keys, parse_store_major_from_modules_yaml, preset_spec_for_install, PreinstallPluginInfo};++ /// 构造预设条目的测试助手(internal 由各用例显式指定)+ fn preset(id: &str, spec: &str, internal: bool) -> PreinstallPluginInfo {+ PreinstallPluginInfo {+ id: id.into(),+ spec: spec.into(),+ package: None,+ name: String::new(),+ description: String::new(),+ repo_url: String::new(),+ recommended: false,+ fix: false,+ default_checked: false,+ win_only: false,+ internal,+ }+ }++ #[test]+ fn install_spec_passthrough_for_regular_preset() {+ // 普通插件:spec 原样返回,与捆绑目录无关+ let p = preset("dshmarket", "dshmarket", false);+ assert_eq!(+ preset_spec_for_install(&p, None).unwrap(),+ "dshmarket"+ );+ assert_eq!(+ preset_spec_for_install(&p, Some(PathBuf::from("/ignored"))).unwrap(),+ "dshmarket"+ );+ }++ #[test]+ fn install_spec_uses_bundled_dir_for_internal_preset() {+ // 内置插件:安装依赖为 file:<捆绑目录>(正斜杠规范形)+ let p = preset("dsh-tauri", "github:hairyf/dsh-tauri", true);+ let dir = PathBuf::from("C:\\Apps\\dsh\\resources\\preset-plugins\\dsh-tauri");+ assert_eq!(+ preset_spec_for_install(&p, Some(dir)).unwrap(),+ "file:C:/Apps/dsh/resources/preset-plugins/dsh-tauri"+ );+ }++ #[test]+ fn install_spec_errors_when_internal_bundle_missing() {+ // 内置插件捆绑目录缺失:发布缺陷,显式报错而非静默走 git spec+ let p = preset("dsh-tauri", "github:hairyf/dsh-tauri", true);+ let err = preset_spec_for_install(&p, None).unwrap_err();+ assert!(err.starts_with("BUNDLED_PLUGIN_MISSING"));+ assert!(err.contains("dsh-tauri"));+ }#[test]fn store_major_parsed_from_modules_yaml() {diff --git a/src-tauri/src/service/plugin/installed.rs b/src-tauri/src/service/plugin/installed.rsindex 77dc5db3..b279d59a 100644--- a/src-tauri/src/service/plugin/installed.rs+++ b/src-tauri/src/service/plugin/installed.rs@@ -88,8 +88,8 @@ pub struct PreinstallPlugin {}/// 用于“已安装”检测的包名:预设显式声明 `package` 时用它(scoped 包名与预设-/// id 不一致),未声明则回落到 `id`。-fn installed_name(p: &PreinstallPluginInfo) -> &str {+/// id 不一致),未声明则回落到 `id`。供内部(`internal.rs` 内置插件自愈)复用。+pub(crate) fn installed_name(p: &PreinstallPluginInfo) -> &str {p.package.as_deref().unwrap_or(p.id.as_str())}@@ -101,6 +101,9 @@ pub fn list(app_handle: &AppHandle) -> Vec<PreinstallPlugin> {load_presets(app_handle).into_iter().filter(|p| !p.win_only || is_windows)+ // 内置插件(internal:true)由启动自愈强制安装,不进入首次引导清单:+ // 对用户而言它们“必装”,给出可取消的勾选框反而造成歧义。+ .filter(|p| !p.internal).map(|p| {// 已安装检测以实际 npm 包名为准:预设可显式声明 package(scoped 包// 名与预设 id 不一致时),未声明则回落到 id。@@ -260,6 +263,7 @@ mod tests {fix: false,default_checked: true,win_only: false,+ internal: false,};// scoped 包名与预设 id 不同:以 package 为准assert_eq!(diff --git a/src-tauri/src/service/plugin/internal.rs b/src-tauri/src/service/plugin/internal.rsnew file mode 100644index 00000000..eca89284--- /dev/null+++ b/src-tauri/src/service/plugin/internal.rs@@ -0,0 +1,148 @@+//! 内置插件启动自愈:随安装包分发的内置插件(`preset-plugins.json` 标记+//! `internal: true`,产物目录 `resources/preset-plugins/<id>` 由构建期+//! `scripts/prebuild.ts` 拉取)在服务启动前核对「是否已安装 + 安装路径是否仍+//! 指向当前捆绑目录」:未安装 / 路径不正确 / 用户卸载后残留缺失 → 一律走常规+//! 安装流程强制重装,保证桌面外壳依赖的桥接层(如 dsh-tauri)随包可用。+//!+//! debug 构建可用仓库根 `.env` 的 `DEV_INTERNAL_PLUGINS_DIR` 把安装目标指到+//! 本地插件源码(热更新迭代,见 [`super::preset::bundled_plugin_dir`])。+//!+//! 为什么放在启动而非安装流程:安装是用户主动行为,内置插件是应用自身的完整性+//! 要求——用户怎么卸载、何时卸载都不影响下次启动自动恢复,无需任何用户操作。++use std::collections::HashMap;+use tauri::AppHandle;++use super::installed::{installed_name, profile_dir, ProfilePackageJson};+use super::preset::{bundled_plugin_dir, file_dep_spec, load_presets};++/// 核对并强制安装缺失/路径不正确/被卸载的内置插件,在服务进程启动前调用。+///+/// 最佳努力:任何失败只记告警(调用方不阻断启动);捆绑目录缺失(开发环境未跑+/// prebuild)时跳过,交由常规引导流程处理;批量待装列表为空则不触发任何安装。+pub(crate) async fn ensure(app_handle: &AppHandle) -> Result<(), String> {+ let presets = load_presets(app_handle);+ let internal: Vec<_> = presets.iter().filter(|p| p.internal).collect();+ if internal.is_empty() {+ return Ok(());+ }++ // 一次读取当前档案的依赖声明;档案未初始化(package.json 缺失/损坏)时按+ // 「全部缺失」处理,由安装流程自行初始化。+ let manifest_path = profile_dir(app_handle).join("package.json");+ let dependencies: HashMap<String, String> = match std::fs::read_to_string(&manifest_path) {+ Ok(raw) => serde_json::from_str::<ProfilePackageJson>(&raw)+ .map(|m| m.dependencies)+ .unwrap_or_default(),+ // 档案尚未初始化+ Err(_) => HashMap::new(),+ };++ let profile = profile_dir(app_handle);+ let mut need: Vec<String> = Vec::new();+ for preset in &internal {+ let Some(bundled) = bundled_plugin_dir(app_handle, &preset.id) else {+ // 未找到内置插件目录:release 说明构建期 prebuild 未拉取(发布缺陷,+ // 由 prebuild 响亮失败);debug 可用 .env 的 DEV_INTERNAL_PLUGINS_DIR+ // 指向本地源码目录,未配置/缺 id 时跳过(「找不到则不装」)。+ log::warn!(+ "INTERNAL_PLUGIN_BUNDLE_MISSING: {}(release 需构建期 prebuild;debug 可配 .env DEV_INTERNAL_PLUGINS_DIR)",+ preset.id+ );+ continue;+ };+ let name = installed_name(preset).to_string();+ let expected = file_dep_spec(&bundled);+ // ① 依赖声明:未声明,或声明的值不再指向当前捆绑目录(路径变更/被改+ // 写)→ 重装;② 依赖真实性:node_modules 链接/拷贝须真实存在(用户+ // 手动清过 node_modules 时声明可能残留但产物已不在)→ 重装。+ let dep_ok = dependencies+ .get(&name)+ .is_some_and(|actual| dep_matches_spec(actual, &expected));+ let link_ok = profile.join("node_modules").join(&name).exists();+ if !dep_ok || !link_ok {+ log::info!(+ "INTERNAL_PLUGIN_NEEDS_REINSTALL: {name}(dep_ok={dep_ok}, link_ok={link_ok}, expected={expected})"+ );+ need.push(preset.id.clone());+ }+ }+ if need.is_empty() {+ return Ok(());+ }++ log::info!("Reinstalling internal preset plugins: {need:?}");+ // 复用常规安装编排(环境准备/补齐 pnpm/`dsh plugin add file:<dir>`);+ // 启动阶段无持有进程,install 内部不会停服务。失败同样交给调用方告警。+ if let Err(e) = super::install::install(app_handle, &need).await {+ return Err(format!("INTERNAL_PLUGIN_INSTALL_FAILED: {e}"));+ }+ Ok(())+}++/// 判断 pnpm 写入 profile 的依赖值与期望的 `file:` 捆绑路径是否一致。+///+/// 容忍:`file:` 前缀缺失/存在两种写法;Windows 下路径大小写不敏感;尾部斜杠+/// 差异(pnpm 各版本落盘形式略有出入)。+fn dep_matches_spec(actual: &str, expected: &str) -> bool {+ let norm = |spec: &str| {+ let stripped = spec.strip_prefix("file:").unwrap_or(spec);+ stripped.replace('\\', "/").trim_end_matches('/').to_string()+ };+ let actual = norm(actual);+ let expected = norm(expected);+ if cfg!(windows) {+ actual.eq_ignore_ascii_case(&expected)+ } else {+ actual == expected+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn dep_spec_matches_itself() {+ let expected = "file:C:/Apps/dsh/resources/preset-plugins/dsh-tauri";+ // 与自身一致+ assert!(dep_matches_spec(expected, expected));+ // 无 file: 前缀(pnpm 某些场景直接落路径)+ assert!(dep_matches_spec(+ "C:/Apps/dsh/resources/preset-plugins/dsh-tauri",+ expected+ ));+ // 尾部斜杠差异+ assert!(dep_matches_spec(+ "file:C:/Apps/dsh/resources/preset-plugins/dsh-tauri/",+ expected+ ));+ // 反斜杠(Windows 原生形式)+ assert!(dep_matches_spec(+ "file:C:\\Apps\\dsh\\resources\\preset-plugins\\dsh-tauri",+ expected+ ));+ }++ #[test]+ fn dep_spec_rejects_wrong_path_or_source() {+ let expected = "file:C:/Apps/dsh/resources/preset-plugins/dsh-tauri";+ // 仍指向 git 源(用户手动从仓库安装)+ assert!(!dep_matches_spec("github:hairyf/dsh-tauri", expected));+ // 指向其它位置(旧版本安装目录等)+ assert!(!dep_matches_spec("file:D:/elsewhere/dsh-tauri", expected));+ // 同名不同宿主盘符+ assert!(!dep_matches_spec("file:D:/Apps/dsh/resources/preset-plugins/dsh-tauri", expected));+ }++ #[cfg(windows)]+ #[test]+ fn dep_spec_case_insensitive_on_windows() {+ // Windows 文件系统大小写不敏感,路径比较须忽略大小写+ let expected = "file:C:/Apps/dsh/resources/preset-plugins/dsh-tauri";+ assert!(dep_matches_spec(+ "file:c:/apps/DSH/resources/preset-plugins/Dsh-Tauri",+ expected+ ));+ }+}\ No newline at end of filediff --git a/src-tauri/src/service/plugin/mod.rs b/src-tauri/src/service/plugin/mod.rsindex 84affc1f..6a5cbf9d 100644--- a/src-tauri/src/service/plugin/mod.rs+++ b/src-tauri/src/service/plugin/mod.rs@@ -17,6 +17,8 @@//! 模块划分(参考 `service/cli/`、`service/download/`)://! - [`preset`]:预设清单读取与解析(`resources/preset-plugins.json`)//! - [`installed`]:profile 内已安装插件检测(解析 package.json 的依赖与 bundles)+//! - [`internal`]:内置插件启动自愈(随包分发产物缺失/路径变更时强制重装)+//! - [`verify`]:预装插件完整性自检(清单引用但 node_modules 产物缺失时 `pnpm install` 修复)//! - [`install`]:对外安装/升级/卸载编排(校验、环境准备、调用 dsh 子进程)//! - [`errors`]:插件错误记录(安装/升级/卸载失败 + 页面运行期上报,持久化)//! - [`process`]:dsh 子进程启动与输出流逐行转发@@ -27,10 +29,12 @@ mod cancel;pub mod errors;mod install;mod installed;+mod internal;mod preset;mod process;pub mod recovery;pub mod update;+pub mod verify;pub mod watch;pub use cancel::cancel;@@ -38,7 +42,9 @@ pub use install::{install, remove, update};pub(crate) use install::harness_prefer_bundled_pnpm;pub use installed::{list, PreinstallPlugin};pub(crate) use installed::ensure_profile_npmrc;+pub(crate) use internal::ensure as ensure_internal_plugins;pub use preset::repo_url_of;pub(crate) use preset::{current_preset_hash, preinstall_pending};pub use recovery::{detect as detect_recovery, uninstall as uninstall_recovery, PluginRecoveryInfo};+pub(crate) use verify::ensure_preset_plugins;pub use watch::DshPlugin;\ No newline at end of filediff --git a/src-tauri/src/service/plugin/preset.rs b/src-tauri/src/service/plugin/preset.rsindex 85eede50..36ea5258 100644--- a/src-tauri/src/service/plugin/preset.rs+++ b/src-tauri/src/service/plugin/preset.rs@@ -20,6 +20,12 @@ pub struct PreinstallPluginInfo {pub id: String,/// 传给 `dsh plugin add` 的依赖形式(npm 包名或 git 依赖形式)pub spec: String,+ /// 内置插件:产物由构建期 `scripts/prebuild.ts` 从上游仓库拉取到+ /// `resources/preset-plugins/<id>/` 随安装包分发,安装固定走 `file:` 本地+ /// 依赖;启动时强制核对「已安装 + 路径指向当前捆绑目录」,不满足即自动+ /// 重装(用户卸载后重启应用同样恢复),因此不出现在首次引导的勾选清单里。+ #[serde(default)]+ pub internal: bool,/// 安装进 profile 后实际出现在 `dependencies`/`bundles` 里的包名。/// 默认与 `id` 相同;仅当 npm 包名与预设 id 不一致时(如 scoped 包/// `@scope/name`)才需要显式指定,供“已安装”检测使用。@@ -71,6 +77,93 @@ fn preset_plugins_path(app_handle: &AppHandle) -> Option<PathBuf> {source.exists().then_some(source)}+/// 内置插件资源目录名(相对资源根的固定前缀)+const BUNDLED_PLUGINS_DIR: &str = "preset-plugins";++/// 在资源根目录下定位某内置插件的捆绑目录:与 [`find_in_resource_root`] 相同的+/// 布局探测——先 `resources/` 子目录(安装包/开发产物按 `bundle.resources` 前缀+/// 落盘),再扁平布局;以目录内存在 `package.json` 判定产物有效(prebuild 恒写入)。+fn find_bundled_in_root(root: &std::path::Path, id: &str) -> Option<PathBuf> {+ let probe = |base: &std::path::Path| {+ let dir = base.join(BUNDLED_PLUGINS_DIR).join(id);+ dir.join("package.json").exists().then_some(dir)+ };+ probe(&root.join("resources")).or_else(|| probe(root))+}++/// 定位内置插件捆绑目录:优先随安装包分发的资源目录,回落到源码+/// `resources/preset-plugins/<id>`(开发机未跑 prebuild 时作为源码兜底)。+///+/// 用于安装(`install.rs` 生成 `file:` 依赖)与启动自愈(`internal.rs` 核对路径)。+///+/// **开发覆盖(仅 debug 构建)**:仓库根 `.env` 声明 `DEV_INTERNAL_PLUGINS_DIR=<dir>`+/// 时,`<dir>/<id>` 命中即以本地插件源码目录为安装目标——pnpm `file:` 依赖是+/// junction(目录联接),改源码 + 重启服务即热更新,无需提交子插件 git、无需+/// prebuild;设置但缺该 id 返回 None(跳过,不回落随包目录),让开发者显式感知。+pub(crate) fn bundled_plugin_dir(app_handle: &AppHandle, id: &str) -> Option<PathBuf> {+ #[cfg(debug_assertions)]+ if let Some(root) = dev_internal_plugins_dir() {+ let dev = root.join(id);+ return dev.join("package.json").exists().then_some(dev);+ }+ if let Ok(dir) = app_handle.path().resource_dir() {+ if let Some(candidate) = find_bundled_in_root(&dir, id) {+ return Some(candidate);+ }+ }+ let source = PathBuf::from(env!("CARGO_MANIFEST_DIR"))+ .join("resources")+ .join(BUNDLED_PLUGINS_DIR)+ .join(id);+ source.join("package.json").exists().then_some(source)+}++/// 开发模式内置插件源码根目录:读取 `<仓库根>/.env` 的 `DEV_INTERNAL_PLUGINS_DIR`。+/// 仅 debug 构建生效(release 恒用随包目录,不受构建机环境影响)。+///+/// `.env` 属于本地个人配置,不入库(见仓库 `.gitignore`);`<仓库根>` 由编译期+/// `CARGO_MANIFEST_DIR`(即 `src-tauri`)的上层目录得到,只在开发机成立。+#[cfg(debug_assertions)]+fn dev_internal_plugins_dir() -> Option<PathBuf> {+ let env_file = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("..").join(".env");+ let content = std::fs::read_to_string(env_file).ok()?;+ parse_dev_internal_dir(&content)+}++/// 从 `.env` 文本解析 `DEV_INTERNAL_PLUGINS_DIR`(纯函数,便于单测):+/// 支持 `KEY=VALUE` / `KEY = VALUE`(键值两侧空白容忍)、值可选单/双引号包裹;+/// `#` 起始行与空行跳过;显式置空(`KEY=`)视为未设置;缺键返回 None。+#[cfg(debug_assertions)]+fn parse_dev_internal_dir(content: &str) -> Option<PathBuf> {+ for line in content.lines() {+ let line = line.trim();+ if line.is_empty() || line.starts_with('#') {+ continue;+ }+ let Some((key, value)) = line.split_once('=') else {+ continue;+ };+ if key.trim() != "DEV_INTERNAL_PLUGINS_DIR" {+ continue;+ }+ let value = value.trim().trim_matches('"').trim_matches('\'');+ if value.is_empty() {+ return None;+ }+ return Some(PathBuf::from(value));+ }+ None+}++/// 内置插件的安装依赖形式:`file:<绝对路径>`(正斜杠、去尾部斜杠)。+///+/// pnpm 按传入形式把 `file:` 依赖写入 profile 的 package.json,这里生成规范形,+/// 安装(`install.rs`)与启动自愈(`internal.rs`)共用同一基准比对路径是否正确。+pub(crate) fn file_dep_spec(dir: &std::path::Path) -> String {+ let normalized = dir.to_string_lossy().replace('\\', "/");+ format!("file:{}", normalized.trim_end_matches('/'))+}+/// 解析预设清单 JSONfn parse_presets(json: &str) -> Result<Vec<PreinstallPluginInfo>, String> {serde_json::from_str(json).map_err(|e| format!("PRESET_PLUGINS_INVALID_JSON: {e}"))@@ -210,6 +303,109 @@ mod tests {std::fs::remove_dir_all(&dir).ok();}+ #[test]+ fn internal_flag_parses_with_default_false() {+ // 无 internal 字段 → 默认 false(老清单兼容)+ let plain: PreinstallPluginInfo = serde_json::from_str(+ r#"{"id":"x","spec":"y","name":"X","description":"","repoUrl":"u"}"#,+ )+ .expect("plain preset should parse");+ assert!(!plain.internal);+ // 显式 internal:true → 解析为内置插件+ let internal: PreinstallPluginInfo = serde_json::from_str(+ r#"{"id":"x","spec":"github:a/b","internal":true,"name":"X","description":"","repoUrl":"u"}"#,+ )+ .expect("internal preset should parse");+ assert!(internal.internal);+ }++ #[test]+ fn bundled_dir_discovers_nested_layout() {+ // 与 preset 文件一致:先探测 {root}/resources/preset-plugins/<id>+ let dir = std::env::temp_dir().join(format!("dsh-bundled-nested-{}", std::process::id()));+ let nested = dir.join("resources").join(BUNDLED_PLUGINS_DIR).join("dsh-tauri");+ std::fs::create_dir_all(&nested).expect("create temp nested bundled dir");+ std::fs::write(nested.join("package.json"), "{}").expect("write bundle manifest");++ let found = find_bundled_in_root(&dir, "dsh-tauri").expect("nested bundled dir should be found");+ assert_eq!(found, nested);++ std::fs::remove_dir_all(&dir).ok();+ }++ #[test]+ fn bundled_dir_discovers_flat_layout() {+ let dir = std::env::temp_dir().join(format!("dsh-bundled-flat-{}", std::process::id()));+ let flat = dir.join(BUNDLED_PLUGINS_DIR).join("dsh-tauri");+ std::fs::create_dir_all(&flat).expect("create temp flat bundled dir");+ std::fs::write(flat.join("package.json"), "{}").expect("write bundle manifest");++ let found = find_bundled_in_root(&dir, "dsh-tauri").expect("flat bundled dir should be found");+ assert_eq!(found, flat);++ std::fs::remove_dir_all(&dir).ok();+ }++ #[test]+ fn bundled_dir_requires_package_json() {+ // 无 package.json 的目录不是有效产物(prebuild 未执行)+ let dir = std::env::temp_dir().join(format!("dsh-bundled-empty-{}", std::process::id()));+ std::fs::create_dir_all(dir.join("preset-plugins").join("dsh-tauri")).expect("create empty dir");+ assert!(find_bundled_in_root(&dir, "dsh-tauri").is_none());+ std::fs::remove_dir_all(&dir).ok();+ }++ #[test]+ fn file_dep_spec_normalizes_windows_separators() {+ assert_eq!(+ file_dep_spec(std::path::Path::new("C:\\Apps\\dsh\\resources\\preset-plugins\\dsh-tauri")),+ "file:C:/Apps/dsh/resources/preset-plugins/dsh-tauri"+ );+ // 尾部斜杠去除(Windows 盘符 C:\ 不会出现,路径恒为子目录)+ assert_eq!(+ file_dep_spec(std::path::Path::new("/opt/dsh/plugins/x/")),+ "file:/opt/dsh/plugins/x"+ );+ }++ #[cfg(debug_assertions)]+ #[test]+ fn dev_internal_dir_parses_plain_and_quoted_values() {+ assert_eq!(+ parse_dev_internal_dir("DEV_INTERNAL_PLUGINS_DIR=C:/dev/plugins\n"),+ Some(PathBuf::from("C:/dev/plugins"))+ );+ // 键值两侧空白 + 引号包裹+ assert_eq!(+ parse_dev_internal_dir("DEV_INTERNAL_PLUGINS_DIR = \"C:/my plugins\"\n"),+ Some(PathBuf::from("C:/my plugins"))+ );+ assert_eq!(+ parse_dev_internal_dir("DEV_INTERNAL_PLUGINS_DIR='D:/dev/plugins'\r\n"),+ Some(PathBuf::from("D:/dev/plugins"))+ );+ }++ #[cfg(debug_assertions)]+ #[test]+ fn dev_internal_dir_skips_comment_and_other_keys() {+ let content = "# comment\n\nVITE_FOO=1\nDEV_INTERNAL_PLUGINS_DIR=E:/plugins\n";+ assert_eq!(+ parse_dev_internal_dir(content),+ Some(PathBuf::from("E:/plugins"))+ );+ }++ #[cfg(debug_assertions)]+ #[test]+ fn dev_internal_dir_unset_when_missing_key_or_empty_value() {+ // 其它键或注释:视为未设置+ assert_eq!(parse_dev_internal_dir("FOO=bar\n"), None);+ assert_eq!(parse_dev_internal_dir("# DEV_INTERNAL_PLUGINS_DIR=C:/x\n"), None);+ // 显式置空:同样视为未设置(关闭覆盖)+ assert_eq!(parse_dev_internal_dir("DEV_INTERNAL_PLUGINS_DIR=\n"), None);+ }+#[test]fn fnv1a_matches_known_vectors() {// FNV-1a 64-bit 标准测试向量diff --git a/src-tauri/src/service/plugin/verify.rs b/src-tauri/src/service/plugin/verify.rsnew file mode 100644index 00000000..2ee41be5--- /dev/null+++ b/src-tauri/src/service/plugin/verify.rs@@ -0,0 +1,395 @@+//! 预装插件完整性自检与离线修复(verify)。+//!+//! 动机(issue #90):首次引导「安装全部推荐插件」后,若安装只把插件写入了+//! profile 清单(`package.json` 的 `dependencies` + `dsh.profile.bundles`)而+//! `node_modules` 中的插件产物缺失/损坏(安装中断、磁盘异常、半失败状态等),+//! dsh 服务启动时 loader 会对每个缺失插件抛 `ERR_MODULE_NOT_FOUND`(日志特征+//! `Cannot find package 'X' imported from .../cordis-plugin-loader/lib/index.js`),+//! 整个插件树加载失败、服务无法启动;更糟的是 pnpm 在损坏的 node_modules 上+//! 同样无法卸载/升级,用户被卡死在「启动失败 + 卸载失败」的组合里。+//!+//! 本模块在服务启动前核对「清单引用的预装插件是否真实存在于 profile 的+//! `node_modules`」,缺失时以现有 manifest + lockfile 为准在 profile 目录执行+//! `pnpm install` 重建依赖图(不解析新版本、不写清单,纯修复节点_modules 与+//! 锁文件一致);修复后仍缺失再给对应插件记录错误标记(前端插件面板显示异常,+//! 配合 [`super::install::remove`] 的离线卸载兜底即可移除问题插件)。+//!+//! 全程最佳努力:任何失败只记日志/错误标记,不阻断启动——最终启动失败场景仍+//! 由前端 recovery 对话框(`recovery.rs`)兜底定位与卸载。++use std::collections::HashMap;+use std::ffi::OsString;+use std::io::Read;+use std::path::{Path, PathBuf};+use std::sync::{Arc, Mutex};+use tauri::AppHandle;++use crate::config;+use crate::service::cli;++use super::errors;+use super::installed::{installed_name, profile_dir, ProfilePackageJson};+use super::install::{build_plugin_envs, harness_prefer_bundled_pnpm};+use super::preset::{load_presets, PreinstallPluginInfo};++/// 判定清单引用的预装插件是否缺失产物(纯函数,便于单测)。+///+/// 命中条件:插件被 profile 清单引用(`dependencies` 键或 `dsh.profile.bundles`+/// 列表,按实际 npm 包名 `installed_name`),但其包目录在 `node_modules` 下+/// 缺少 `package.json`(目录不存在、被删、或只是残壳都不算就绪)。+fn missing_plugin_ids(+ presets: &[PreinstallPluginInfo],+ dependencies: &HashMap<String, String>,+ bundles: &[String],+ node_modules: &Path,+) -> Vec<String> {+ presets+ .iter()+ .filter(|preset| {+ let name = installed_name(preset);+ let referenced =+ dependencies.contains_key(name) || bundles.iter().any(|bundle| bundle == name);+ if !referenced {+ return false;+ }+ !node_modules.join(name).join("package.json").is_file()+ })+ .map(|preset| preset.id.clone())+ .collect()+}++/// 给指定的缺失插件记录错误标记(前端插件面板显示异常并可卸载兜底)。+fn record_missing(app_handle: &AppHandle, ids: &[String], detail: &str) {+ for id in ids {+ if let Err(e) = errors::record(app_handle, id, "install", detail) {+ log::warn!("failed to record plugin integrity error for {id}: {e}");+ }+ }+}++/// 启动前调用:核对并修复预装插件完整性。最佳努力:失败只返回 Err(调用方告警)。+pub(crate) async fn ensure_preset_plugins(app_handle: &AppHandle) -> Result<(), String> {+ let presets = load_presets(app_handle);+ if presets.is_empty() {+ return Ok(());+ }++ let profile = profile_dir(app_handle);+ // 读取清单(dependencies + bundles);档案未初始化(无 package.json /+ // 不可解析)视为尚未安装任何插件,无需修复。+ let (dependencies, bundles) = match std::fs::read_to_string(profile.join("package.json")) {+ Ok(raw) => match serde_json::from_str::<ProfilePackageJson>(&raw) {+ Ok(manifest) => (+ manifest.dependencies,+ manifest+ .dsh+ .and_then(|d| d.profile)+ .map(|p| p.bundles)+ .unwrap_or_default(),+ ),+ Err(_) => return Ok(()),+ },+ Err(_) => return Ok(()),+ };++ let node_modules = profile.join("node_modules");+ let missing = missing_plugin_ids(&presets, &dependencies, &bundles, &node_modules);+ if missing.is_empty() {+ return Ok(());+ }+ log::warn!(+ "PRESET_PLUGIN_INTEGRITY: {} preset plugin(s) referenced by profile but missing from node_modules: {missing:?}",+ missing.len()+ );++ // 修复:在 profile 目录以现有 manifest + lockfile 为准执行 `pnpm install`,+ // 重建 node_modules 依赖图(不解析新版本)。修复失败不阻断启动,给缺失插件+ // 记录错误标记,让前端插件面板暴露问题、用户可走卸载兜底恢复。+ if let Err(e) = repair_with_pnpm_install(app_handle, &profile).await {+ log::warn!("PRESET_PLUGIN_REPAIR_FAILED: {e}");+ record_missing(app_handle, &missing, &e);+ return Ok(());+ }++ // 复检:dependencies/bundles 未变(pnpm install 不写清单),只需重新探测产物。+ let still_missing = missing_plugin_ids(&presets, &dependencies, &bundles, &node_modules);+ if still_missing.is_empty() {+ log::info!("preset plugin integrity repaired via pnpm install: {missing:?}");+ return Ok(());+ }+ let detail = format!(+ "PRESET_PLUGIN_STILL_MISSING: 修复后仍缺失以下插件产物: {still_missing:?}。可尝试卸载后重新安装。"+ );+ log::warn!("{detail}");+ record_missing(app_handle, &still_missing, &detail);+ Ok(())+}++/// 在 profile 目录执行 `pnpm install` 修复 node_modules 依赖图。+///+/// 选定直接执行的 pnpm(见 [`pnpm_direct`]),环境沿用桌面端插件子进程策略+/// (`build_plugin_envs`:隔离 $DSH_HOME、PATH 前置 shim 与 node 目录、pnpm+/// 选版开关),与安装/升级/卸载同一套行为,避免意外的 store/版本不兼容。+async fn repair_with_pnpm_install(app_handle: &AppHandle, profile: &Path) -> Result<(), String> {+ let (program, mut args) = pnpm_direct(app_handle).ok_or_else(|| {+ "PNPM_NOT_FOUND: 无捆绑 pnpm 且无用户 pnpm,无法修复插件依赖(如需可手动执行 pnpm install)"+ .to_string()+ })?;+ args.push(OsString::from("install"));++ let envs = build_plugin_envs(app_handle, harness_prefer_bundled_pnpm(app_handle));+ log::info!("repairing profile node_modules via pnpm install in {}", profile.display());+ let (exit_code, output) = spawn_and_wait(&program, &args, profile, &envs).await?;+ if exit_code != 0 {+ // 日志只保留输出尾部,避免刷屏(pnpm 失败信息集中在末尾)。+ let tail: String = output+ .chars()+ .rev()+ .take(REPAIR_OUTPUT_LIMIT)+ .collect::<String>()+ .chars()+ .rev()+ .collect();+ return Err(format!("PNPM_INSTALL_FAILED: exit code {exit_code}: {tail}"));+ }+ Ok(())+}++/// 修复输出日志保留的最大字符数(pnpm 失败信息集中在输出末尾)。+const REPAIR_OUTPUT_LIMIT: usize = 4000;++/// 选定修复用的 pnpm 直接执行程序:(program, 前置参数)。+///+/// 与 [`super::install::ensure_pnpm`] 同一套 store 主版本感知策略(pnpm 10 与 11+/// 的 store 布局互不兼容,主版本不一致会 `ERR_PNPM_UNEXPECTED_STORE` 失败),+/// 但修复路径**不触发下载**(启动阶段零额外下载):+/// - 档案 store 主版本已知 → 优先选主版本一致的 pnpm(捆绑版 → 用户版);+/// - store 未知(全新档案/未装过依赖)→ 捆绑版优先,否则用户版;+/// - 全不匹配时仍退回捆绑版尽力一试(失败由调用方记录错误标记)。+///+/// Windows 上 `.cmd`/`.bat` 无法被 CreateProcess 直接执行(需 cmd.exe 解析),+/// 用户 pnpm 只接受 `.exe`。+fn pnpm_direct(app_handle: &AppHandle) -> Option<(PathBuf, Vec<OsString>)> {+ use super::install::{bundled_pnpm_major, profile_store_major, user_pnpm_major_version};++ let bundled = config::get_pnpm_binary_path(app_handle);+ let bundled_ready = bundled.exists();+ let store = profile_store_major(app_handle);+ let bundled_matches = bundled_ready && store.is_none_or(|s| bundled_pnpm_major(app_handle) == Some(s));++ if bundled_matches {+ let node = config::get_node_binary_path(app_handle);+ return Some((node, vec![bundled.into_os_string()]));+ }++ // 用户 pnpm 主版本与 store 一致(或 store 未知)都可直接用+ if let Some(user) = cli::find_user_pnpm(app_handle) {+ #[cfg(windows)]+ let spawnable = user.extension().and_then(|e| e.to_str()) == Some("exe");+ #[cfg(not(windows))]+ let spawnable = true;+ if spawnable && store.is_none_or(|s| user_pnpm_major_version(app_handle) == Some(s)) {+ return Some((user, Vec::new()));+ }+ }++ // 都不匹配:退回捆绑版尽力一试(pnpm 会因 store 不兼容失败,由调用方记录)+ if bundled_ready {+ let node = config::get_node_binary_path(app_handle);+ return Some((node, vec![bundled.into_os_string()]));+ }+ None+}++/// 启动子进程 `program args...`(cwd=`cwd`)并等待退出,返回 (退出码, 合并输出)。+///+/// Windows 复用隐藏控制台方案(`workflow::win_spawn`):GUI 进程直接以+/// CREATE_NO_WINDOW 启动会让 node 的子进程各自新建可见控制台窗口(黑窗闪烁)。+/// 原始进程句柄(`*mut c_void`)非 Send,整个「spawn + 读管道 + 等待」都在单个+/// `spawn_blocking` 内完成(与 `plugin::process` 的等待语义一致),句柄不外传。+async fn spawn_and_wait(+ program: &Path,+ args: &[OsString],+ cwd: &Path,+ envs: &HashMap<String, String>,+) -> Result<(i32, String), String> {+ let captured = Arc::new(Mutex::new(String::new()));++ #[cfg(windows)]+ {+ use crate::service::workflow;+ use std::time::Duration;++ let program = program.to_path_buf();+ let args = args.to_vec();+ let cwd = cwd.to_path_buf();+ let envs = envs.clone();+ let captured = captured.clone();+ let (exit_code, output) = tauri::async_runtime::spawn_blocking(move || {+ use windows_sys::Win32::Foundation::CloseHandle;+ use windows_sys::Win32::System::Threading::{+ GetExitCodeProcess, WaitForSingleObject, INFINITE,+ };++ let (stdout, stderr, handle) =+ workflow::win_spawn::spawn_with_hidden_console_tracked(+ &program,+ &args,+ Some(&cwd),+ &envs,+ )+ .map_err(|e| format!("PNPM_REPAIR_SPAWN: {e}"))?;+ drain_pipe(stdout, captured.clone());+ drain_pipe(stderr, captured.clone());++ // 等孤立读取线程把管道内容写完(短命令通常已结束,此等待为兜底)。+ std::thread::sleep(Duration::from_millis(200));+ let exit_code = unsafe {+ let wait = WaitForSingleObject(handle, INFINITE);+ let mut code: u32 = 0;+ if GetExitCodeProcess(handle, &mut code) == 0 {+ code = wait;+ }+ CloseHandle(handle);+ code as i32+ };+ Ok::<_, String>((exit_code, drain_captured(captured)))+ })+ .await+ .map_err(|e| format!("PNPM_REPAIR_WAIT: {e}"))??;+ Ok((exit_code, output))+ }++ #[cfg(not(windows))]+ {+ use std::os::unix::process::CommandExt;+ use std::process::{Command, Stdio};++ let mut child = Command::new(program)+ .args(args)+ .envs(envs)+ .current_dir(cwd)+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .process_group(0) // 独立进程组,便于将来取消+ .spawn()+ .map_err(|e| format!("PNPM_REPAIR_SPAWN: {e}"))?;+ if let Some(out) = child.stdout.take() {+ drain_pipe(out, captured.clone());+ }+ if let Some(err) = child.stderr.take() {+ drain_pipe(err, captured.clone());+ }+ let exit_code = tauri::async_runtime::spawn_blocking(move || {+ child.wait().map(|s| s.code().unwrap_or(1)).unwrap_or(1)+ })+ .await+ .map_err(|e| format!("PNPM_REPAIR_WAIT: {e}"))?;++ tokio::time::sleep(std::time::Duration::from_millis(200)).await;+ Ok((exit_code, drain_captured(captured)))+ }+}++/// 在独立线程中把管道读取到 EOF 并追加进共享缓冲区(无事件转发:修复过程+/// 只需落日志,进度反馈非必需)。+fn drain_pipe<R: Read + Send + 'static>(mut reader: R, captured: Arc<Mutex<String>>) {+ std::thread::spawn(move || {+ let mut buffer = Vec::new();+ if reader.read_to_end(&mut buffer).is_err() {+ return;+ }+ if let Ok(mut acc) = captured.lock() {+ acc.push_str(&String::from_utf8_lossy(&buffer));+ }+ });+}++/// 取出(并清空)共享缓冲区中的全部捕获输出。+fn drain_captured(captured: Arc<Mutex<String>>) -> String {+ captured+ .lock()+ .map(|mut buf| std::mem::take(&mut *buf))+ .unwrap_or_default()+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::fs;++ fn preset(id: &str, package: Option<&str>) -> PreinstallPluginInfo {+ PreinstallPluginInfo {+ id: id.into(),+ spec: String::new(),+ package: package.map(String::from),+ name: String::new(),+ description: String::new(),+ repo_url: String::new(),+ recommended: false,+ fix: false,+ default_checked: false,+ win_only: false,+ internal: false,+ }+ }++ fn setup(dir_label: &str, present: &[&str]) -> PathBuf {+ let root = std::env::temp_dir().join(format!("dsh-verify-{}-{}", std::process::id(), dir_label));+ let _ = fs::remove_dir_all(&root);+ let node_modules = root.join("node_modules");+ for name in present {+ let dir = node_modules.join(name);+ fs::create_dir_all(&dir).expect("create node_modules pkg dir");+ fs::write(dir.join("package.json"), "{}").expect("write package.json");+ }+ root+ }++ #[test]+ fn missing_detects_absent_but_referenced() {+ let presets = vec![preset("dshmarket", None), preset("dsh-notification", None)];+ let deps = HashMap::from([+ ("dshmarket".to_string(), "1.0.0".to_string()),+ ("dsh-notification".to_string(), "github:omdsh-dev/dsh-notification".to_string()),+ ]);+ let bundles = vec!["dshmarket".to_string()];+ // dshmarket 在(引用且产物在);dsh-notification 被引用但产物缺失+ let root = setup("absent", &["dshmarket"]);+ let missing = missing_plugin_ids(&presets, &deps, &bundles, &root.join("node_modules"));+ assert_eq!(missing, vec!["dsh-notification"]);+ fs::remove_dir_all(&root).ok();+ }++ #[test]+ fn missing_ignores_unreferenced_and_present() {+ let presets = vec![preset("dshmarket", None), preset("dsh-better-sidebar", None)];+ let deps = HashMap::from([("dshmarket".to_string(), "^1.0.0".to_string())]);+ let bundles: Vec<String> = Vec::new();+ // 全部就绪:dshmarket 已装;better-sidebar 未被引用+ let root = setup("ok", &["dshmarket"]);+ let missing = missing_plugin_ids(&presets, &deps, &bundles, &root.join("node_modules"));+ assert!(missing.is_empty());+ fs::remove_dir_all(&root).ok();+ }++ #[test]+ fn missing_resolves_scoped_package_name() {+ // scoped 包名(installed_name 走 package 字段)对应 node_modules/@scope/name+ let presets = vec![preset("dsh-session-context-menu", Some("@baihejiangnan/dsh-session-context-menu"))];+ let deps = HashMap::from([(+ "@baihejiangnan/dsh-session-context-menu".to_string(),+ "github:baihejiangnan/dsh-session-context-menu".to_string(),+ )]);+ let bundles = vec!["@baihejiangnan/dsh-session-context-menu".to_string()];+ // 按 scoped 目录探测:存在 → 不缺失+ let root = setup("scoped", &["@baihejiangnan/dsh-session-context-menu"]);+ let missing = missing_plugin_ids(&presets, &deps, &bundles, &root.join("node_modules"));+ assert!(missing.is_empty());+ // 目录缺失 → 缺失+ let missing = missing_plugin_ids(&presets, &deps, &bundles, &root.join("missing-node_modules"));+ assert_eq!(missing, vec!["dsh-session-context-menu"]);+ fs::remove_dir_all(&root).ok();+ }+}\ No newline at end of filediff --git a/src-tauri/src/service/plugin/watch.rs b/src-tauri/src/service/plugin/watch.rsindex 70275789..a89720de 100644--- a/src-tauri/src/service/plugin/watch.rs+++ b/src-tauri/src/service/plugin/watch.rs@@ -341,6 +341,7 @@ mod tests {default_checked: false,win_only: false,package: None,+ internal: false,}]}diff --git a/src-tauri/src/service/workflow/mod.rs b/src-tauri/src/service/workflow/mod.rsindex ff25b7b1..6d828546 100644--- a/src-tauri/src/service/workflow/mod.rs+++ b/src-tauri/src/service/workflow/mod.rs@@ -725,6 +725,14 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {if let Err(e) = crate::service::plugin::ensure_internal_plugins(&app_handle).await {log::warn!("ensure internal plugins failed: {e}");}+ // 预装插件完整性自检:清单引用的预装插件若在 node_modules 缺失产物,服务+ // 启动时 loader 会对每个缺失插件抛 ERR_MODULE_NOT_FOUND 而整体失败(issue+ // #90,日志特征 `Cannot find package`)。用 `pnpm install` 以现有 manifest ++ // lockfile 为准重建依赖图修复;修复失败只告警并给缺失插件记录错误标记+ // (启动失败场景由前端 recovery 对话框兜底,见 service::plugin::recovery)。+ if let Err(e) = crate::service::plugin::ensure_preset_plugins(&app_handle).await {+ log::warn!("ensure preset plugins failed: {e}");+ }let mut envs: HashMap<String, String> = HashMap::new();envs.insert("DSH_HOME".to_string(),