DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
refactor(desktop)!: 统一资源清单为 manifest.jsonc 并引入依赖路径映射表
hairyf1c9c8ef9570f
diff --git a/README.en.md b/README.en.mdindex 28e837b2..0c901b01 100644--- a/README.en.md+++ b/README.en.md@@ -159,7 +159,7 @@ The prebuilt Harness bundle is published by [deepseek-harness-pkg](https://githuRemote assets and upstream catalogs that plugins reference at runtime:-- [PC2005-cloud/dsh-pet](https://github.com/PC2005-cloud/dsh-pet) — preset pet media (WebM motions, preview GIFs, `config.jsonc`); `preset-pets.json` pins `e1ff8c1`+- [PC2005-cloud/dsh-pet](https://github.com/PC2005-cloud/dsh-pet) — preset pet media (WebM motions, preview GIFs, `config.jsonc`); `pets.built-in` in `manifest.jsonc` pins `e1ff8c1`- [dsh-tauri/dsh-pet-mov](https://github.com/dsh-tauri/dsh-pet-mov) — macOS HEVC-alpha `.mov` mirror (WKWebView does not support VP9-alpha), pinned to `be0f3bb`- [hairyf/dsh-pet-component](https://github.com/hairyf/dsh-pet-component) — pet rendering component (npm `dsh-pet-component`)diff --git a/README.es.md b/README.es.mdindex c5db9d66..a0580c4e 100644--- a/README.es.md+++ b/README.es.md@@ -158,7 +158,7 @@ El paquete Harness prearmado lo publica [deepseek-harness-pkg](https://github.coRecursos remotos y catálogos oficiales que los plugins consumen en tiempo de ejecución:-- [PC2005-cloud/dsh-pet](https://github.com/PC2005-cloud/dsh-pet) — recursos de las mascotas predefinidas (movimientos WebM, GIF de vista previa, `config.jsonc`); `preset-pets.json` fija `e1ff8c1`+- [PC2005-cloud/dsh-pet](https://github.com/PC2005-cloud/dsh-pet) — recursos de las mascotas predefinidas (movimientos WebM, GIF de vista previa, `config.jsonc`); `pets.built-in` de `manifest.jsonc` fija `e1ff8c1`- [dsh-tauri/dsh-pet-mov](https://github.com/dsh-tauri/dsh-pet-mov) — espejo `.mov` HEVC-alpha para macOS (WKWebView no soporta VP9-alpha), fijado en `be0f3bb`- [hairyf/dsh-pet-component](https://github.com/hairyf/dsh-pet-component) — componente de render de la mascota (npm `dsh-pet-component`)diff --git a/README.md b/README.mdindex 5aea8bd6..3b48f331 100644--- a/README.md+++ b/README.md@@ -156,7 +156,7 @@ Harness 发行版由 [deepseek-harness-pkg](https://github.com/dsh-tauri/deepsee插件在运行时直接引用的远端素材与上游清单:-- [PC2005-cloud/dsh-pet](https://github.com/PC2005-cloud/dsh-pet) — 预设桌宠素材(WebM 动作、预览 GIF、`config.jsonc`),`preset-pets.json` 固定到 `e1ff8c1`+- [PC2005-cloud/dsh-pet](https://github.com/PC2005-cloud/dsh-pet) — 预设桌宠素材(WebM 动作、预览 GIF、`config.jsonc`),`manifest.jsonc` 的 `pets.built-in` 固定到 `e1ff8c1`- [dsh-tauri/dsh-pet-mov](https://github.com/dsh-tauri/dsh-pet-mov) — macOS HEVC-alpha `.mov` 镜像(WKWebView 不认 VP9-alpha),固定到 `be0f3bb`- [hairyf/dsh-pet-component](https://github.com/hairyf/dsh-pet-component) — 桌宠渲染组件(npm `dsh-pet-component`)diff --git a/packages/dsh-tauri-pet/THIRD_PARTY_NOTICES.md b/packages/dsh-tauri-pet/THIRD_PARTY_NOTICES.mdindex c2594024..eb5ece8e 100644--- a/packages/dsh-tauri-pet/THIRD_PARTY_NOTICES.md+++ b/packages/dsh-tauri-pet/THIRD_PARTY_NOTICES.md@@ -4,7 +4,7 @@The pet media assets (WebM animations, preview GIFs and `config.jsonc`) are **nolonger bundled or downloaded** by this package. The preset pet catalog-(`src-tauri/resources/preset-pets.json`) only registers the remote URLs, and the+(`pets.built-in` in `src-tauri/resources/manifest.jsonc`) only registers the remote URLs, and thepet window streams them directly from[`PC2005-cloud/dsh-pet`](https://github.com/PC2005-cloud/dsh-pet) at play time(macOS reads the HEVC-alpha `.mov` mirror fromdiff --git a/packages/dsh-tauri-pet/src/client/service/pet.invoke.ts b/packages/dsh-tauri-pet/src/client/service/pet.invoke.tsindex ff41ea9a..fd06959c 100644--- a/packages/dsh-tauri-pet/src/client/service/pet.invoke.ts+++ b/packages/dsh-tauri-pet/src/client/service/pet.invoke.ts@@ -35,7 +35,7 @@ export function postPetImport(name: string, data: string): Promise<PetListItem>return invoke<PetListItem>(CMD_IMPORT_PET, { name, data })}-/** 预设宠物清单(`resources/preset-pets.json`;条目直连远端素材,无安装态)。 */+/** 预设宠物清单(清单 `pets.built-in`;条目直连远端素材,无安装态)。 */export function getPresetPets(): Promise<PresetPetItem[]> {return invoke<PresetPetItem[]>(CMD_LIST_PRESET_PETS)}diff --git a/packages/dsh-tauri-pet/src/client/service/pet.types.ts b/packages/dsh-tauri-pet/src/client/service/pet.types.tsindex e24efc2f..061898e0 100644--- a/packages/dsh-tauri-pet/src/client/service/pet.types.ts+++ b/packages/dsh-tauri-pet/src/client/service/pet.types.ts@@ -21,7 +21,7 @@ export interface PetListItem {}/**- * 预设宠物清单条目(`resources/preset-pets.json` 的展示层投影)。+ * 预设宠物清单条目(`resources/manifest.jsonc` 的 `pets.built-in` 展示层投影)。** 预设不下载/安装:清单条目本身就是桌宠组件的渲染参数,设置页只需要展示字段,* 因此这里只声明投影形状,Rust 返回的其余字段前端原样忽略。diff --git a/packages/dsh-tauri-ui-playground/README.md b/packages/dsh-tauri-ui-playground/README.mdindex f90cef52..9052694b 100644--- a/packages/dsh-tauri-ui-playground/README.md+++ b/packages/dsh-tauri-ui-playground/README.md@@ -2,4 +2,4 @@Dev-only「UI 组件」调试面板,从 `dsh-tauri-ui` 拆出的独立包;组件层仍从 `dsh-tauri-ui/client` 复用。-该包 **不在** `src-tauri/resources/internal-plugins.json` 中:debug 构建由 `preset.rs` 的 `discover_dev_internal_plugins_at` 扫描 `packages/*` 发现并安装,release 构建不包含它。+该包 **不在** `src-tauri/resources/manifest.jsonc` 的 `plugins.built-in` 中:debug 构建由 `preset.rs` 的 `discover_dev_internal_plugins_at` 扫描 `packages/*` 发现并安装,release 构建不包含它。diff --git a/src-tauri/resources/README.md b/src-tauri/resources/README.mdindex 8441d71d..8c18a843 100644--- a/src-tauri/resources/README.md+++ b/src-tauri/resources/README.md@@ -39,29 +39,79 @@ a successful migration, and the one-shot migration is recorded in `.store.dat`(`dsh_home_migrated`). Migration failures are non-fatal: legacy data stays inplace and the migration retries on the next launch.-## Preset plugins — `preset-plugins.json`+## Resource manifest — `manifest.jsonc`-The first-run wizard / sidebar preset list is driven by `preset-plugins.json`-(loaded at runtime by `src-tauri/src/service/plugin/mod.rs` — **no Rust code-change needed to add a preset**). To propose a new preset plugin, open a PR-that adds one entry to the JSON array:+Every runtime resource catalog now lives in a single `manifest.jsonc` (JSONC:+`//` and `/* */` comments plus trailing commas are tolerated). It is parsed at+runtime by `src-tauri/src/config/manifest.rs` — **no Rust code change is needed+to add a preset, a built-in plugin, a deprecated id, a pet, or a dependency+mapping entry**.-> **Note on "new preset" detection**: the file ships with the installer and is-> force-overwritten on every install, so the app records a fingerprint of its-> content into the user-data settings after the wizard ends (install or skip)-> and re-opens the wizard on the next launch when the content differs. No extra-> action is needed when adding an entry.+```jsonc+{+ "engines": { "dsh": { "recommend": "0.1.5-rc.3", "minimum": "0.1.5-rc.1" } },+ "dependencies": {+ "node": {+ "engine": ">=22.22.0",+ "entry": { "windows": "node.exe", "default": "bin/node" },+ "managedRoot": "runtime",+ "overridable": true+ }+ },+ "plugins": { "depercated": [], "built-in": [], "preset": [] },+ "pets": { "built-in": [] }+}+```++| Section | Purpose |+| ------- | ------- |+| `engines.dsh.recommend` | Recommended core version (update hints, "above recommended" marks) |+| `engines.dsh.minimum` | Lowest supported core; older local cores are not preferred |+| `dependencies` | Dependency mapping spec: entry path per platform, default managed root, whether arbitrary overrides are allowed |+| `plugins.preset` | Community preset list shown by the first-run wizard / sidebar |+| `plugins.built-in` | Plugins shipped *with* the installer (auto-installed and auto-healed at startup) |+| `plugins.depercated` | Ids of presets that are no longer offered and get uninstalled at startup (key spelling is kept for compatibility) |+| `pets.built-in` | Preset pet catalog |++### Dependency mapping++The manifest only describes **where a dependency's entry lives inside its root**.+Which root is actually used is recorded per machine in+`<app-data>/dependencies.json` (debug: `<app-data>/dev/dependencies.json`):```json+{ "node": "C:/Users/you/AppData/Roaming/dsh-tauri/runtime", "pnpm": null, "dsh": "C:/Users/you/AppData/Roaming/dsh-tauri/dependencies/dsh" }+```++* a path → that root is used (any absolute location, or a `resources/...` token+ resolved against the installed app's resource root);+* `null` → the system environment satisfies this dependency, nothing is managed;+* a missing key → fall back to the manifest's `managedRoot` (under app data).++This is what makes a future "bundled core" build a manifest-only change:+point `managedRoot` (or the recorded root) at `resources/dsh` and no path logic+in `src-tauri` has to move.++### Preset plugins — `plugins.preset`++To propose a new preset plugin, open a PR that adds one entry:++> **Note on "new preset" detection**: the manifest ships with the installer and+> is force-overwritten on every install, so the app records a fingerprint of the+> `plugins` section into the user-data settings after the wizard ends (install or+> skip) and re-opens the wizard on the next launch when that section differs. No+> extra action is needed when adding an entry.++```jsonc{"id": "npm-package-name","spec": "npm-package-name | github:owner/repo","name": "Display name","description": "English description. · 中文描述",- "repoUrl": "https://github.com/owner/repo",+ "repo": "https://github.com/owner/repo","recommended": true,- "fix": false,- "winOnly": false+ "checked": true,+ "version": [{ "version": "^0.19.1", "dsh": "^0.1.5-rc.1" }]}```@@ -69,43 +119,49 @@ that adds one entry to the JSON array:| ------------- | -------- | ----------------------------------------------------------------------- || `id` | yes | Unique front-end key; must be a legal npm dependency name || `spec` | yes | Dependency form passed to `dsh plugin add` (npm name or `github:owner/repo`) |-| `version` | no | Inclusive installed-plugin version cap for core-driven automatic removal; not an installation pin |-| `dshSupportedVersion` | no | Highest supported core version; a newer core disables the preset in the UI and makes it eligible for automatic cleanup |+| `package` | no | Real npm package name when it differs from `id` || `name` | yes | Display name || `description` | yes | Shown in the wizard; bilingual (`en. · 中文`) is encouraged |-| `repoUrl` | yes | Repository page, opened via the "open repo" button |-| `recommended` | no | Green "recommended" chip, checked by default (defaults to `false`) |+| `repo` | yes | Repository page, opened via the "open repo" button |+| `recommended` | no | Green "recommended" chip (defaults to `false`) || `fix` | no | Yellow "fix" chip, checked by default — reserved for Windows minimal-mode fixes (defaults to `false`) |-| `defaultUnchecked` | no | Listed with the "recommended" chip but **not** pre-checked in the wizard (defaults to `false`) |+| `checked` | no | Pre-checked in the first-run wizard (defaults to `false`) || `winOnly` | no | Only listed on Windows (defaults to `false`) |+| `version` | no | Version-range declaration: a plain string (e.g. `"latest"`) or a matrix of `{ "version": <plugin range>, "dsh": <core range> }` pairs |-`id` must be unique across the file. The plugin itself is **not** vendored into-this repository — it is installed on the user's machine from `spec` at setup-time, so the PR only needs to add the JSON entry.+`id` must be unique across the section. The plugin itself is **not** vendored+into this repository — it is installed on the user's machine from `spec` at+setup time, so the PR only needs to add the JSON entry.### Core-driven automatic removal-When the running core is newer than `dshSupportedVersion`, startup cleanup can-remove the installed plugin. An optional `version` limits this cleanup to installed-versions **less than or equal to** that cap, using semantic-version precedence.-Higher installed versions are kept. If a cap is present but the installed version-is unknown or invalid, or the cap itself is invalid, core-driven cleanup is skipped.-Omitting `version` retains the previous uncapped cleanup behavior.+For a given active core version, the **last** `version` matrix entry whose `dsh`+range matches the core decides the compatible plugin version range — the matrix is+an ascending ladder, and older rules usually stay open-ended (`^0.1.5-rc.1` covers+all of `0.1.x`), so a release core can match several entries at once. That single+matching entry drives both the UI compatibility mark and core-driven cleanup:++* no matrix entry matches the running core → the preset is marked+ "unsupported by the current core" and installed copies inside any declared+ plugin range are removed;+* a matching entry exists but the installed plugin version falls outside its+ `version` range → the installed copy is removed so it can be reinstalled at a+ compatible version;+* a plain string declaration (or no declaration) never triggers removal.-`version` is metadata for automatic removal, **not** an installation pin: installation-still uses `spec`. It does not change the core-based UI compatibility check or manual-uninstall. The separate `deprecated-plugins.json` list is unaffected and continues-to remove listed plugins independently of these version caps.+The separate `plugins.depercated` list is unaffected and continues to remove+listed plugins independently of these ranges.### Built-in (internal) pluginsPlugins that must ship *with* the installer and are treated as part of the app-(auto-installed and auto-healed at startup) live in `internal-plugins.json`,-separate from the community preset list. Add an extra `package` field when the-real npm name differs from `id`. The entries are bundled at build time by-`scripts/build-plugins.ts` (via `pnpm deploy` of the workspace packages listed in-`packages/dsh-tauri-bundle`) into `resources/node_modules/<name>` (via-`bundle.resources`) and never appear in the first-run checklist. On startup the-app removes the legacy `resources/preset-plugins/` directory left by upgrades.-See the [built-in plugin guide](../../docs/BUILTIN_PLUGINS.md) for the full-workflow.\ No newline at end of file+(auto-installed and auto-healed at startup) live in `plugins.built-in`. Add a+`package` field when the real npm name differs from `id`. The entries are+bundled at build time by `scripts/build-plugins.ts` (via `pnpm deploy` of the+workspace packages listed in `packages/dsh-tauri-bundle`) into+`resources/node_modules/<name>` (via `bundle.resources`) and never appear in the+first-run checklist. On startup the app removes the legacy+`resources/preset-plugins/` directory left by upgrades. In debug builds the+workspace packages under `packages/*` are discovered directly, so a new built-in+plugin only needs its `dsh` field and a `plugins.built-in` entry for release+builds.\ No newline at end of filediff --git a/src-tauri/resources/deprecated-plugins.json b/src-tauri/resources/deprecated-plugins.jsondeleted file mode 100644index bda072bb..00000000--- a/src-tauri/resources/deprecated-plugins.json+++ /dev/null@@ -1,8 +0,0 @@-[- "dsh-win-terminal-inspector",- "dsh-session-context-menu",- "dsh-notification",- "dsh-tauri-panel",- "dsh-tauri-turnrewind",- "dsh-tauri-connection"-]diff --git a/src-tauri/resources/internal-plugins.json b/src-tauri/resources/internal-plugins.jsondeleted file mode 100644index 711e1b74..00000000--- a/src-tauri/resources/internal-plugins.json+++ /dev/null@@ -1,72 +0,0 @@-[- {- "id": "dsh-tauri",- "spec": "dsh-tauri",- "name": "DSH Tauri",- "description": "Message bridge for the DeepSeek Harness desktop shell. Also carries the desktop authentication adaptation: the embedded sandboxed WebView is cross-origin, so it cannot complete the SameSite=Strict browser-session cookie exchange.",- "repoUrl": "https://github.com/dsh-tauri-desk/dsh-tauri-plugins/tree/main/packages/dsh-tauri"- },- {- "id": "dsh-tauri-running-changes",- "spec": "dsh-tauri-running-changes",- "name": "DSH Running Changes",- "description": "Turn-level change tracking for the desktop shell: a private Git snapshot per agent turn and an input-dock chip reporting the changed files and +N -M of the turn that is currently running. Restoring files is handled by the recommended dsh-rewind plugin.",- "repoUrl": "https://github.com/dsh-tauri-desk/deepseek-harness-desktop/tree/main/packages/dsh-tauri-running-changes"- },- {- "id": "dsh-tauri-ui",- "spec": "dsh-tauri-ui",- "name": "DSH Tauri UI",- "description": "Customized Tauri UI plugin for the DeepSeek Harness desktop shell: provides the settings sidebar, settings sections, and shared UI integration points",- "repoUrl": "https://github.com/dsh-tauri-desk/dsh-tauri-plugins/tree/main/packages/dsh-tauri-ui"- },- {- "id": "dsh-tauri-worktree",- "spec": "dsh-tauri-worktree",- "name": "DSH Tauri Worktree",- "description": "Per-session isolated Git Worktree for the desktop shell: switch a conversation to its own isolated worktree, then check changes back into a local dsh/ branch or discard them.",- "repoUrl": "https://github.com/dsh-tauri-desk/dsh-tauri-plugins/tree/main/packages/dsh-tauri-worktree"- },- {- "id": "dsh-tauri-panel-extension",- "spec": "dsh-tauri-panel-extension",- "name": "DSH Tauri Panel Extension",- "description": "Skills, MCP, and the plugin market in the DeepSeek Harness desktop extension panel.",- "repoUrl": "https://github.com/dsh-tauri-desk/dsh-tauri-plugins/tree/main/packages/dsh-tauri-panel-extension"- },- {- "id": "dsh-tauri-panel-scheduler",- "spec": "dsh-tauri-panel-scheduler",- "name": "DSH Tauri Panel Scheduler",- "description": "Scheduled tasks for the DeepSeek Harness desktop panel: create daily/interval/workday/weekly automations, run them in fresh sessions on schedule, and review run history.",- "repoUrl": "https://github.com/dsh-tauri-desk/deepseek-harness-desktop/tree/main/packages/dsh-tauri-panel-scheduler"- },- {- "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"- },- {- "id": "dsh-tauri-pet",- "spec": "dsh-tauri-pet",- "name": "DSH Tauri Pet",- "description": "Persistent animated desktop pets with conversation activity states, bubbles, and Chat/Codex pet libraries.",- "repoUrl": "https://github.com/dsh-tauri-desk/deepseek-harness-desktop/tree/main/packages/dsh-tauri-pet"- },- {- "id": "dsh-tauri-rightclick",- "spec": "dsh-tauri-rightclick",- "name": "DSH Tauri Rightclick Menu",- "description": "Native-style right-click context menu for the desktop shell: quick actions for sessions, workspaces, conversation text, links, and inputs — in-house successor to the deprecated dsh-session-context-menu.",- "repoUrl": "https://github.com/dsh-tauri-desk/dsh-tauri-plugins/tree/main/packages/dsh-tauri-rightclick"- },- {- "id": "dsh-tauri-model-config",- "spec": "dsh-tauri-model-config",- "name": "DSH Tauri Model Config",- "description": "Model selection and parameter configuration for the DeepSeek Harness desktop shell",- "repoUrl": "https://github.com/dsh-tauri-desk/dsh-tauri-plugins/tree/main/packages/dsh-tauri-model-config"- }-]diff --git a/src-tauri/resources/manifest.jsonc b/src-tauri/resources/manifest.jsoncindex 088f3496..b99a0ea9 100644--- a/src-tauri/resources/manifest.jsonc+++ b/src-tauri/resources/manifest.jsonc@@ -19,6 +19,44 @@}}},+ "dependencies": {+ // 依赖映射规范:AppData 的 dependencies.json 只记录每个依赖的安装根+ // (null = 用系统环境);入口相对路径与默认托管根以本表为准。+ // 位置可为绝对路径(任意位置)、resources/*(安装包资源)或相对 AppData 的相对路径。+ "node": {+ "engine": ">=22.22.0",+ "entry": {+ "windows": "node.exe",+ "default": "bin/node"+ },+ "managedRoot": "runtime",+ "overridable": true+ },+ "pnpm": {+ "engine": ">=11.7.0",+ "entry": "bin/pnpm.cjs",+ "managedRoot": "dependencies/pnpm",+ "overridable": true+ },+ "dsh": {+ "engine": {+ "recommend": "0.1.5-rc.3",+ "minimum": "0.1.5-rc.1"+ },+ "entry": "node_modules/@deepseek-ai/dsh/lib/bin.js",+ "managedRoot": "dependencies/dsh",+ "overridable": true+ },+ "git": {+ "engine": ">2.53.0.2",+ "entry": {+ "windows": "cmd/git.exe",+ "default": "bin/git"+ },+ "managedRoot": "dependencies/git",+ "overridable": true+ }+ },"plugins": {"depercated": ["dsh-win-terminal-inspector",@@ -191,4 +229,4 @@}]}-}\ No newline at end of file+}diff --git a/src-tauri/resources/preset-pets.json b/src-tauri/resources/preset-pets.jsondeleted file mode 100644index f0616db1..00000000--- a/src-tauri/resources/preset-pets.json+++ /dev/null@@ -1,19 +0,0 @@-[- {- "id": "maid-deepseek-whale",- "name": "Maid DeepSeek Whale",- "desc": "一只小小的七比蓝头发的鲸鱼女仆Codex宠物,穿着海军蓝裙子,白色褶边,蓝眼睛,侧鳍和鲸鱼尾巴。",- "image": "https://raw.githubusercontent.com/PC2005-cloud/dsh-pet/e1ff8c1e4001878cbb80441262d530e16541f138/dsh-pet/assets/preview/daiji-huxi-xiuxian.gif",- "kind": "dsh",- "size": 220,- "config": "https://raw.githubusercontent.com/PC2005-cloud/dsh-pet/e1ff8c1e4001878cbb80441262d530e16541f138/dsh-pet/assets/config.jsonc",- "uri": {- "default": "https://raw.githubusercontent.com/PC2005-cloud/dsh-pet/e1ff8c1e4001878cbb80441262d530e16541f138/dsh-pet/assets/webm",- "mac": "https://raw.githubusercontent.com/dsh-tauri-desk/dsh-pet-mov/be0f3bb494cb71a4c73f916c0b92d25a3ab4d002/mov"- },- "ext": {- "default": "webm",- "mac": "mov"- }- }-]diff --git a/src-tauri/resources/preset-plugins.json b/src-tauri/resources/preset-plugins.jsondeleted file mode 100644index 417bd157..00000000--- a/src-tauri/resources/preset-plugins.json+++ /dev/null@@ -1,44 +0,0 @@-[-- {- "id": "dshmarket",- "spec": "dshmarket",- "version": "1.58.0",- "name": "DSH Market",- "description": "Visual plugin market inside DeepSeek Harness — browse, search, and one-click install community plugins.",- "repoUrl": "https://github.com/dsh-market/dsh-market",- "recommended": true,- "dshSupportedVersion": "0.1.7"- },- {- "id": "dsh-better-sidebar",- "spec": "dsh-better-sidebar",- "version": "0.19.1",- "name": "DSH Better Sidebar",- "description": "A VSCode-like right sidebar (explorer / editor / terminal / git / browser), isolated per conversation session. Exposes a service for other plugins to register sidebar tabs and file viewers.",- "repoUrl": "https://github.com/omdsh-dev/DSH-better-sidebar",- "recommended": true,- "dshSupportedVersion": "0.1.5-rc.2"- },- {- "id": "dsh-rewind-plugin",- "spec": "dsh-rewind-plugin",- "version": "0.12.2",- "name": "DSH Rewind",- "description": "In-window conversation rewind that never forks a new session, with a lightweight workspace backup that restores files together with the rewind.",- "repoUrl": "https://github.com/SiriLee/dsh-rewind",- "recommended": true,- "dshSupportedVersion": "0.1.5-rc.2"- },- {- "id": "@xmanrui/dsh-im",- "spec": "@xmanrui/dsh-im",- "version": "4.25.0",- "name": "DSH IM",- "description": "Connect IM channels (WeChat, Feishu, DingTalk, WeCom, QQ, Slack, Telegram, Discord, WhatsApp, iMessage and more) plus a public AI Office to a local DeepSeek Harness, with bot management in the desktop sidebar.",- "repoUrl": "https://github.com/xmanrui/dsh-im",- "recommended": true,- "defaultUnchecked": true,- "dshSupportedVersion": "0.1.5-rc.2"- }-]diff --git a/src-tauri/resources/version-recommend.json b/src-tauri/resources/version-recommend.jsondeleted file mode 100644index d3da7e28..00000000--- a/src-tauri/resources/version-recommend.json+++ /dev/null@@ -1,3 +0,0 @@-{- "dsh": "0.1.5-rc.3"-}diff --git a/src-tauri/src/bridge/guard.rs b/src-tauri/src/bridge/guard.rsindex bb4605a6..02fb7a55 100644--- a/src-tauri/src/bridge/guard.rs+++ b/src-tauri/src/bridge/guard.rs@@ -30,6 +30,15 @@ pub fn allowed_roots(app_handle: &AppHandle) -> Vec<PathBuf> {if let Some(dir) = crate::service::core::local_core_package_dir(app_handle) {roots.push(dir);}+ // 依赖映射表解析出的安装根:依赖可被映射到任意位置(含 `resources/*` 捆绑+ // 副本),核心/环境面板的「打开目录」必须能打开它们。+ for key in [+ crate::config::dependencies::DEP_NODE,+ crate::config::dependencies::DEP_PNPM,+ crate::config::dependencies::DEP_DSH,+ ] {+ roots.push(crate::config::dependencies::active_root(app_handle, key));+ }roots}diff --git a/src-tauri/src/bridge/lifecycle.rs b/src-tauri/src/bridge/lifecycle.rsindex 7523b7d0..8d1faae2 100644--- a/src-tauri/src/bridge/lifecycle.rs+++ b/src-tauri/src/bridge/lifecycle.rs@@ -93,6 +93,10 @@ pub async fn install_dependencies(app_handle: AppHandle) -> Result<bool, String>// 非 Windows 返回 true,保持原有依赖集合不变。let git_ok = config::git_runtime_ready(&app_handle);+ // 依赖路径映射回写:系统已有合规版本记 `null`(使用系统环境),只有真正托管在+ // 本地的内核才记路径。幂等,且内容未变化时不落盘。+ download::record_mappings(&app_handle);+// 启动自愈捷径:记录显示未安装、但运行时文件已全部在盘。常见于桌面端自更新// 安装器强杀进程,或上次启动时核心文件短暂缺失被 workflow::start 复位// `installed`(一旦复位,此后每次启动都会走进安装分支)。此时直接补记diff --git a/src-tauri/src/bridge/pet.rs b/src-tauri/src/bridge/pet.rsindex b41b59df..7b4eaa9e 100644--- a/src-tauri/src/bridge/pet.rs+++ b/src-tauri/src/bridge/pet.rs@@ -126,7 +126,7 @@ pub struct PetAsset {}/// 将缺省、旧版未限定 id 或非法选择归一化为空字符串(未选择任何宠物)。-/// 合法值:预设宠物 id(`resources/preset-pets.json` 的安全字符集)或来源限定 id。+/// 合法值:预设宠物 id(清单 `pets.built-in` 的安全字符集)或来源限定 id。/// 注意:不再默认给内置宠物 —— 全新安装下 active_pet 为空,由用户在设置页主动启用/// (预设条目直连远端素材,启用即用,无需任何安装步骤)。fn normalize_active_pet(active_pet: Option<&str>) -> String {diff --git a/src-tauri/src/bridge/preset_pet.rs b/src-tauri/src/bridge/preset_pet.rsindex 80493cfc..c38a40ca 100644--- a/src-tauri/src/bridge/preset_pet.rs+++ b/src-tauri/src/bridge/preset_pet.rs@@ -1,4 +1,4 @@-//! bridge/preset_pet.rs — 预设宠物清单(`resources/preset-pets.json`)。+//! bridge/preset_pet.rs — 预设宠物清单(`resources/manifest.jsonc` 的 `pets.built-in`)。//!//! 预设宠物不再下载到本地:清单里的条目本身就是 `dsh-pet-component` 的//! `<Pet>` 渲染参数(`config` / `uri` / `ext` / `kind` / `size`),pet 窗口按@@ -6,67 +6,13 @@//! 指向 HEVC-with-Alpha 的 `.mov` 素材:WKWebView 不认 VP9-alpha WebM)。//!//! 于是本模块只剩两件事,全部与「下载/解压/安装」无关:-//! 1. 定位并读取随安装包分发的清单;+//! 1. 从资源清单取 `pets.built-in`;//! 2. 校验形状(id 安全 + 唯一、地址非空、kind 合法)后原样交给前端。-use serde::{Deserialize, Serialize};use std::collections::HashSet;-use std::fs;-use std::path::PathBuf;-use tauri::{AppHandle, Manager};+use tauri::AppHandle;-/// 预设宠物清单文件名(随安装包分发,见 `tauri.conf.json` 的 bundle.resources)。-const PRESET_PETS_FILE: &str = "preset-pets.json";--/// 清单条目(`resources/preset-pets.json` 的一个元素)。-///-/// 字段名与 `dsh-pet-component` 的 props 一一对应,前端拿到后直接展开给 `<Pet>`;-/// `deny_unknown_fields` 保证清单写错字段(如 `sizeMB`)立即报错,而不是被静默忽略。-#[derive(Debug, Clone, Serialize, Deserialize)]-#[serde(rename_all = "camelCase", deny_unknown_fields)]-pub struct PresetPetSpec {- /// 唯一标识(`active_pet` 持久化的就是它)。- pub id: String,- /// 设置页展示名。- pub name: String,- /// 设置页展示描述。- #[serde(default, skip_serializing_if = "Option::is_none")]- pub desc: Option<String>,- /// 设置页卡片预览图(远端 URL,主窗口 CSP 需允许该图源)。- #[serde(default, skip_serializing_if = "Option::is_none")]- pub image: Option<String>,- /// 渲染器协议:`dsh`(逐动作透明视频)/ `codex`(单张雪碧图集);缺省由组件自动判定。- #[serde(default, skip_serializing_if = "Option::is_none")]- pub kind: Option<String>,- /// 渲染宽度 px(高度由协议画布比例推算);缺省取组件默认值。- #[serde(default, skip_serializing_if = "Option::is_none")]- pub size: Option<f64>,- /// 配置文件地址(dsh-pet `config.jsonc` 或 Codex `pet.json`)。- pub config: String,- /// 素材地址(dsh-pet 用 `{ default, mac }`:macOS 换 HEVC-alpha 素材)。- pub uri: PresetPetUri,- /// 素材后缀;缺省 `{ default: "webm", mac: "mov" }`(Codex 渲染器忽略)。- #[serde(default, skip_serializing_if = "Option::is_none")]- pub ext: Option<PresetPetExt>,-}--/// 素材基地址:`default` 必填,`mac` 覆盖 Apple 平台(WKWebView 不认 VP9-alpha)。-#[derive(Debug, Clone, Serialize, Deserialize)]-#[serde(rename_all = "camelCase", deny_unknown_fields)]-pub struct PresetPetUri {- pub default: String,- #[serde(default, skip_serializing_if = "Option::is_none")]- pub mac: Option<String>,-}--/// 素材后缀:`default` 必填,`mac` 覆盖 Apple 平台。-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]-#[serde(rename_all = "camelCase", deny_unknown_fields)]-pub struct PresetPetExt {- pub default: String,- #[serde(default, skip_serializing_if = "Option::is_none")]- pub mac: Option<String>,-}+use crate::config::manifest::{self, PresetPetSpec};/// 预设 id 是否安全(直接进入设置持久化与命令参数,只允许 ASCII 字母数字与 `-`/`_`)。pub(crate) fn safe_preset_id(id: &str) -> bool {@@ -77,37 +23,11 @@ pub(crate) fn safe_preset_id(id: &str) -> bool {.all(|value| value.is_ascii_alphanumeric() || value == '-' || value == '_')}-/// 定位清单文件:优先随安装包分发的资源目录,回落源码 `resources/`。-fn preset_pets_path(app: &AppHandle) -> Option<PathBuf> {- if let Ok(dir) = app.path().resource_dir() {- for candidate in [- dir.join(PRESET_PETS_FILE),- dir.join("resources").join(PRESET_PETS_FILE),- ] {- if candidate.exists() {- return Some(candidate);- }- }- }- let source = PathBuf::from(env!("CARGO_MANIFEST_DIR"))- .join("resources")- .join(PRESET_PETS_FILE);- source.exists().then_some(source)-}-/// 读取并校验清单。任何形状问题都返回带 `PET_PRESET_CATALOG_*` 前缀的错误,不做静默兜底。pub fn read_preset_catalog(app: &AppHandle) -> Result<Vec<PresetPetSpec>, String> {- let path = preset_pets_path(app)- .ok_or_else(|| "PET_PRESET_CATALOG_MISSING: preset-pets.json was not found".to_string())?;- let bytes = fs::read(&path).map_err(|error| {- format!(- "PET_PRESET_CATALOG_READ_FAILED: failed to read {}: {error}",- path.display()- )- })?;- let catalog: Vec<PresetPetSpec> = serde_json::from_slice(&bytes).map_err(|error| {- format!("PET_PRESET_CATALOG_INVALID: invalid preset-pets.json: {error}")- })?;+ let manifest = manifest::read(app)+ .ok_or_else(|| "PET_PRESET_CATALOG_MISSING: manifest.jsonc was not found".to_string())?;+ let catalog = manifest.pets.built_in;let mut ids = HashSet::new();for spec in &catalog {if !safe_preset_id(&spec.id) {@@ -163,21 +83,21 @@ mod tests {use super::*;fn shipped_catalog() -> Vec<PresetPetSpec> {- let bytes = fs::read(concat!(- env!("CARGO_MANIFEST_DIR"),- "/resources/preset-pets.json"- ))- .unwrap();- let catalog: Vec<PresetPetSpec> = serde_json::from_slice(&bytes).unwrap();- assert!(!catalog.is_empty(), "预设清单不应为空");- catalog+ manifest::read_at(+ &std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/manifest.jsonc"),+ )+ .expect("shipped manifest should be valid")+ .pets+ .built_in}#[test]fn shipped_catalog_is_valid_and_remote_only() {// 随包分发的清单是唯一事实来源:字段名/形状写错必须在这里炸,// 而不是等用户点「启用」才在运行时静默失败。- for spec in shipped_catalog() {+ let catalog = shipped_catalog();+ assert!(!catalog.is_empty(), "预设清单不应为空");+ for spec in catalog {assert!(safe_preset_id(&spec.id), "非法 id: {}", spec.id);assert!(!spec.name.trim().is_empty());assert!(!spec.config.trim().is_empty());@@ -259,7 +179,7 @@ mod tests {kind: Some("dsh".to_string()),size: Some(220.0),config: "https://example.com/config.jsonc".to_string(),- uri: PresetPetUri {+ uri: manifest::PresetPetUri {default: "https://example.com/webm".to_string(),mac: None,},diff --git a/src-tauri/src/config/constants.rs b/src-tauri/src/config/constants.rsindex 88cb69e6..8667806c 100644--- a/src-tauri/src/config/constants.rs+++ b/src-tauri/src/config/constants.rs@@ -73,25 +73,14 @@ pub const LEGACY_APP_IDENTIFIER: &str = "io.github.hairyf.deepseek-harness-deskt/// 核心不应与 release 共用,否则开发版更新/切换核心会替换正在运行的生产文件。pub const APP_DATA_DEV_DIR_NAME: &str = "dev";-/// 安装目录与 CLI 入口(相对安装目录)-pub const DSH_CORE_DIR: &str = "dsh";-pub const DSH_ENTRY_RELATIVE: &str = "node_modules/@deepseek-ai/dsh/lib/bin.js";+/// Harness 发行版清单文件名(相对安装根)。安装根、入口相对路径由+/// `resources/manifest.jsonc` 的 `dependencies.dsh` 与 AppData 依赖映射表决定。pub const DSH_MANIFEST_RELATIVE: &str = "package.json";-/// pnpm 安装目录与 CLI 入口(相对安装目录)-pub const PNPM_CORE_DIR: &str = "pnpm";-pub const PNPM_ENTRY_RELATIVE: &str = "bin/pnpm.cjs";-/// 开发构建的用户级 shim 根目录名,不与 release 的 CLI 集成目录冲突。#[cfg_attr(not(windows), allow(dead_code))] // 仅 Windows 的 bin 目录计算使用pub const CLI_ROOT_DEV_DIR_NAME: &str = "dev-dsh";-/// Windows 免安装 Git 的安装目录与 CLI 入口(相对安装目录)。-#[cfg_attr(not(windows), allow(dead_code))] // 仅 Windows 的 MinGit 安装路径使用-pub const MINGIT_CORE_DIR: &str = "git";-#[cfg_attr(not(windows), allow(dead_code))] // 仅 Windows 的 MinGit 安装路径使用-pub const MINGIT_ENTRY_RELATIVE: &str = "cmd/git.exe";-/// 旧版数据目录名:迁移前 $DSH_HOME 位于 `{app_data}/data/dsh`,/// 现仅用于 legacy 路径识别(见 service::migrate)。新 $DSH_HOME = 官方 `~/.dsh`。pub const DSH_DATA_DIR_NAME: &str = "dsh";diff --git a/src-tauri/src/config/dependencies.rs b/src-tauri/src/config/dependencies.rsnew file mode 100644index 00000000..4e462506--- /dev/null+++ b/src-tauri/src/config/dependencies.rs@@ -0,0 +1,341 @@+//! 依赖映射表:`<AppData>[/dev]/dependencies.json`。+//!+//! 桌面端不再假设 node/pnpm/dsh 一定装在固定的 AppData 路径下,而是把每个依赖+//! 的**安装根**记在映射表里:+//!+//! - 路径 → 使用该根(可为任意绝对路径,或 `resources/...` 令牌,见+//! [`super::manifest::resolve_location`]);+//! - `null` → 由系统环境满足,桌面端不托管该依赖;+//! - 键缺失 → 尚未探测,按清单的 `managedRoot` 默认托管根解析。+//!+//! 入口相对路径由清单 `dependencies.<key>.entry` 决定,因此「装在哪」与「入口形状」+//! 各有一处真值。将来做本地捆绑版只需把清单(或映射表)指向 `resources/*`,路径解析+//! 逻辑无需改动。写入单点收口到 [`record`],且内容不变时不落盘。++use serde::{Deserialize, Serialize};+use std::collections::BTreeMap;+use std::path::{Path, PathBuf};+use std::sync::Mutex;+use tauri::{AppHandle, Runtime};++use super::manifest;++/// 映射表文件名(debug 构建与其它依赖同处 `<base>/dev/` 之下)+pub const MAPPING_FILE: &str = "dependencies.json";++/// 逻辑依赖键+pub const DEP_NODE: &str = "node";+pub const DEP_PNPM: &str = "pnpm";+pub const DEP_DSH: &str = "dsh";+pub const DEP_GIT: &str = "git";++/// 读-改-写映射表的进程内互斥:多处(安装、检测、核心切换)都会写同一文件+static MAPPING_LOCK: Mutex<()> = Mutex::new(());++/// 映射表内容:键 → 安装根(`null` = 系统环境)+#[derive(Debug, Clone, Default, Serialize, Deserialize)]+#[serde(transparent)]+pub struct DependencyMapping(pub BTreeMap<String, Option<String>>);++impl DependencyMapping {+ /// 单键映射:`Some(None)` = 系统环境,`Some(Some(path))` = 指定根,`None` = 未记录+ pub fn get(&self, key: &str) -> Option<Option<PathBuf>> {+ self.0+ .get(key)+ .map(|value| value.as_ref().map(PathBuf::from))+ }++ /// 记录单键(`None` = 系统环境)+ pub fn set(&mut self, key: &str, value: Option<PathBuf>) {+ self.0.insert(+ key.to_string(),+ value.map(|path| path.to_string_lossy().into_owned()),+ );+ }+}++/// 映射表文件路径+pub fn mapping_path<R: Runtime>(app: &AppHandle<R>) -> PathBuf {+ super::runtime::get_base_dir(app).join(MAPPING_FILE)+}++/// 解析缓存:映射表在解析热路径上被反复读取(每个 `get_*_install_path`),按+/// 「路径 + mtime」命中即复用;写盘后由 [`write_mapping`] 直接刷新缓存。+static CACHE: Mutex<Option<(PathBuf, u64, DependencyMapping)>> = Mutex::new(None);++fn cached(path: &Path, stamp: u64) -> Option<DependencyMapping> {+ let guard = CACHE.lock().unwrap_or_else(|error| error.into_inner());+ guard+ .as_ref()+ .filter(|(cached_path, cached_stamp, _)| cached_path == path && *cached_stamp == stamp)+ .map(|(_, _, mapping)| mapping.clone())+}++fn store_cache(path: &Path, stamp: u64, mapping: &DependencyMapping) {+ let mut guard = CACHE.lock().unwrap_or_else(|error| error.into_inner());+ *guard = Some((path.to_path_buf(), stamp, mapping.clone()));+}++/// 读取映射表;缺失/损坏时返回空表(解析失败只告警,绝不阻断启动)+pub fn read_mapping<R: Runtime>(app: &AppHandle<R>) -> DependencyMapping {+ read_mapping_cached(&mapping_path(app))+}++fn read_mapping_cached(path: &Path) -> DependencyMapping {+ let stamp = super::file_stamp(path);+ if let Some(mapping) = cached(path, stamp) {+ return mapping;+ }+ let mapping = read_mapping_at(path);+ store_cache(path, stamp, &mapping);+ mapping+}++fn read_mapping_at(path: &Path) -> DependencyMapping {+ let Ok(raw) = std::fs::read_to_string(path) else {+ return DependencyMapping::default();+ };+ match serde_json::from_str(&raw) {+ Ok(mapping) => mapping,+ Err(error) => {+ log::warn!(+ "DEPENDENCY_MAPPING_INVALID: {}: {error}; falling back to manifest defaults",+ path.display()+ );+ DependencyMapping::default()+ }+ }+}++/// 落盘(原子替换:同目录临时文件 + rename)。内容未变化时不写盘。+pub fn write_mapping<R: Runtime>(+ app: &AppHandle<R>,+ mapping: &DependencyMapping,+) -> Result<(), String> {+ let path = mapping_path(app);+ let body = serde_json::to_string_pretty(mapping).map_err(|error| error.to_string())?;+ if std::fs::read_to_string(&path).is_ok_and(|current| current == body) {+ return Ok(());+ }+ if let Some(parent) = path.parent() {+ std::fs::create_dir_all(parent)+ .map_err(|error| format!("DEPENDENCY_MAPPING_WRITE_FAILED: {error}"))?;+ }+ let temp = path.with_extension("json.tmp");+ std::fs::write(&temp, &body)+ .map_err(|error| format!("DEPENDENCY_MAPPING_WRITE_FAILED: {error}"))?;+ std::fs::rename(&temp, &path).map_err(|error| {+ let _ = std::fs::remove_file(&temp);+ format!("DEPENDENCY_MAPPING_WRITE_FAILED: {error}")+ })?;+ // 同一秒内的写入可能不改变 mtime 粒度,这里显式刷新缓存而不是依赖文件时间。+ store_cache(&path, super::file_stamp(&path), mapping);+ Ok(())+}++/// 记录单个依赖的安装根(`None` = 系统环境)。+///+/// 映射表的唯一写入口;写入失败只告警——解析链路在下次启动时按清单默认根兜底,+/// 不该因为一次落盘失败阻断安装/启动。+pub fn record<R: Runtime>(app: &AppHandle<R>, key: &str, value: Option<PathBuf>) {+ let _guard = MAPPING_LOCK+ .lock()+ .unwrap_or_else(|error| error.into_inner());+ let current = read_mapping(app);+ let mut next = current.clone();+ next.set(key, value);+ if next.0 == current.0 {+ return;+ }+ if let Err(error) = write_mapping(app, &next) {+ log::warn!("DEPENDENCY_MAPPING_RECORD_FAILED: {key}: {error}");+ } else {+ log::info!(+ "dependency mapping updated: {key} = {}",+ next.0+ .get(key)+ .and_then(|value| value.clone())+ .unwrap_or_else(|| "<system>".to_string())+ );+ }+}++/// 单键映射(见 [`DependencyMapping::get`])+pub fn mapped<R: Runtime>(app: &AppHandle<R>, key: &str) -> Option<Option<PathBuf>> {+ read_mapping(app).get(key)+}++/// 清单声明的默认托管根(映射未记录或为系统时使用)+pub fn managed_root<R: Runtime>(app: &AppHandle<R>, key: &str) -> PathBuf {+ let declared = manifest::dependency_spec(app, key).and_then(|spec| spec.managed_root);+ match declared {+ Some(raw) => manifest::resolve_location(app, &raw),+ None => super::runtime::get_base_dir(app).join(default_managed_root(key)),+ }+}++/// 当前生效的依赖根:映射指定的根优先,否则回落清单默认托管根+pub fn active_root<R: Runtime>(app: &AppHandle<R>, key: &str) -> PathBuf {+ match mapped(app, key) {+ Some(Some(path)) => path,+ _ => managed_root(app, key),+ }+}++/// 入口相对路径(相对依赖根):清单 `dependencies.<key>.entry`,未声明时用内置默认+pub fn entry_relative<R: Runtime>(app: &AppHandle<R>, key: &str) -> PathBuf {+ let declared = manifest::dependency_spec(app, key)+ .and_then(|spec| spec.entry.resolve().map(str::to_string));+ match declared {+ Some(raw) => split_entry(&raw),+ None => split_entry(default_entry(key)),+ }+}++/// 当前生效的依赖入口绝对路径(不校验存在性)+pub fn binary_path<R: Runtime>(app: &AppHandle<R>, key: &str) -> PathBuf {+ active_root(app, key).join(entry_relative(app, key))+}++/// 入口路径 → 相对路径(统一分隔符;`/` 与 `\` 都接受)+fn split_entry(raw: &str) -> PathBuf {+ raw.split(['/', '\\'])+ .filter(|segment| !segment.is_empty())+ .collect()+}++fn default_managed_root(key: &str) -> &'static str {+ match key {+ DEP_NODE => "runtime",+ DEP_PNPM => "dependencies/pnpm",+ DEP_DSH => "dependencies/dsh",+ DEP_GIT => "dependencies/git",+ _ => "dependencies",+ }+}++fn default_entry(key: &str) -> &'static str {+ match key {+ DEP_NODE => {+ if cfg!(windows) {+ "node.exe"+ } else {+ "bin/node"+ }+ }+ DEP_PNPM => "bin/pnpm.cjs",+ DEP_DSH => "node_modules/@deepseek-ai/dsh/lib/bin.js",+ DEP_GIT => {+ if cfg!(windows) {+ "cmd/git.exe"+ } else {+ "bin/git"+ }+ }+ _ => "",+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn temp_path(tag: &str) -> PathBuf {+ std::env::temp_dir().join(format!(+ "dsh-deps-{tag}-{}-{}",+ std::process::id(),+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_nanos())+ .unwrap_or(0)+ ))+ }++ #[test]+ fn mapping_round_trips_system_and_path_roots() {+ let dir = temp_path("mapping");+ std::fs::create_dir_all(&dir).unwrap();+ let file = dir.join(MAPPING_FILE);++ let mut mapping = DependencyMapping::default();+ mapping.set(DEP_NODE, Some(PathBuf::from("C:/app/runtime")));+ mapping.set(DEP_PNPM, None);+ std::fs::write(&file, serde_json::to_string_pretty(&mapping).unwrap()).unwrap();++ let read = read_mapping_at(&file);+ assert_eq!(+ read.get(DEP_NODE),+ Some(Some(PathBuf::from("C:/app/runtime")))+ );+ assert_eq!(read.get(DEP_PNPM), Some(None));+ assert_eq!(read.get(DEP_DSH), None);+ assert!(read.get(DEP_NODE).is_some_and(|value| value.is_some()));++ let _ = std::fs::remove_dir_all(dir);+ }++ #[test]+ fn invalid_mapping_falls_back_to_empty_table() {+ let dir = temp_path("invalid");+ std::fs::create_dir_all(&dir).unwrap();+ let file = dir.join(MAPPING_FILE);+ std::fs::write(&file, "{ not json").unwrap();+ assert!(read_mapping_at(&file).0.is_empty());+ let _ = std::fs::remove_dir_all(dir);+ }++ #[test]+ fn entry_split_accepts_both_separators() {+ assert_eq!(+ split_entry("bin/pnpm.cjs"),+ PathBuf::from("bin").join("pnpm.cjs")+ );+ assert_eq!(+ split_entry(r"node_modules\@deepseek-ai\dsh\lib\bin.js"),+ PathBuf::from("node_modules")+ .join("@deepseek-ai")+ .join("dsh")+ .join("lib")+ .join("bin.js")+ );+ assert_eq!(split_entry("node.exe"), PathBuf::from("node.exe"));+ }++ #[test]+ fn default_roots_and_entries_match_the_manifest_spec() {+ assert_eq!(default_managed_root(DEP_NODE), "runtime");+ assert_eq!(default_managed_root(DEP_PNPM), "dependencies/pnpm");+ assert_eq!(default_managed_root(DEP_DSH), "dependencies/dsh");+ assert_eq!(default_entry(DEP_PNPM), "bin/pnpm.cjs");+ assert_eq!(+ default_entry(DEP_DSH),+ "node_modules/@deepseek-ai/dsh/lib/bin.js"+ );+ assert_eq!(+ default_entry(DEP_GIT),+ if cfg!(windows) {+ "cmd/git.exe"+ } else {+ "bin/git"+ }+ );+ }++ #[test]+ fn shipped_manifest_matches_builtin_defaults() {+ let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))+ .join("resources")+ .join(manifest::MANIFEST_FILE);+ let manifest = manifest::read_at(&path).expect("manifest should parse");+ for (key, root, entry) in [+ (DEP_NODE, "runtime", default_entry(DEP_NODE)),+ (DEP_PNPM, "dependencies/pnpm", default_entry(DEP_PNPM)),+ (DEP_DSH, "dependencies/dsh", default_entry(DEP_DSH)),+ (DEP_GIT, "dependencies/git", default_entry(DEP_GIT)),+ ] {+ let spec = manifest.dependencies.get(key).expect("spec should exist");+ assert_eq!(spec.managed_root.as_deref(), Some(root), "{key}");+ assert_eq!(spec.entry.resolve(), Some(entry), "{key}");+ }+ }+}diff --git a/src-tauri/src/config/manifest.rs b/src-tauri/src/config/manifest.rsnew file mode 100644index 00000000..1f00f97c--- /dev/null+++ b/src-tauri/src/config/manifest.rs@@ -0,0 +1,691 @@+//! 资源清单(`resources/manifest.jsonc`):引擎版本、插件目录、预设宠物与依赖+//! 映射规范的唯一真值来源。+//!+//! 定位顺序按构建区分:debug 优先源码 `resources/`(构建产物中的资源可能过期),+//! release 优先随安装包分发的资源目录,两者互为兜底。清单缺失/损坏只记日志并回落+//! 空清单——插件与宠物目录不是启动硬依赖;依赖映射的读写见 [`super::dependencies`]。++use serde::Deserialize;+use std::collections::BTreeMap;+use std::env;+use std::path::{Path, PathBuf};+use tauri::{AppHandle, Manager, Runtime};++/// 资源清单文件名+pub const MANIFEST_FILE: &str = "manifest.jsonc";++/// 资源清单根结构+#[derive(Debug, Clone, Default, Deserialize)]+#[serde(default)]+pub struct Manifest {+ pub engines: Engines,+ pub plugins: Plugins,+ pub pets: Pets,+ pub dependencies: BTreeMap<String, DependencySpec>,+}++/// 引擎版本声明(仅消费 `dsh`;node/pnpm/git 为发布侧声明,运行期常量另见 constants)+#[derive(Debug, Clone, Default, Deserialize)]+#[serde(default)]+pub struct Engines {+ pub dsh: DshEngine,+}++#[derive(Debug, Clone, Default, Deserialize)]+#[serde(default)]+pub struct DshEngine {+ /// 推荐核心版本(更新提示与「高于推荐版本」标记用)+ pub recommend: String,+ /// 最低支持核心版本(低于它的核心不参与本地优先)+ pub minimum: String,+}++#[derive(Debug, Clone, Default, serde::Serialize, Deserialize)]+#[serde(default)]+pub struct Plugins {+ /// 弃用插件 id(清单键为历史拼写 `depercated`)+ #[serde(rename = "depercated")]+ pub deprecated: Vec<String>,+ /// 随包内置插件+ #[serde(rename = "built-in")]+ pub built_in: Vec<PluginEntry>,+ /// 社区预设插件+ pub preset: Vec<PluginEntry>,+}++/// 插件清单条目+#[derive(Debug, Clone, Default, serde::Serialize, Deserialize)]+#[serde(default)]+pub struct PluginEntry {+ pub id: String,+ pub spec: String,+ pub name: String,+ pub description: String,+ /// 仓库地址(历史字段名 `repoUrl`)+ pub repo: String,+ /// profile `dependencies`/`bundles` 中的实际包名;缺省与 `id` 相同+ pub package: Option<String>,+ pub recommended: bool,+ /// 「修复」类项(Windows 极简模式),默认勾选+ pub fix: bool,+ /// 首次引导默认勾选+ pub checked: bool,+ /// 仅 Windows 列出+ #[serde(rename = "winOnly")]+ pub win_only: bool,+ /// 版本区间声明:`"latest"` 字符串或(插件版本区间 ↔ 核心版本区间)配对矩阵+ #[serde(default, deserialize_with = "deserialize_version")]+ pub version: Option<PluginVersion>,+}++/// 插件版本声明+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]+#[serde(untagged)]+pub enum PluginVersion {+ /// 无区间语义的字符串声明(如 `"latest"`)+ Declared(String),+ /// (插件版本区间 ↔ 核心版本区间)配对矩阵+ Matrix(Vec<VersionPair>),+}++/// 版本配对:`dsh` 核心区间命中时,兼容的插件版本为 `version` 区间+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, Deserialize)]+pub struct VersionPair {+ pub version: String,+ pub dsh: String,+}++/// 区间是否命中给定版本(区间无法解析时视为不命中)+fn req_matches(req: &str, version: &semver::Version) -> bool {+ semver::VersionReq::parse(req)+ .map(|req| req.matches(version))+ .unwrap_or(false)+}++impl PluginVersion {+ /// 当前核心命中的插件版本区间(没有任何 `dsh` 区间命中时为 None)。+ ///+ /// 矩阵按**升序阶梯**声明(越靠后的一代越新)。较旧的区间通常对上界开放+ /// (如 `^0.1.5-rc.1` 覆盖整个 0.1.x),因此 release 核心可能同时落在多条区间内;+ /// 此时必须取**最后**一条命中规则,否则会把新插件按旧一代的版本区间判成不兼容,+ /// 进而在 `retire_on` 下被误退役。+ pub fn plugin_req_for_core(&self, core: Option<&str>) -> Option<&str> {+ let PluginVersion::Matrix(pairs) = self else {+ return None;+ };+ let core = semver::Version::parse(core?).ok()?;+ pairs+ .iter()+ .rev()+ .find(|pair| req_matches(&pair.dsh, &core))+ .map(|pair| pair.version.as_str())+ }++ /// 核心是否已超出矩阵声明的全部 `dsh` 区间(无矩阵或版本不可解析时为 false)+ pub fn unsupported_on(&self, core: Option<&str>) -> bool {+ let PluginVersion::Matrix(pairs) = self else {+ return false;+ };+ let Some(Ok(core)) = core.map(semver::Version::parse) else {+ return false;+ };+ !pairs.iter().any(|pair| req_matches(&pair.dsh, &core))+ }++ /// 已安装版本是否落在矩阵声明的任一同代区间内(核心已超出时的清理判定)+ pub fn matches_any_declared(&self, installed: Option<&str>) -> bool {+ let PluginVersion::Matrix(pairs) = self else {+ return false;+ };+ let Some(Ok(installed)) = installed.map(semver::Version::parse) else {+ return false;+ };+ pairs+ .iter()+ .any(|pair| req_matches(&pair.version, &installed))+ }+}++fn deserialize_version<'de, D>(deserializer: D) -> Result<Option<PluginVersion>, D::Error>+where+ D: serde::Deserializer<'de>,+{+ #[derive(Deserialize)]+ #[serde(untagged)]+ enum Raw {+ Declared(String),+ Matrix(Vec<VersionPair>),+ }+ Ok(match Option::<Raw>::deserialize(deserializer)? {+ None => None,+ Some(Raw::Declared(value)) => Some(PluginVersion::Declared(value)),+ Some(Raw::Matrix(pairs)) => Some(PluginVersion::Matrix(pairs)),+ })+}++/// 预设宠物目录+#[derive(Debug, Clone, Default, Deserialize)]+#[serde(default)]+pub struct Pets {+ #[serde(rename = "built-in")]+ pub built_in: Vec<PresetPetSpec>,+}++/// 预设宠物条目:字段名与 `dsh-pet-component` 的 props 一一对应,前端拿到后直接+/// 展开给 `<Pet>`;`deny_unknown_fields` 保证清单写错字段(如 `sizeMB`)立即报错。+#[derive(Debug, Clone, serde::Serialize, Deserialize)]+#[serde(rename_all = "camelCase", deny_unknown_fields)]+pub struct PresetPetSpec {+ pub id: String,+ pub name: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub desc: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub image: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub kind: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub size: Option<f64>,+ pub config: String,+ pub uri: PresetPetUri,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub ext: Option<PresetPetExt>,+}++/// 素材基地址:`default` 必填,`mac` 覆盖 Apple 平台(WKWebView 不认 VP9-alpha)+#[derive(Debug, Clone, serde::Serialize, Deserialize)]+#[serde(rename_all = "camelCase", deny_unknown_fields)]+pub struct PresetPetUri {+ pub default: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub mac: Option<String>,+}++#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, Deserialize)]+#[serde(rename_all = "camelCase", deny_unknown_fields)]+pub struct PresetPetExt {+ pub default: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub mac: Option<String>,+}++/// 依赖映射规范:入口相对路径与默认托管根+#[derive(Debug, Clone, Default, Deserialize)]+#[serde(default, rename_all = "camelCase")]+pub struct DependencySpec {+ /// 入口相对路径(相对依赖根),按平台覆盖:`default` / `windows` / `macos` / `linux`+ pub entry: EntrySpec,+ /// AppData 下的默认托管根(相对 AppData 基础目录,或 `resources/...`)+ pub managed_root: Option<String>,+ /// 是否允许运行期覆盖为任意位置+ pub overridable: bool,+}++/// 入口路径声明:单一路径字符串或按平台映射+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum EntrySpec {+ Single(String),+ Platform(BTreeMap<String, String>),+ Empty,+}++impl Default for EntrySpec {+ fn default() -> Self {+ EntrySpec::Empty+ }+}++impl<'de> Deserialize<'de> for EntrySpec {+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>+ where+ D: serde::Deserializer<'de>,+ {+ #[derive(Deserialize)]+ #[serde(untagged)]+ enum Raw {+ Single(String),+ Platform(BTreeMap<String, String>),+ }+ Ok(match Option::<Raw>::deserialize(deserializer)? {+ None => EntrySpec::Empty,+ Some(Raw::Single(value)) => EntrySpec::Single(value),+ Some(Raw::Platform(map)) => EntrySpec::Platform(map),+ })+ }+}++impl EntrySpec {+ /// 当前平台的入口相对路径+ pub fn resolve(&self) -> Option<&str> {+ match self {+ EntrySpec::Single(value) => (!value.is_empty()).then_some(value.as_str()),+ EntrySpec::Platform(map) => map+ .get(env::consts::OS)+ .or_else(|| map.get("default"))+ .map(String::as_str),+ EntrySpec::Empty => None,+ }+ }+}++/// 安装包资源根:`resources/...` 位置令牌与入口路径的解析基准。+///+/// Tauri 2 在 Windows 上 `resource_dir()` 恒等于 exe 所在目录,安装包与开发产物+/// 都会把资源按 `resources/**` 前缀落盘到 `{resource_dir}/resources/` 子目录,+/// 因此实际资源根可能是该子目录;两处都探测不到时回落到资源目录本身。+pub fn resource_root<R: Runtime>(app: &AppHandle<R>) -> Option<PathBuf> {+ let dir = app.path().resource_dir().ok()?;+ Some(pick_resource_root(&dir).unwrap_or(dir))+}++/// 资源根探测顺序:扁平布局(exe 同级)优先,再 `resources/` 子目录布局。+fn pick_resource_root(dir: &Path) -> Option<PathBuf> {+ if dir.join(MANIFEST_FILE).is_file() {+ return Some(dir.to_path_buf());+ }+ let nested = dir.join("resources");+ nested.join(MANIFEST_FILE).is_file().then_some(nested)+}++fn source_manifest_path() -> PathBuf {+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))+ .join("resources")+ .join(MANIFEST_FILE)+}++/// 定位资源清单:debug 优先当前 checkout,release 优先进安装包资源。+pub fn manifest_path<R: Runtime>(app: &AppHandle<R>) -> Option<PathBuf> {+ let mut candidates: Vec<PathBuf> = Vec::new();+ let packaged = resource_root(app).map(|root| root.join(MANIFEST_FILE));+ let source = source_manifest_path();+ if cfg!(debug_assertions) {+ candidates.push(source.clone());+ candidates.extend(packaged.clone());+ } else {+ candidates.extend(packaged.clone());+ candidates.push(source.clone());+ }+ candidates.into_iter().find(|path| path.is_file())+}++/// 解析结果缓存:清单是热路径(核心来源判定、插件清单、宠物列表、依赖映射都要读),+/// 按「路径 + mtime」命中即复用解析结果;debug 下编辑清单会因 mtime 变化而重载。+static CACHE: std::sync::Mutex<Option<(PathBuf, u64, Manifest)>> = std::sync::Mutex::new(None);++/// 在缓存命中的清单上取值;缺失/损坏时返回 None。+///+/// 缓存锁在闭包执行期间持有,因此闭包内**不得**再次调用本模块的读取接口+/// (std 互斥锁不可重入)。+pub fn with_manifest<R: Runtime, T>(+ app: &AppHandle<R>,+ pick: impl FnOnce(&Manifest) -> T,+) -> Option<T> {+ let path = match manifest_path(app) {+ Some(path) => path,+ None => {+ log::warn!("RESOURCE_MANIFEST_MISSING: {MANIFEST_FILE} not found in resource dir or source resources dir");+ return None;+ }+ };+ let stamp = super::file_stamp(&path);+ let mut guard = CACHE.lock().unwrap_or_else(|error| error.into_inner());+ let fresh = matches!(+ guard.as_ref(),+ Some((cached_path, cached_stamp, _)) if cached_path == &path && *cached_stamp == stamp+ );+ if !fresh {+ match read_at(&path) {+ Ok(manifest) => *guard = Some((path.clone(), stamp, manifest)),+ Err(error) => {+ log::error!("RESOURCE_MANIFEST_INVALID: {}: {error}", path.display());+ return None;+ }+ }+ }+ guard.as_ref().map(|(_, _, manifest)| pick(manifest))+}++/// 读取并解析资源清单;缺失/损坏时返回 None(调用方按空清单处理)+pub fn read<R: Runtime>(app: &AppHandle<R>) -> Option<Manifest> {+ with_manifest(app, Manifest::clone)+}++/// 读取指定路径的清单(单测与依赖映射共用)+pub fn read_at(path: &Path) -> Result<Manifest, String> {+ let raw = std::fs::read_to_string(path).map_err(|error| error.to_string())?;+ parse(&raw)+}++/// 解析 JSONC 文本:容忍 `//`、`/* */` 注释与尾逗号+pub fn parse(raw: &str) -> Result<Manifest, String> {+ let stripped = strip_jsonc(raw);+ serde_json::from_str(&stripped).map_err(|error| error.to_string())+}++/// 清单中的推荐 DSH 核心版本+pub fn recommended_dsh_version<R: Runtime>(app: &AppHandle<R>) -> Option<String> {+ let version = with_manifest(app, |manifest| {+ manifest.engines.dsh.recommend.trim().to_string()+ })?;+ (!version.is_empty() && semver::Version::parse(&version).is_ok()).then_some(version)+}++/// 清单中的最低支持 DSH 核心版本+pub fn minimum_dsh_version<R: Runtime>(app: &AppHandle<R>) -> Option<String> {+ let version = with_manifest(app, |manifest| {+ manifest.engines.dsh.minimum.trim().to_string()+ })?;+ (!version.is_empty()).then_some(version)+}++/// 版本是否高于推荐版本;任一版本无法解析时返回 false+pub fn is_above_recommended<R: Runtime>(app: &AppHandle<R>, version: &str) -> bool {+ let Some(recommended) = recommended_dsh_version(app) else {+ return false;+ };+ match (+ semver::Version::parse(version),+ semver::Version::parse(&recommended),+ ) {+ (Ok(actual), Ok(recommended)) => actual > recommended,+ _ => false,+ }+}++/// 依赖映射规范(清单缺失或未声明该键时返回 None)+pub fn dependency_spec<R: Runtime>(app: &AppHandle<R>, key: &str) -> Option<DependencySpec> {+ with_manifest(app, |manifest| manifest.dependencies.get(key).cloned())?+}++/// 位置令牌解析:`resources/...` 相对安装包资源根,其余相对 AppData 基础目录,+/// 绝对路径原样返回——依赖可以位于任意位置(AppData 托管、安装目录捆绑、+/// 或用户指定的其它盘符)。+pub fn resolve_location<R: Runtime>(app: &AppHandle<R>, raw: &str) -> PathBuf {+ resolve_location_from(+ &super::runtime::get_base_dir(app),+ resource_root(app).as_deref(),+ raw,+ )+}++/// [`resolve_location`] 的纯函数版本(不依赖 AppHandle,便于单测)+pub fn resolve_location_from(base: &Path, resource_root: Option<&Path>, raw: &str) -> PathBuf {+ let value = raw.trim();+ let path = PathBuf::from(value);+ if path.is_absolute() {+ return path;+ }+ let normalized = value.replace('\\', "/");+ if let Some(rest) = normalized.strip_prefix("./") {+ return resolve_location_from(base, resource_root, rest);+ }+ if let Some(rest) = normalized.strip_prefix("resources/") {+ if let Some(root) = resource_root {+ return root.join(rest.replace('/', std::path::MAIN_SEPARATOR_STR));+ }+ }+ base.join(value)+}++fn strip_jsonc(raw: &str) -> String {+ let chars: Vec<char> = raw.chars().collect();+ let mut out = String::with_capacity(raw.len());+ let mut i = 0;+ let mut in_string = false;+ while i < chars.len() {+ let c = chars[i];+ if in_string {+ out.push(c);+ if c == '\\' {+ if let Some(next) = chars.get(i + 1) {+ out.push(*next);+ i += 2;+ continue;+ }+ } else if c == '"' {+ in_string = false;+ }+ i += 1;+ continue;+ }+ if c == '"' {+ in_string = true;+ out.push(c);+ i += 1;+ continue;+ }+ if c == '/' && chars.get(i + 1) == Some(&'/') {+ while i < chars.len() && chars[i] != '\n' {+ i += 1;+ }+ continue;+ }+ if c == '/' && chars.get(i + 1) == Some(&'*') {+ i += 2;+ while i + 1 < chars.len() && !(chars[i] == '*' && chars[i + 1] == '/') {+ i += 1;+ }+ i = (i + 2).min(chars.len());+ continue;+ }+ out.push(c);+ i += 1;+ }+ strip_trailing_commas(&out)+}++fn strip_trailing_commas(raw: &str) -> String {+ let chars: Vec<char> = raw.chars().collect();+ let mut out = String::with_capacity(raw.len());+ let mut i = 0;+ let mut in_string = false;+ while i < chars.len() {+ let c = chars[i];+ if in_string {+ out.push(c);+ if c == '\\' {+ if let Some(next) = chars.get(i + 1) {+ out.push(*next);+ i += 2;+ continue;+ }+ } else if c == '"' {+ in_string = false;+ }+ i += 1;+ continue;+ }+ if c == '"' {+ in_string = true;+ out.push(c);+ i += 1;+ continue;+ }+ if c == ',' {+ let mut j = i + 1;+ while j < chars.len() && chars[j].is_whitespace() {+ j += 1;+ }+ if matches!(chars.get(j), Some('}') | Some(']')) {+ i += 1;+ continue;+ }+ }+ out.push(c);+ i += 1;+ }+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ fn shipped_manifest() -> Manifest {+ parse(&std::fs::read_to_string(source_manifest_path()).expect("manifest should exist"))+ .expect("shipped manifest should be valid")+ }++ #[test]+ fn shipped_manifest_carries_engines_plugins_pets_and_dependencies() {+ let manifest = shipped_manifest();+ assert_eq!(manifest.engines.dsh.recommend, "0.1.5-rc.3");+ assert_eq!(manifest.engines.dsh.minimum, "0.1.5-rc.1");+ assert!(!manifest.plugins.preset.is_empty());+ assert!(!manifest.plugins.built_in.is_empty());+ assert!(!manifest.plugins.deprecated.is_empty());+ assert!(!manifest.pets.built_in.is_empty());+ for key in ["node", "pnpm", "dsh", "git"] {+ assert!(+ manifest.dependencies.contains_key(key),+ "依赖映射规范缺少 {key}"+ );+ }+ }++ #[test]+ fn dependency_entries_resolve_per_platform() {+ let manifest = shipped_manifest();+ let node = &manifest.dependencies["node"];+ assert!(node.managed_root.is_some());+ assert!(node.overridable);+ assert!(node.entry.resolve().is_some());++ let pnpm = &manifest.dependencies["pnpm"];+ assert_eq!(pnpm.entry.resolve(), Some("bin/pnpm.cjs"));++ let dsh = &manifest.dependencies["dsh"];+ assert_eq!(+ dsh.entry.resolve(),+ Some("node_modules/@deepseek-ai/dsh/lib/bin.js")+ );+ }++ #[test]+ fn plugin_version_matrix_matches_core_ranges() {+ let matrix = PluginVersion::Matrix(vec![+ VersionPair {+ version: "^0.19.1".to_string(),+ dsh: "^0.1.5-rc.1".to_string(),+ },+ VersionPair {+ version: "^0.21.1".to_string(),+ dsh: "^0.1.7-rc.1".to_string(),+ },+ ]);+ assert_eq!(+ matrix.plugin_req_for_core(Some("0.1.5-rc.3")),+ Some("^0.19.1")+ );+ assert_eq!(+ matrix.plugin_req_for_core(Some("0.1.7-rc.2")),+ Some("^0.21.1")+ );+ // release 核心同时落在两条区间内:必须取最新一代规则,否则新插件会被误退役+ assert_eq!(matrix.plugin_req_for_core(Some("0.1.8")), Some("^0.21.1"));+ assert_eq!(matrix.plugin_req_for_core(Some("0.2.0")), None);+ assert!(!matrix.unsupported_on(Some("0.1.5-rc.3")));+ assert!(!matrix.unsupported_on(Some("0.1.8")));+ assert!(!matrix.unsupported_on(None));+ assert!(!matrix.unsupported_on(Some("not-a-version")));+ assert!(matrix.unsupported_on(Some("0.2.0")));+ assert!(matrix.matches_any_declared(Some("0.19.5")));+ assert!(!matrix.matches_any_declared(Some("0.25.0")));+ assert!(!matrix.matches_any_declared(None));+ }++ #[test]+ fn declared_version_string_is_never_unsupported() {+ let declared = PluginVersion::Declared("latest".to_string());+ assert!(!declared.unsupported_on(Some("9.9.9")));+ assert_eq!(declared.plugin_req_for_core(Some("9.9.9")), None);+ }++ #[test]+ fn jsonc_tolerates_comments_and_trailing_commas() {+ let raw = r#"+ {+ // 行注释+ "engines": { "dsh": { "recommend": "1.2.3", "minimum": "1.0.0" } },+ /* 块注释+ 跨行 */+ "dependencies": {+ "node": { "managedRoot": "runtime", "entry": { "windows": "node.exe", }, },+ },+ }+ "#;+ let manifest = parse(raw).expect("jsonc should parse");+ assert_eq!(manifest.engines.dsh.recommend, "1.2.3");+ assert_eq!(+ manifest.dependencies["node"].entry,+ EntrySpec::Platform(BTreeMap::from([(+ "windows".to_string(),+ "node.exe".to_string()+ )]))+ );+ }++ #[test]+ fn jsonc_keeps_comment_markers_inside_strings() {+ let raw = r#"{"plugins":{"preset":[{"id":"x","spec":"x","name":"a//b/*c*/","description":"d","repo":""}]}}"#;+ let manifest = parse(raw).expect("string content must survive comment stripping");+ assert_eq!(manifest.plugins.preset[0].name, "a//b/*c*/");+ }++ #[test]+ fn resource_root_probe_prefers_flat_then_nested() {+ let dir = std::env::temp_dir().join(format!(+ "dsh-manifest-probe-{}-{}",+ std::process::id(),+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_nanos())+ .unwrap_or(0)+ ));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();++ // 两处都没有 → 无资源根+ assert_eq!(pick_resource_root(&dir), None);++ // 只有嵌套布局 → 命中 `resources/` 子目录+ let nested = dir.join("resources");+ std::fs::create_dir_all(&nested).unwrap();+ std::fs::write(nested.join(MANIFEST_FILE), "{}").unwrap();+ assert_eq!(pick_resource_root(&dir), Some(nested.clone()));++ // 扁平布局存在 → 扁平优先(Tauri 2 的两种落盘形态同时出现时以 exe 同级为准)+ std::fs::write(dir.join(MANIFEST_FILE), "{}").unwrap();+ assert_eq!(pick_resource_root(&dir), Some(dir.clone()));++ let _ = std::fs::remove_dir_all(dir);+ }++ #[test]+ fn location_token_resolves_arbitrary_bases() {+ let base = PathBuf::from("C:/app/data");+ let resources = PathBuf::from("C:/app/resources");+ let absolute = if cfg!(windows) {+ "D:/anywhere"+ } else {+ "/anywhere"+ };++ assert_eq!(+ resolve_location_from(&base, Some(&resources), "dependencies/dsh"),+ base.join("dependencies/dsh")+ );+ assert_eq!(+ resolve_location_from(&base, Some(&resources), "resources/dsh"),+ resources.join("dsh")+ );+ assert_eq!(+ resolve_location_from(&base, Some(&resources), r"resources\node"),+ resources.join("node")+ );+ assert_eq!(+ resolve_location_from(&base, Some(&resources), absolute),+ PathBuf::from(absolute)+ );+ }+}diff --git a/src-tauri/src/config/mod.rs b/src-tauri/src/config/mod.rsindex ed4dbfce..0eabcec5 100644--- a/src-tauri/src/config/mod.rs+++ b/src-tauri/src/config/mod.rs@@ -1,22 +1,23 @@mod constants;+pub mod dependencies;mod format;pub mod i18n;+pub mod manifest;mod region;mod runtime;mod setting;mod theme;mod utils;-mod version_recommend;mod window_state;pub use constants::*;pub use format::*;+pub use manifest::{+ is_above_recommended as is_dsh_version_above_recommended, recommended_dsh_version,+};pub use region::*;pub use runtime::*;pub use setting::*;pub use theme::*;pub use utils::*;-pub use version_recommend::{- is_above_recommended as is_dsh_version_above_recommended, recommended_dsh_version,-};pub use window_state::*;diff --git a/src-tauri/src/config/runtime.rs b/src-tauri/src/config/runtime.rsindex 5b143946..7e7384e9 100644--- a/src-tauri/src/config/runtime.rs+++ b/src-tauri/src/config/runtime.rs@@ -6,6 +6,7 @@ use std::sync::atomic::{AtomicBool, Ordering};use tauri::{AppHandle, Manager, Runtime};use super::constants::*;+use super::dependencies;use super::format::get_dsh_service_url;use super::utils::search_node_binary;use super::{detect_region, Region};@@ -230,32 +231,26 @@ pub fn set_prefer_bundled_node_runtime(prefer: bool) {/// 已安装的捆绑运行时 node 二进制(未安装时返回 None)pub fn bundled_node_binary(app_handle: &tauri::AppHandle) -> Option<PathBuf> {let runtime_dir = get_node_install_path(app_handle);- // 使用 cfg 宏在编译时确定文件名- let (rel_path, bin_name) = if cfg!(windows) {- ("", "node.exe")- } else {- ("bin", "node")- };- let direct_path = runtime_dir.join(rel_path).join(bin_name);+ let entry = dependencies::entry_relative(app_handle, dependencies::DEP_NODE);+ let direct_path = runtime_dir.join(&entry);if direct_path.exists() {- Some(direct_path)- } else {- // 只有在直接路径不存在时才进行开销较大的递归搜索- search_node_binary(&runtime_dir, bin_name)+ return Some(direct_path);}+ // 只有在直接路径不存在时才进行开销较大的递归搜索(解压可能多套一层目录)+ let bin_name = entry.file_name()?.to_string_lossy().into_owned();+ search_node_binary(&runtime_dir, &bin_name)}/// Node.js 二进制路径///-/// 优先级:ABI 探测要求捆绑运行时(原生模块不匹配时的兜底)> 本地版本兼容的-/// Node.js 环境 > 已安装的捆绑运行时+/// 优先级:ABI 探测要求捆绑运行时(原生模块不匹配时的兜底)> 映射表(`null` =+/// 系统环境 / 路径 = 指定根)> 未记录时沿用「本地版本兼容优先」> 已安装的捆绑运行时。pub fn get_node_binary_path(app_handle: &tauri::AppHandle) -> PathBuf {let runtime_dir = get_node_install_path(app_handle);- let (rel_path, bin_name) = if cfg!(windows) {- ("", "node.exe")- } else {- ("bin", "node")- };+ let target = runtime_dir.join(dependencies::entry_relative(+ app_handle,+ dependencies::DEP_NODE,+ ));let bundled = bundled_node_binary(app_handle);if prefer_bundled_node_runtime() {@@ -271,40 +266,48 @@ pub fn get_node_binary_path(app_handle: &tauri::AppHandle) -> PathBuf {);}+ // 映射显式指定了托管根:该根下的运行时优先(缺失时才回落到系统环境)。+ let pinned_managed = matches!(+ dependencies::mapped(app_handle, dependencies::DEP_NODE),+ Some(Some(_))+ );+ if pinned_managed {+ if let Some(bundled) = bundled.clone() {+ log::debug!("Using mapped Node.js runtime root: {}", bundled.display());+ return bundled;+ }+ }+if let Some(local_node) = get_local_node_path() {log::debug!("Using local Node.js: {}", local_node.display());return local_node;}- bundled.unwrap_or_else(|| runtime_dir.join(rel_path).join(bin_name))+ bundled.unwrap_or(target)}pub fn get_node_install_path(app_handle: &tauri::AppHandle) -> PathBuf {- get_base_dir(app_handle).join("runtime")+ dependencies::active_root(app_handle, dependencies::DEP_NODE)}/// Harness 发行版安装目录pub fn get_dsh_install_path<R: Runtime>(app_handle: &AppHandle<R>) -> PathBuf {- get_base_dir(app_handle)- .join("dependencies")- .join(DSH_CORE_DIR)+ dependencies::active_root(app_handle, dependencies::DEP_DSH)}/// dsh CLI 入口pub fn get_dsh_binary_path<R: Runtime>(app_handle: &AppHandle<R>) -> PathBuf {- get_dsh_install_path(app_handle).join(DSH_ENTRY_RELATIVE)+ dependencies::binary_path(app_handle, dependencies::DEP_DSH)}/// pnpm 安装目录pub fn get_pnpm_install_path<R: Runtime>(app_handle: &AppHandle<R>) -> PathBuf {- get_base_dir(app_handle)- .join("dependencies")- .join(PNPM_CORE_DIR)+ dependencies::active_root(app_handle, dependencies::DEP_PNPM)}/// 捆绑 pnpm CLI 入口(纯 JS 发行,用 node 运行)pub fn get_pnpm_binary_path<R: Runtime>(app_handle: &AppHandle<R>) -> PathBuf {- get_pnpm_install_path(app_handle).join(PNPM_ENTRY_RELATIVE)+ dependencies::binary_path(app_handle, dependencies::DEP_PNPM)}/// pnpm 官方/镜像下载前缀:国内走 npmmirror registry,其他直连 npmjs.org@@ -327,15 +330,13 @@ pub fn get_pnpm_download_url() -> String {/// Windows 免安装 Git 的安装目录。#[cfg_attr(not(windows), allow(dead_code))] // 仅 Windows 的 Git 运行时探测使用pub fn get_mingit_install_path<R: Runtime>(app_handle: &AppHandle<R>) -> PathBuf {- get_base_dir(app_handle)- .join("dependencies")- .join(MINGIT_CORE_DIR)+ dependencies::active_root(app_handle, dependencies::DEP_GIT)}/// Windows 免安装 Git 的 CLI 入口。#[cfg_attr(not(windows), allow(dead_code))] // 仅 Windows 的 Git 运行时探测使用pub fn get_mingit_binary_path<R: Runtime>(app_handle: &AppHandle<R>) -> PathBuf {- get_mingit_install_path(app_handle).join(MINGIT_ENTRY_RELATIVE)+ dependencies::binary_path(app_handle, dependencies::DEP_GIT)}/// Windows MinGit 官方发行包文件名。diff --git a/src-tauri/src/config/setting.rs b/src-tauri/src/config/setting.rsindex 87cb3064..27e1721e 100644--- a/src-tauri/src/config/setting.rs+++ b/src-tauri/src/config/setting.rs@@ -25,7 +25,7 @@ pub struct Setting {/// 预装插件引导是否已完成(确认安装或跳过都算完成,之后不再弹出)#[serde(default)]pub preinstall_done: bool,- /// 上次引导结束时的 `preset-plugins.json` 内容指纹。资源文件每次安装都会被+ /// 上次引导结束时的清单 `plugins` 节内容指纹。资源清单每次安装都会被/// 强制覆盖、旧文件不复存在,只能把「上次看到的内容」记在这里,每次启动再比对:/// 内容有变更 → 重新进入预设引导。`None` = 老用户升级(无基线)→ 弹一次建立基线。#[serde(default)]diff --git a/src-tauri/src/config/utils.rs b/src-tauri/src/config/utils.rsindex cb8b02bc..dccf08cd 100644--- a/src-tauri/src/config/utils.rs+++ b/src-tauri/src/config/utils.rs@@ -1,5 +1,18 @@use std::path::{Path, PathBuf};+/// 文件的修改时间戳(纳秒,取不到时为 0)。+///+/// 资源清单与依赖映射表都是「进程内可反复读取、但 debug 下可能被编辑」的文件,+/// 用「路径 + 时间戳」作为解析缓存键即可在两者之间取得平衡。+pub fn file_stamp(path: &Path) -> u64 {+ std::fs::metadata(path)+ .and_then(|meta| meta.modified())+ .ok()+ .and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())+ .map(|duration| duration.as_nanos() as u64)+ .unwrap_or(0)+}+/// Linux inotify 文件监视上限的推荐最小值。////// harness 服务(dsh web)用 chokidar 递归监视 `$DSH_HOME/profiles/*`,node 的diff --git a/src-tauri/src/config/version_recommend.rs b/src-tauri/src/config/version_recommend.rsdeleted file mode 100644index 0e29942c..00000000--- a/src-tauri/src/config/version_recommend.rs+++ /dev/null@@ -1,114 +0,0 @@-//! DSH 核心推荐版本配置读取。-//!-//! 配置随应用资源分发,开发构建优先使用源码 resources 目录;读取失败时不限制-//! 版本,避免配置损坏阻断核心管理。--use serde::Deserialize;-use std::path::PathBuf;-use tauri::{AppHandle, Manager};--const FILE_NAME: &str = "version-recommend.json";--#[derive(Debug, Default, Deserialize)]-struct VersionRecommend {- dsh: Option<String>,-}--/// 解析推荐版本清单内容。-fn parse_recommended_version(content: &str) -> Option<String> {- let config: VersionRecommend = serde_json::from_str(content).ok()?;- let version = config.dsh?.trim().to_string();- (!version.is_empty() && semver::Version::parse(&version).is_ok()).then_some(version)-}--fn is_version_above(version: &str, recommended: &str) -> bool {- match (- semver::Version::parse(version),- semver::Version::parse(recommended),- ) {- (Ok(actual), Ok(recommended)) => actual > recommended,- _ => false,- }-}--fn manifest_candidates(source: PathBuf, resource_root: Option<PathBuf>) -> Vec<PathBuf> {- let mut paths = Vec::new();- // 开发版的 resource_dir 可能来自旧的构建产物;首次安装必须以当前 checkout- // 中的清单为准,否则会用过期版本的摘要校验当前下载内容,稳定触发 mismatch。- if cfg!(debug_assertions) {- paths.push(source.clone());- }- if let Some(root) = resource_root {- paths.extend([root.join(FILE_NAME), root.join("resources").join(FILE_NAME)]);- }- if !cfg!(debug_assertions) {- paths.push(source);- }- paths-}--fn manifest_path(app_handle: &AppHandle) -> Option<PathBuf> {- let source = PathBuf::from(env!("CARGO_MANIFEST_DIR"))- .join("resources")- .join(FILE_NAME);- manifest_candidates(source, app_handle.path().resource_dir().ok())- .into_iter()- .find(|path| path.is_file())-}--/// 返回配置中的推荐 DSH 版本。-pub fn recommended_dsh_version(app_handle: &AppHandle) -> Option<String> {- let path = manifest_path(app_handle)?;- let content = std::fs::read_to_string(&path).ok()?;- parse_recommended_version(&content)-}--/// 判断版本是否高于推荐版本;任一版本无法解析时返回 false。-pub fn is_above_recommended(app_handle: &AppHandle, version: &str) -> bool {- let Some(recommended) = recommended_dsh_version(app_handle) else {- return false;- };- is_version_above(version, &recommended)-}--#[cfg(test)]-mod tests {- use super::{is_version_above, manifest_candidates, parse_recommended_version};- use std::path::PathBuf;-- #[test]- fn development_manifest_candidates_prioritize_source_resources() {- let source = PathBuf::from(r"checkout\src-tauri\resources\version-recommend.json");- let bundled = PathBuf::from(r"target\debug\resources");- let candidates = manifest_candidates(source.clone(), Some(bundled));-- if cfg!(debug_assertions) {- assert_eq!(candidates.first(), Some(&source));- } else {- assert_ne!(candidates.first(), Some(&source));- }- }-- #[test]- fn parses_valid_recommendation_and_trims_whitespace() {- assert_eq!(- parse_recommended_version(r#"{ "dsh": " 0.1.1-rc.2 " }"#),- Some("0.1.1-rc.2".to_string())- );- }-- #[test]- fn rejects_missing_or_invalid_recommendation() {- assert_eq!(parse_recommended_version(r#"{ "dsh": "latest" }"#), None);- assert_eq!(parse_recommended_version(r#"{}"#), None);- assert_eq!(parse_recommended_version("not json"), None);- }-- #[test]- fn compares_semver_without_treating_invalid_versions_as_risky() {- assert!(is_version_above("0.1.1-rc.3", "0.1.1-rc.2"));- assert!(!is_version_above("0.1.1-rc.2", "0.1.1-rc.2"));- assert!(!is_version_above("0.1.1-rc.1", "0.1.1-rc.2"));- assert!(!is_version_above("invalid", "0.1.1-rc.2"));- }-}diff --git a/src-tauri/src/service/cli/shim/build.rs b/src-tauri/src/service/cli/shim/build.rsindex 6aad118f..1d910ed6 100644--- a/src-tauri/src/service/cli/shim/build.rs+++ b/src-tauri/src/service/cli/shim/build.rs@@ -2,7 +2,7 @@//! 各构建函数是纯函数(便于测试),落盘见 [`super::write`]。//! shim 文本必须全英文:cmd/ps1 按系统代码页解析,中文注释会乱码成命令执行。-use std::path::Path;+use std::path::{Path, PathBuf};use super::escape_path_cmd;use super::escape_path_ps1;@@ -14,6 +14,35 @@ use super::templates::{SH_NODE_RESOLVE,};+/// shim 内烘焙的依赖路径:全部来自运行时解析(依赖映射表 + 清单 `entry`),+/// 因此 shim 不再假设 AppData 下的 `dependencies/<name>` 布局,也不依赖+/// `APP_DIR` 推导——依赖可以被映射到任意位置(含 `resources/*` 捆绑副本)。+#[derive(Debug, Clone)]+pub struct ShimPaths {+ /// node 可执行文件绝对路径+ pub node_bin: PathBuf,+ /// dsh `bin.js` 绝对路径+ pub dsh_bin: PathBuf,+ /// pnpm `pnpm.cjs` 绝对路径+ pub pnpm_bin: PathBuf,+ /// 捆绑 MinGit 的 `cmd` 目录(系统 Git 缺 HTTPS helper 时注入 PATH)+ pub bundled_git_dir: Option<PathBuf>,+}++impl ShimPaths {+ /// node 所在目录(注入 PATH 用)+ fn node_dir(&self) -> PathBuf {+ self.node_bin+ .parent()+ .map(Path::to_path_buf)+ .unwrap_or_default()+ }++ fn git_dir(&self) -> PathBuf {+ self.bundled_git_dir.clone().unwrap_or_default()+ }+}+/// Windows `.cmd` 统一为 CRLF 行尾。////// 批处理由 `cmd.exe` 按行解析,本文件被 `.gitattributes` 固定为 LF(`*.rs@@ -29,23 +58,22 @@ fn normalize_cmd_line_endings(content: String) -> String {// dsh shim// ----------------------------------------------------------------------------/// Windows `dsh.cmd` 内容。`app_dir` 为应用数据目录(绝对路径,生成时写死),-/// `dsh_home` 为官方 `$DSH_HOME`(release 为 `~/.dsh`,生成时写死,与桌面端/-/// 官方一致)。+/// Windows `dsh.cmd` 内容。`paths` 为解析后的依赖入口路径,`dsh_home` 为官方+/// `$DSH_HOME`(release 为 `~/.dsh`,生成时写死,与桌面端/官方一致)。#[cfg_attr(debug_assertions, allow(dead_code))] // 仅 release 构建写入 dsh shim-pub fn build_cmd_shim(app_dir: &Path, dsh_home: &Path) -> String {- let dsh_bin = app_dir.join("dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js");-+pub fn build_cmd_shim(paths: &ShimPaths, dsh_home: &Path) -> String {normalize_cmd_line_endings(format!(r#"@echo offrem DeepSeek Harness Desktop - dsh command shim (generated)rem Do not edit: regenerated by the desktop app on install/startup.setlocal-set "APP_DIR={app_dir}"+set "NODE_BIN={node_bin}"+set "NODE_DIR={node_dir}"+set "GIT_DIR={git_dir}"rem Use bundled MinGit only when system Git lacks its HTTPS transport helper.set "SYSTEM_GIT_WORKS="for /f "delims=" %%g in ('git --exec-path 2^>nul') do if exist "%%g\git-remote-https.exe" set "SYSTEM_GIT_WORKS=1"-if not defined SYSTEM_GIT_WORKS if exist "%APP_DIR%\dependencies\git\cmd\git.exe" set "PATH=%APP_DIR%\dependencies\git\cmd;%PATH%"+if not defined SYSTEM_GIT_WORKS if exist "%GIT_DIR%\git.exe" set "PATH=%GIT_DIR%;%PATH%"{user_dsh}set "DSH_BIN={dsh_bin}"set "DSH_HOME={dsh_home}"@@ -64,9 +92,11 @@ exit /b 1echo [dsh] Node.js runtime not found. Please run DeepSeek Harness Desktop to install it first. 1>&2exit /b 1"#,- app_dir = escape_path_cmd(app_dir),- dsh_bin = escape_path_cmd(&dsh_bin),- dsh_home = escape_path_cmd(&dsh_home),+ node_bin = escape_path_cmd(&paths.node_bin),+ node_dir = escape_path_cmd(&paths.node_dir()),+ git_dir = escape_path_cmd(&paths.git_dir()),+ dsh_bin = escape_path_cmd(&paths.dsh_bin),+ dsh_home = escape_path_cmd(dsh_home),user_dsh = CMD_USER_DSH_PRECEDENCE,node_resolve = CMD_NODE_RESOLVE,))@@ -74,14 +104,14 @@ exit /b 1/// Windows `dsh.ps1` 内容#[cfg_attr(debug_assertions, allow(dead_code))] // 仅 release 构建写入 dsh shim-pub fn build_ps1_shim(app_dir: &Path, dsh_home: &Path) -> String {- let dsh_bin = app_dir.join("dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js");-+pub fn build_ps1_shim(paths: &ShimPaths, dsh_home: &Path) -> String {format!(r#"# DeepSeek Harness Desktop - dsh command shim (generated)# Do not edit: regenerated by the desktop app on install/startup.$ErrorActionPreference = "Stop"-$appDir = '{app_dir}'+$nodeBin = '{node_bin}'+$nodeDir = '{node_dir}'+$gitDir = '{git_dir}'$dshBin = '{dsh_bin}'# Use bundled MinGit only when system Git lacks its HTTPS transport helper.$systemGitWorks = $false@@ -89,11 +119,8 @@ try {{$gitExecPath = & git --exec-path 2> $null$systemGitWorks = ($LASTEXITCODE -eq 0) -and (Test-Path -LiteralPath (Join-Path $gitExecPath 'git-remote-https.exe'))}} catch {{}}-if (-not $systemGitWorks) {{- $gitDir = Join-Path $appDir 'dependencies\git\cmd'- if (Test-Path -LiteralPath (Join-Path $gitDir 'git.exe')) {{- $env:PATH = $gitDir + ';' + $env:PATH- }}+if (-not $systemGitWorks -and $gitDir -and (Test-Path -LiteralPath (Join-Path $gitDir 'git.exe'))) {{+ $env:PATH = $gitDir + ';' + $env:PATH}}{user_dsh}$dshHome = '{dsh_home}'@@ -107,25 +134,26 @@ $env:DSH_HOME = $dshHome& $node $dshBin @argsexit $LASTEXITCODE"#,- app_dir = escape_path_ps1(app_dir),- dsh_bin = escape_path_ps1(&dsh_bin),+ node_bin = escape_path_ps1(&paths.node_bin),+ node_dir = escape_path_ps1(&paths.node_dir()),+ git_dir = escape_path_ps1(&paths.git_dir()),+ dsh_bin = escape_path_ps1(&paths.dsh_bin),user_dsh = PS1_USER_DSH_PRECEDENCE,node_resolve = PS1_NODE_RESOLVE,- dsh_home = escape_path_ps1(&dsh_home),+ dsh_home = escape_path_ps1(dsh_home),)}/// Unix `dsh` shell 脚本内容(POSIX sh)#[cfg(not(windows))]#[cfg_attr(debug_assertions, allow(dead_code))] // 仅 release 构建写入 dsh shim-pub fn build_sh_shim(app_dir: &Path, dsh_home: &Path) -> String {- let dsh_bin = app_dir.join("dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js");-+pub fn build_sh_shim(paths: &ShimPaths, dsh_home: &Path) -> String {format!(r#"#!/bin/sh# DeepSeek Harness Desktop - dsh command shim (generated)# Do not edit: regenerated by the desktop app on install/startup.-APP_DIR='{app_dir}'+NODE_BIN='{node_bin}'+NODE_DIR='{node_dir}'DSH_BIN='{dsh_bin}'{user_dsh}export DSH_HOME='{dsh_home}'@@ -137,10 +165,11 @@ if [ ! -f "$DSH_BIN" ]; thenfiexec "$NODE" "$DSH_BIN" "$@""#,- app_dir = escape_path_sh(app_dir),- dsh_bin = escape_path_sh(&dsh_bin),+ node_bin = escape_path_sh(&paths.node_bin),+ node_dir = escape_path_sh(&paths.node_dir()),+ dsh_bin = escape_path_sh(&paths.dsh_bin),user_dsh = SH_USER_DSH_PRECEDENCE,- dsh_home = escape_path_sh(&dsh_home),+ dsh_home = escape_path_sh(dsh_home),node_resolve = SH_NODE_RESOLVE,)}@@ -161,20 +190,20 @@ exec "$NODE" "$DSH_BIN" "$@"/// - 不用 `findstr` 匹配路径(`\` 会被当正则转义导致过滤失效);/// - 块内变量判断用 for 变量(`%%~xp`)而非 `%VAR%`(块解析时机陷阱)。#[cfg_attr(all(not(windows), not(test)), allow(dead_code))] // 仅 Windows 的 shim 落盘与单测使用-pub fn build_pnpm_cmd_shim(app_dir: &Path) -> String {- let pnpm_bin = app_dir.join("dependencies/pnpm/bin/pnpm.cjs");-+pub fn build_pnpm_cmd_shim(paths: &ShimPaths) -> String {normalize_cmd_line_endings(format!(r#"@echo offrem DeepSeek Harness Desktop - pnpm command shim (generated)rem Do not edit: regenerated by the desktop app on install/startup.setlocal-set "APP_DIR={app_dir}"+set "NODE_BIN={node_bin}"+set "NODE_DIR={node_dir}"+set "GIT_DIR={git_dir}"set "PNPM_BIN={pnpm_bin}"rem Use bundled MinGit only when system Git lacks its HTTPS transport helper.set "SYSTEM_GIT_WORKS="for /f "delims=" %%g in ('git --exec-path 2^>nul') do if exist "%%g\git-remote-https.exe" set "SYSTEM_GIT_WORKS=1"-if not defined SYSTEM_GIT_WORKS if exist "%APP_DIR%\dependencies\git\cmd\git.exe" set "PATH=%APP_DIR%\dependencies\git\cmd;%PATH%"+if not defined SYSTEM_GIT_WORKS if exist "%GIT_DIR%\git.exe" set "PATH=%GIT_DIR%;%PATH%"rem App-internal installs (DSH_PREFER_BUNDLED_PNPM=1) use the bundled pnpm,rem falling back to the user's only when the bundled one is missing.@@ -242,8 +271,10 @@ exit /b 1echo [pnpm] Node.js runtime not found. Please run DeepSeek Harness Desktop to install it first. 1>&2exit /b 1"#,- app_dir = escape_path_cmd(app_dir),- pnpm_bin = escape_path_cmd(&pnpm_bin),+ node_bin = escape_path_cmd(&paths.node_bin),+ node_dir = escape_path_cmd(&paths.node_dir()),+ git_dir = escape_path_cmd(&paths.git_dir()),+ pnpm_bin = escape_path_cmd(&paths.pnpm_bin),node_resolve = CMD_NODE_RESOLVE,))}@@ -252,14 +283,14 @@ exit /b 1/// 排除本 shim 目录),否则用 node 运行捆绑 pnpm.cjs。/// `DSH_PREFER_BUNDLED_PNPM=1` 时捆绑版优先(见模块头注)。#[cfg_attr(all(not(windows), not(test)), allow(dead_code))] // 仅 Windows 的 shim 落盘与单测使用-pub fn build_pnpm_ps1_shim(app_dir: &Path) -> String {- let pnpm_bin = app_dir.join("dependencies/pnpm/bin/pnpm.cjs");-+pub fn build_pnpm_ps1_shim(paths: &ShimPaths) -> String {format!(r#"# DeepSeek Harness Desktop - pnpm command shim (generated)# Do not edit: regenerated by the desktop app on install/startup.$ErrorActionPreference = "Stop"-$appDir = '{app_dir}'+$nodeBin = '{node_bin}'+$nodeDir = '{node_dir}'+$gitDir = '{git_dir}'$pnpmBin = '{pnpm_bin}'# Use bundled MinGit only when system Git lacks its HTTPS transport helper.$systemGitWorks = $false@@ -267,11 +298,8 @@ try {{$gitExecPath = & git --exec-path 2> $null$systemGitWorks = ($LASTEXITCODE -eq 0) -and (Test-Path -LiteralPath (Join-Path $gitExecPath 'git-remote-https.exe'))}} catch {{}}-if (-not $systemGitWorks) {{- $gitDir = Join-Path $appDir 'dependencies\git\cmd'- if (Test-Path -LiteralPath (Join-Path $gitDir 'git.exe')) {{- $env:PATH = $gitDir + ';' + $env:PATH- }}+if (-not $systemGitWorks -and $gitDir -and (Test-Path -LiteralPath (Join-Path $gitDir 'git.exe'))) {{+ $env:PATH = $gitDir + ';' + $env:PATH}}$useBundled = $env:DSH_PREFER_BUNDLED_PNPM -eq '1' -and (Test-Path -LiteralPath $pnpmBin -PathType Leaf)@@ -309,8 +337,10 @@ if (-not (Test-Path -LiteralPath $pnpmBin)) {{& $node $pnpmBin @argsexit $LASTEXITCODE"#,- app_dir = escape_path_ps1(app_dir),- pnpm_bin = escape_path_ps1(&pnpm_bin),+ node_bin = escape_path_ps1(&paths.node_bin),+ node_dir = escape_path_ps1(&paths.node_dir()),+ git_dir = escape_path_ps1(&paths.git_dir()),+ pnpm_bin = escape_path_ps1(&paths.pnpm_bin),node_resolve = PS1_NODE_RESOLVE,)}@@ -319,14 +349,13 @@ exit $LASTEXITCODE/// 的用户 pnpm,否则用 node 运行捆绑 pnpm.cjs。`DSH_PREFER_BUNDLED_PNPM=1`/// 时捆绑版优先(见模块头注)。#[cfg_attr(all(windows, not(test)), allow(dead_code))]-pub fn build_pnpm_sh_shim(app_dir: &Path) -> String {- let pnpm_bin = app_dir.join("dependencies/pnpm/bin/pnpm.cjs");-+pub fn build_pnpm_sh_shim(paths: &ShimPaths) -> String {format!(r#"#!/bin/sh# DeepSeek Harness Desktop - pnpm command shim (generated)# Do not edit: regenerated by the desktop app on install/startup.-APP_DIR='{app_dir}'+NODE_BIN='{node_bin}'+NODE_DIR='{node_dir}'PNPM_BIN='{pnpm_bin}'USE_BUNDLED=@@ -371,24 +400,30 @@ if [ ! -f "$PNPM_BIN" ]; thenfiexec "$NODE" "$PNPM_BIN" "$@""#,- app_dir = escape_path_sh(app_dir),- pnpm_bin = escape_path_sh(&pnpm_bin),+ node_bin = escape_path_sh(&paths.node_bin),+ node_dir = escape_path_sh(&paths.node_dir()),+ pnpm_bin = escape_path_sh(&paths.pnpm_bin),node_resolve = SH_NODE_RESOLVE,)}#[cfg(test)]mod tests {- use super::super::test_util::{sample_app_dir, sample_dsh_home, temp_dir};+ use super::super::test_util::{+ sample_app_dir, sample_dsh_home, sample_shim_paths, shim_paths_for, temp_dir,+ };use super::*;use std::path::PathBuf;#[cfg(windows)]#[test]fn cmd_shim_contains_baked_paths() {- let content = build_cmd_shim(&sample_app_dir(), &sample_dsh_home());+ let paths = sample_shim_paths();+ let content = build_cmd_shim(&paths, &sample_dsh_home());assert!(content.contains(r"C:\Users\test\AppData\Roaming"));- assert!(content.contains("dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js"));+ // 解析后的依赖入口直接烘焙进 shim(不再有 APP_DIR 相对拼接)+ assert!(content.contains(&paths.dsh_bin.to_string_lossy().to_string()));+ assert!(content.contains(&paths.node_bin.to_string_lossy().to_string()));assert!(content.contains(r"C:\Users\test\.dsh"));assert!(!content.contains("data/dsh"));assert!(content.contains("%*"));@@ -397,7 +432,7 @@ mod tests {#[test]fn cmd_shim_escapes_percent() {let dir = PathBuf::from(r"C:\Users\100%test\AppData\Roaming\dsh-tauri");- let content = build_cmd_shim(&dir, &sample_dsh_home());+ let content = build_cmd_shim(&shim_paths_for(&dir), &sample_dsh_home());assert!(content.contains("100%%test"));assert!(!content.contains(r#"set "APP_DIR=C:\Users\100%test""#));}@@ -410,9 +445,9 @@ mod tests {for (name, content) in [("dsh.cmd",- build_cmd_shim(&sample_app_dir(), &sample_dsh_home()),+ build_cmd_shim(&sample_shim_paths(), &sample_dsh_home()),),- ("pnpm.cmd", build_pnpm_cmd_shim(&sample_app_dir())),+ ("pnpm.cmd", build_pnpm_cmd_shim(&sample_shim_paths())),] {assert!(content.contains("@echo off"), "{name}: missing header");let bytes = content.as_bytes();@@ -447,40 +482,47 @@ mod tests {#[cfg(windows)]#[test]fn windows_shims_configure_bundled_git_without_shadowing_system_git() {- let dsh_cmd = build_cmd_shim(&sample_app_dir(), &sample_dsh_home());- let dsh_ps1 = build_ps1_shim(&sample_app_dir(), &sample_dsh_home());- let pnpm_cmd = build_pnpm_cmd_shim(&sample_app_dir());- let pnpm_ps1 = build_pnpm_ps1_shim(&sample_app_dir());-+ let dsh_cmd = build_cmd_shim(&sample_shim_paths(), &sample_dsh_home());+ let dsh_ps1 = build_ps1_shim(&sample_shim_paths(), &sample_dsh_home());+ let pnpm_cmd = build_pnpm_cmd_shim(&sample_shim_paths());+ let pnpm_ps1 = build_pnpm_ps1_shim(&sample_shim_paths());++ let git_dir = sample_shim_paths()+ .bundled_git_dir+ .expect("bundled MinGit dir");+ let git_dir_text = git_dir.to_string_lossy().to_string();for content in [&dsh_cmd, &pnpm_cmd] {assert!(content.contains("git --exec-path 2^>nul"));assert!(content.contains("git-remote-https.exe"));- assert!(content.contains(r"dependencies\git\cmd\git.exe"));- assert!(content.contains(r"dependencies\git\cmd;%PATH%"));+ assert!(content.contains(r"%GIT_DIR%\git.exe"));+ assert!(content.contains("%GIT_DIR%;%PATH%"));+ assert!(content.contains(&git_dir_text));let system_probe = content.find("git --exec-path").expect("system Git probe");+ // 捆绑 Git 只在系统 Git 缺 HTTPS helper 时才注入 PATH:探测必须在前let bundled_git = content- .find(r"dependencies\git\cmd")- .expect("bundled Git path");+ .find("if not defined SYSTEM_GIT_WORKS")+ .expect("bundled Git activation");assert!(system_probe < bundled_git);}for content in [&dsh_ps1, &pnpm_ps1] {assert!(content.contains("& git --exec-path 2> $null"));assert!(content.contains("git-remote-https.exe"));- assert!(content.contains(r"dependencies\git\cmd"));+ assert!(content.contains(&git_dir_text));assert!(content.contains("$env:PATH = $gitDir + ';' + $env:PATH"));}}#[test]fn pnpm_cmd_shim_contains_user_precedence() {- let content = build_pnpm_cmd_shim(&sample_app_dir());+ let paths = sample_shim_paths();+ let content = build_pnpm_cmd_shim(&paths);assert!(content.contains("pnpm command shim"));- assert!(content.contains(r#"dependencies/pnpm/bin/pnpm.cjs"#));+ assert!(content.contains(&paths.pnpm_bin.to_string_lossy().to_string()));assert!(content.contains("where pnpm"));assert!(content.contains("SELF_PREFIX"));assert!(content.contains(r#"call "%USER_PNPM%" %*"#));assert!(content.contains(":use_bundled"));- assert!(content.contains("%APP_DIR%\\runtime\\node.exe"));+ assert!(content.contains(&paths.node_bin.to_string_lossy().to_string()));// 应用内部安装可经 DSH_PREFER_BUNDLED_PNPM=1 强制捆绑版(须在用户搜索前生效)assert!(content.contains("DSH_PREFER_BUNDLED_PNPM"));let env_at = content.find("DSH_PREFER_BUNDLED_PNPM").unwrap();@@ -506,7 +548,11 @@ mod tests {std::fs::create_dir_all(&shim_dir).unwrap();std::fs::create_dir_all(&user_dir).unwrap();let shim = shim_dir.join("pnpm.cmd");- std::fs::write(&shim, build_pnpm_cmd_shim(&dir.join("app"))).unwrap();+ std::fs::write(+ &shim,+ build_pnpm_cmd_shim(&shim_paths_for(&dir.join("app"))),+ )+ .unwrap();std::fs::write(user_dir.join("pnpm.cmd"),"@echo off\r\necho REAL_USER_PNPM\r\nexit /b 37\r\n",@@ -542,7 +588,11 @@ mod tests {let selected = dunce::canonicalize(&selected).unwrap();assert!(!selected.to_string_lossy().starts_with(r"\\?\"));let shim = dir.join("pnpm.cmd");- std::fs::write(&shim, build_pnpm_cmd_shim(&dir.join("app"))).unwrap();+ std::fs::write(+ &shim,+ build_pnpm_cmd_shim(&shim_paths_for(&dir.join("app"))),+ )+ .unwrap();let system_root = std::env::var_os("SystemRoot").unwrap_or_else(|| "C:\\Windows".into());let system32 = PathBuf::from(&system_root).join("System32");let output = std::process::Command::new(system32.join("cmd.exe"))@@ -574,7 +624,7 @@ mod tests {std::fs::write(&selected, "@echo off\r\necho SELECTED\r\n").unwrap();std::fs::write(&node, "@echo off\r\necho BUNDLED %*\r\nexit /b 0\r\n").unwrap();let shim = dir.join("pnpm.cmd");- std::fs::write(&shim, build_pnpm_cmd_shim(&app_dir)).unwrap();+ std::fs::write(&shim, build_pnpm_cmd_shim(&shim_paths_for(&app_dir))).unwrap();let system_root = std::env::var_os("SystemRoot").unwrap_or_else(|| "C:\\Windows".into());let system32 = PathBuf::from(&system_root).join("System32");let output = std::process::Command::new(system32.join("cmd.exe"))@@ -597,12 +647,16 @@ mod tests {#[test]fn pnpm_ps1_shim_contains_user_precedence() {- let content = build_pnpm_ps1_shim(&sample_app_dir());+ let paths = sample_shim_paths();+ let content = build_pnpm_ps1_shim(&paths);assert!(content.contains("Get-Command pnpm -All"));assert!(content.contains("$PSScriptRoot"));assert!(content.contains("$userPnpm.Source"));assert!(content.contains("@args"));- assert!(content.contains("Join-Path $appDir 'runtime\\node.exe'"));+ assert!(content.contains(&format!(+ "$nodeBin = '{}'",+ paths.node_bin.to_string_lossy()+ )));assert!(content.contains("$env:DSH_PREFER_BUNDLED_PNPM"));assert!(content.contains("$env:DSH_PNPM"));let bundled_at = content.find("$useBundled =").unwrap();@@ -618,7 +672,11 @@ mod tests {let selected = dir.join("selected pnpm.cmd");std::fs::write(&selected, "@echo off\r\necho SELECTED:%*\r\nexit /b 37\r\n").unwrap();let shim = dir.join("pnpm.ps1");- std::fs::write(&shim, build_pnpm_ps1_shim(&dir.join("app"))).unwrap();+ std::fs::write(+ &shim,+ build_pnpm_ps1_shim(&shim_paths_for(&dir.join("app"))),+ )+ .unwrap();let system_root = std::env::var_os("SystemRoot").unwrap_or_else(|| "C:\\Windows".into());let powershell =PathBuf::from(&system_root).join("System32/WindowsPowerShell/v1.0/powershell.exe");@@ -652,7 +710,7 @@ mod tests {std::fs::write(&selected, "@echo off\r\necho SELECTED\r\n").unwrap();std::fs::write(&node, "@echo off\r\necho BUNDLED %*\r\nexit /b 0\r\n").unwrap();let shim = dir.join("pnpm.ps1");- std::fs::write(&shim, build_pnpm_ps1_shim(&app_dir)).unwrap();+ std::fs::write(&shim, build_pnpm_ps1_shim(&shim_paths_for(&app_dir))).unwrap();let system_root = std::env::var_os("SystemRoot").unwrap_or_else(|| "C:\\Windows".into());let powershell =PathBuf::from(&system_root).join("System32/WindowsPowerShell/v1.0/powershell.exe");@@ -678,12 +736,13 @@ mod tests {#[test]fn pnpm_sh_shim_contains_user_precedence() {- let content = build_pnpm_sh_shim(&sample_app_dir());+ let paths = sample_shim_paths();+ let content = build_pnpm_sh_shim(&paths);assert!(content.starts_with("#!/bin/sh"));assert!(content.contains(r#"exec "$dir/pnpm" "$@""#));assert!(content.contains("SELF_DIR"));assert!(content.contains(r#"exec "$NODE" "$PNPM_BIN" "$@""#));- assert!(content.contains(r#"$APP_DIR/runtime/bin/node"#));+ assert!(content.contains(&format!("NODE_BIN='{}'", paths.node_bin.to_string_lossy())));assert!(content.contains("DSH_PREFER_BUNDLED_PNPM"));assert!(content.contains(r#"exec "$DSH_PNPM" "$@""#));let bundled_at = content.find("USE_BUNDLED=").unwrap();@@ -708,7 +767,7 @@ mod tests {permissions.set_mode(0o700);std::fs::set_permissions(&selected, permissions).unwrap();let shim = dir.join("pnpm");- std::fs::write(&shim, build_pnpm_sh_shim(&dir.join("app"))).unwrap();+ std::fs::write(&shim, build_pnpm_sh_shim(&shim_paths_for(&dir.join("app")))).unwrap();let mut permissions = std::fs::metadata(&shim).unwrap().permissions();permissions.set_mode(0o700);std::fs::set_permissions(&shim, permissions).unwrap();@@ -748,7 +807,7 @@ mod tests {std::fs::set_permissions(path, permissions).unwrap();}let shim = dir.join("pnpm");- std::fs::write(&shim, build_pnpm_sh_shim(&app_dir)).unwrap();+ std::fs::write(&shim, build_pnpm_sh_shim(&shim_paths_for(&app_dir))).unwrap();let mut permissions = std::fs::metadata(&shim).unwrap().permissions();permissions.set_mode(0o700);std::fs::set_permissions(&shim, permissions).unwrap();@@ -773,9 +832,9 @@ mod tests {fn pnpm_shims_guard_against_reentrant_forwarding() {let app_dir = sample_app_dir();for (name, content) in [- ("pnpm.sh", build_pnpm_sh_shim(&app_dir)),- ("pnpm.cmd", build_pnpm_cmd_shim(&app_dir)),- ("pnpm.ps1", build_pnpm_ps1_shim(&app_dir)),+ ("pnpm.sh", build_pnpm_sh_shim(&shim_paths_for(&app_dir))),+ ("pnpm.cmd", build_pnpm_cmd_shim(&shim_paths_for(&app_dir))),+ ("pnpm.ps1", build_pnpm_ps1_shim(&shim_paths_for(&app_dir))),] {assert!(content.contains("DSH_PNPM_SHIM_GUARD"),@@ -783,7 +842,7 @@ mod tests {);}// cmd 在入口一次判断 + 一次置位;转发块保持 issue #130 修复时的原样。- let cmd = build_pnpm_cmd_shim(&app_dir);+ let cmd = build_pnpm_cmd_shim(&shim_paths_for(&app_dir));assert_eq!(cmd.matches("DSH_PNPM_SHIM_GUARD").count(), 2);assert_eq!(cmd.matches("set \"DSH_PNPM_SHIM_GUARD=1\"").count(), 1);}@@ -793,7 +852,7 @@ mod tests {/// 时提前展开,失败码被吞成 0/1。这里锁死「call 之后紧跟 exit /b %ERRORLEVEL%」。#[test]fn cmd_shim_exit_code_stays_adjacent_to_call() {- let content = build_pnpm_cmd_shim(&sample_app_dir());+ let content = build_pnpm_cmd_shim(&sample_shim_paths());for call in [r#"call "%DSH_PNPM%" %*"#, r#"call "%USER_PNPM%" %*"#] {let expected = format!("{call}\r\nexit /b %ERRORLEVEL%\r\n");assert!(@@ -828,7 +887,7 @@ mod tests {std::fs::write(&node, "#!/bin/sh\necho BUNDLED \"$@\"\n").unwrap();// 本 shim 落在 PATH 中,等价于桌面端把自身 shim 目录前置到子进程 PATH。let shim = bin_dir.join("pnpm");- std::fs::write(&shim, build_pnpm_sh_shim(&app_dir)).unwrap();+ std::fs::write(&shim, build_pnpm_sh_shim(&shim_paths_for(&app_dir))).unwrap();// 模拟 mise shim:自身没有实现,只把调用交回 PATH 上的 pnpm。let forwarder = loop_dir.join("pnpm");std::fs::write(&forwarder, "#!/bin/sh\nexec pnpm \"$@\"\n").unwrap();@@ -890,7 +949,7 @@ mod tests {/// 本地 node / 捆绑运行时解析之前被采用——shim 与应用预检保持一致。#[test]fn cmd_shim_prefers_dsh_node_before_local_node() {- let content = build_cmd_shim(&sample_app_dir(), &sample_dsh_home());+ let content = build_cmd_shim(&sample_shim_paths(), &sample_dsh_home());let dsh_node_at = content.find("DSH_NODE").unwrap();let where_node_at = content.find("where node").unwrap();// `:node_dsh` 标签行(独占一行)位于 `:node_ok` 之后、`:use_bundled`@@ -915,7 +974,7 @@ mod tests {#[test]fn ps1_shim_prefers_dsh_node_before_local_node() {- let content = build_ps1_shim(&sample_app_dir(), &sample_dsh_home());+ let content = build_ps1_shim(&sample_shim_paths(), &sample_dsh_home());let dsh_node_at = content.find("$env:DSH_NODE").unwrap();let local_at = content.find("Get-Command node").unwrap();assert!(@@ -931,7 +990,7 @@ mod tests {fn sh_shim_prefers_dsh_node_before_local_node() {#[cfg(not(windows))]{- let content = build_sh_shim(&sample_app_dir(), &sample_dsh_home());+ let content = build_sh_shim(&sample_shim_paths(), &sample_dsh_home());let dsh_node_at = content.find("$DSH_NODE").unwrap();let local_at = content.find("command -v node").unwrap();assert!(@@ -944,8 +1003,8 @@ mod tests {/// 三种 shim 的版本门槛必须与应用预检及当前 DSH engines 保持一致。#[test]fn generated_shims_match_current_dsh_node_engine() {- let cmd = build_cmd_shim(&sample_app_dir(), &sample_dsh_home());- let ps1 = build_ps1_shim(&sample_app_dir(), &sample_dsh_home());+ let cmd = build_cmd_shim(&sample_shim_paths(), &sample_dsh_home());+ let ps1 = build_ps1_shim(&sample_shim_paths(), &sample_dsh_home());assert!(cmd.contains(r#"findstr /r /x "v[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*""#));assert!(cmd.contains("EQU 22 if defined NODE_MINOR if %NODE_MINOR% GEQ 19"));@@ -968,7 +1027,7 @@ mod tests {std::fs::create_dir_all(pnpm_bin.parent().unwrap()).unwrap();std::fs::write(&pnpm_bin, "fixture").unwrap();let shim = dir.join("pnpm.cmd");- std::fs::write(&shim, build_pnpm_cmd_shim(&app_dir)).unwrap();+ std::fs::write(&shim, build_pnpm_cmd_shim(&shim_paths_for(&app_dir))).unwrap();let node_dir = dir.join("local-node");std::fs::create_dir_all(&node_dir).unwrap();let node = node_dir.join("node.cmd");@@ -1017,7 +1076,7 @@ mod tests {#[test]fn ps1_shim_escapes_quotes() {let dir = PathBuf::from(r"C:\Users\o'brien\AppData\Roaming\dsh-tauri");- let content = build_ps1_shim(&dir, &sample_dsh_home());+ let content = build_ps1_shim(&shim_paths_for(&dir), &sample_dsh_home());assert!(content.contains(r"o''brien"));// dsh_home 同样走 ps1 转义assert!(content.contains(r"C:\Users\test\.dsh"));@@ -1025,7 +1084,7 @@ mod tests {#[test]fn cmd_shim_prefers_user_dsh() {- let content = build_cmd_shim(&sample_app_dir(), &sample_dsh_home());+ let content = build_cmd_shim(&sample_shim_paths(), &sample_dsh_home());assert!(content.contains("USER_DSH"));assert!(content.contains(r#"call "%USER_DSH%" %*"#));assert!(content.contains("SELF_PREFIX"));@@ -1037,7 +1096,7 @@ mod tests {#[test]fn ps1_shim_prefers_user_dsh() {- let content = build_ps1_shim(&sample_app_dir(), &sample_dsh_home());+ let content = build_ps1_shim(&sample_shim_paths(), &sample_dsh_home());assert!(content.contains("Get-Command dsh -All"));assert!(content.contains("$userDsh.Source"));assert!(content.contains("$PSScriptRoot"));@@ -1051,7 +1110,7 @@ mod tests {fn sh_shim_prefers_user_dsh() {#[cfg(not(windows))]{- let content = build_sh_shim(&sample_app_dir(), &sample_dsh_home());+ let content = build_sh_shim(&sample_shim_paths(), &sample_dsh_home());assert!(content.contains(r#"exec "$dir/dsh" "$@""#));assert!(content.contains("SELF_DIR"));// 用户 dsh 优先 > 注入 DSH_HOMEdiff --git a/src-tauri/src/service/cli/shim/mod.rs b/src-tauri/src/service/cli/shim/mod.rsindex 176e2027..f089a5aa 100644--- a/src-tauri/src/service/cli/shim/mod.rs+++ b/src-tauri/src/service/cli/shim/mod.rs@@ -57,6 +57,40 @@ pub fn escape_path_sh(path: &Path) -> String {mod test_util {use std::path::PathBuf;+ /// 与生产同源的默认布局样例(AppData 托管根 + 清单入口相对路径),+ /// 供 shim 构建/落盘测试断言烘焙结果。+ pub(super) fn sample_shim_paths() -> super::build::ShimPaths {+ shim_paths_for(&sample_app_dir())+ }++ /// 任意根目录 + 清单默认布局的等价 `ShimPaths`:生产侧入口路径来自依赖映射表+ /// 与清单 `entry`,按临时目录构造的测试用同一布局换算。+ pub(super) fn shim_paths_for(app_dir: &std::path::Path) -> super::build::ShimPaths {+ let app_dir = app_dir.to_path_buf();+ let node_root = app_dir.join("runtime");+ super::build::ShimPaths {+ node_bin: if cfg!(windows) {+ node_root.join("node.exe")+ } else {+ node_root.join("bin").join("node")+ },+ dsh_bin: app_dir+ .join("dependencies")+ .join("dsh")+ .join("node_modules")+ .join("@deepseek-ai")+ .join("dsh")+ .join("lib")+ .join("bin.js"),+ pnpm_bin: app_dir+ .join("dependencies")+ .join("pnpm")+ .join("bin")+ .join("pnpm.cjs"),+ bundled_git_dir: Some(app_dir.join("dependencies").join("git").join("cmd")),+ }+ }+pub(super) fn sample_app_dir() -> PathBuf {if cfg!(windows) {PathBuf::from(r"C:\Users\test\AppData\Roaming\dsh-tauri")diff --git a/src-tauri/src/service/cli/shim/templates.rs b/src-tauri/src/service/cli/shim/templates.rsindex cd43cebf..d7c00365 100644--- a/src-tauri/src/service/cli/shim/templates.rs+++ b/src-tauri/src/service/cli/shim/templates.rs@@ -1,7 +1,10 @@//! shim 共享脚本片段(纯文本常量,作为 format! 的参数嵌入各构建函数)。//!//! shim 文本必须全英文:cmd/ps1 按系统代码页解析,中文注释会乱码成命令执行。-//! 变量约定:cmd 用 `%APP_DIR%`,ps1 用 `$appDir`,sh 用 `$APP_DIR`;+//! 变量约定:cmd 用 `%NODE_BIN%` / `%NODE_DIR%` / `%GIT_DIR%` / `%DSH_BIN%` /+//! `%PNPM_BIN%`,ps1 用 `$nodeBin` / `$nodeDir` / `$gitDir` / `$dshBin` /+//! `$pnpmBin`,sh 用同名大写下划线形式。路径全部由桌面端在生成 shim 时按+//! 依赖映射表解析后写死(不再假设 `<AppData>/dependencies/<name>` 布局);//! 这些常量里的 `{`/`}` 是字面量(由 format! 的参数占位符区分)。// ---------------------------------------------------------------------------@@ -49,9 +52,9 @@ set "NODE=%DSH_NODE%"goto :launch:use_bundled-if not exist "%APP_DIR%\runtime\node.exe" goto :no_node-set "NODE=%APP_DIR%\runtime\node.exe"-set "PATH=%APP_DIR%\runtime;%PATH%"+if not exist "%NODE_BIN%" goto :no_node+set "NODE=%NODE_BIN%"+set "PATH=%NODE_DIR%;%PATH%""#;pub(super) const PS1_NODE_RESOLVE: &str = r#"@@ -82,10 +85,9 @@ if (-not $node) {}}if (-not $node) {- $bundled = Join-Path $appDir 'runtime\node.exe'- if (Test-Path -LiteralPath $bundled) {- $node = $bundled- $env:PATH = (Split-Path -Parent $bundled) + ';' + $env:PATH+ if (Test-Path -LiteralPath $nodeBin) {+ $node = $nodeBin+ $env:PATH = $nodeDir + ';' + $env:PATH}}if (-not $node) {@@ -114,9 +116,9 @@ if [ -z "$NODE" ] && command -v node >/dev/null 2>&1; thenfifiif [ -z "$NODE" ]; then- if [ -x "$APP_DIR/runtime/bin/node" ]; then- NODE="$APP_DIR/runtime/bin/node"- export PATH="$APP_DIR/runtime/bin:$PATH"+ if [ -x "$NODE_BIN" ]; then+ NODE="$NODE_BIN"+ export PATH="$NODE_DIR:$PATH"fifiif [ -z "$NODE" ]; thendiff --git a/src-tauri/src/service/cli/shim/write.rs b/src-tauri/src/service/cli/shim/write.rsindex d698120f..bd99149a 100644--- a/src-tauri/src/service/cli/shim/write.rs+++ b/src-tauri/src/service/cli/shim/write.rs@@ -2,7 +2,7 @@use crate::config;use std::fs;-use std::path::Path;+use std::path::{Path, PathBuf};use tauri::AppHandle;#[cfg(not(windows))]@@ -11,6 +11,7 @@ use super::build::build_sh_shim;#[allow(unused_imports)] // 构建函数在 debug 构建/异平台下由 cfg 裁剪,测试仍引用use super::build::{build_cmd_shim, build_pnpm_cmd_shim, build_pnpm_ps1_shim, build_pnpm_sh_shim, build_ps1_shim,+ ShimPaths,};#[cfg(all(windows, not(debug_assertions)))]use super::SHIM_PS1_NAME;@@ -106,6 +107,30 @@ pub fn user_dsh_preserved(bin_dir: &Path) -> bool {path.is_file() && is_foreign_file(&path)}+/// shim 生成时烘焙的依赖路径:按依赖映射表解析,可能指向 AppData 之外的任意+/// 位置(如安装目录的 `resources/*` 捆绑副本)。+pub fn shim_paths(app_handle: &AppHandle) -> ShimPaths {+ ShimPaths {+ node_bin: config::dependencies::binary_path(app_handle, config::dependencies::DEP_NODE),+ dsh_bin: config::get_dsh_binary_path(app_handle),+ pnpm_bin: config::get_pnpm_binary_path(app_handle),+ bundled_git_dir: bundled_git_dir(app_handle),+ }+}++/// 捆绑 MinGit 的 `cmd` 目录(系统 Git 缺 HTTPS helper 时由 shim 注入 PATH)。+#[cfg(windows)]+fn bundled_git_dir(app_handle: &AppHandle) -> Option<PathBuf> {+ config::get_mingit_binary_path(app_handle)+ .parent()+ .map(Path::to_path_buf)+}++#[cfg(not(windows))]+fn bundled_git_dir(_app_handle: &AppHandle) -> Option<PathBuf> {+ None+}+/// 将 shim 文件写入 bin 目录;目标已存在但非本应用生成的同名文件时跳过(保留)。/// 目标为悬空符号链接时先移除链接再写入(链接目标已失效,保留只会让写入/// 报 ENOENT)。@@ -113,7 +138,7 @@ pub fn user_dsh_preserved(bin_dir: &Path) -> bool {/// 覆盖式仅针对本应用生成的 shim(自愈时内容与当前安装一致);用户手动放置的/// 同名 `dsh`/`pnpm` 一律保留不动,避免覆盖用户自己的安装与配置。pub fn write_shims(app_handle: &AppHandle, bin_dir: &Path) -> Result<(), String> {- let app_dir = config::get_base_dir(app_handle);+ let paths = shim_paths(app_handle);fs::create_dir_all(bin_dir).map_err(|e| format!("SHIM_MKDIR_FAILED: create bin dir failed: {e}"))?;@@ -134,12 +159,12 @@ pub fn write_shims(app_handle: &AppHandle, bin_dir: &Path) -> Result<(), String>let dsh_home = config::get_dsh_data_path(app_handle);#[cfg(windows)]{- write_if_ours!(SHIM_CMD_NAME, build_cmd_shim(&app_dir, &dsh_home));- write_if_ours!(SHIM_PS1_NAME, build_ps1_shim(&app_dir, &dsh_home));+ write_if_ours!(SHIM_CMD_NAME, build_cmd_shim(&paths, &dsh_home));+ write_if_ours!(SHIM_PS1_NAME, build_ps1_shim(&paths, &dsh_home));}#[cfg(not(windows))]{- write_if_ours!(SHIM_SH_NAME, build_sh_shim(&app_dir, &dsh_home));+ write_if_ours!(SHIM_SH_NAME, build_sh_shim(&paths, &dsh_home));}}#[cfg(debug_assertions)]@@ -150,12 +175,12 @@ pub fn write_shims(app_handle: &AppHandle, bin_dir: &Path) -> Result<(), String>// pnpm 依赖它,写它不污染任何共享数据。#[cfg(windows)]{- write_if_ours!(PNPM_SHIM_CMD_NAME, build_pnpm_cmd_shim(&app_dir));- write_if_ours!(PNPM_SHIM_PS1_NAME, build_pnpm_ps1_shim(&app_dir));+ write_if_ours!(PNPM_SHIM_CMD_NAME, build_pnpm_cmd_shim(&paths));+ write_if_ours!(PNPM_SHIM_PS1_NAME, build_pnpm_ps1_shim(&paths));}#[cfg(not(windows))]{- write_if_ours!(PNPM_SHIM_SH_NAME, build_pnpm_sh_shim(&app_dir));+ write_if_ours!(PNPM_SHIM_SH_NAME, build_pnpm_sh_shim(&paths));// 仅对本应用生成/覆盖过的 shim 设置可执行位;保留的用户文件不动let chmod_names: &[&str] = if cfg!(debug_assertions) {&[PNPM_SHIM_SH_NAME]@@ -176,7 +201,7 @@ pub fn write_shims(app_handle: &AppHandle, bin_dir: &Path) -> Result<(), String>#[cfg(test)]mod tests {- use super::super::test_util::{sample_app_dir, sample_dsh_home};+ use super::super::test_util::{sample_dsh_home, sample_shim_paths, shim_paths_for};use super::*;#[test]@@ -195,9 +220,9 @@ mod tests {// 本应用生成的 shim -> 不是 foreign,可覆盖#[cfg(not(windows))]- let generated = build_sh_shim(&sample_app_dir(), &sample_dsh_home());+ let generated = build_sh_shim(&sample_shim_paths(), &sample_dsh_home());#[cfg(windows)]- let generated = build_cmd_shim(&sample_app_dir(), &sample_dsh_home());+ let generated = build_cmd_shim(&sample_shim_paths(), &sample_dsh_home());std::fs::write(&user_dsh, generated).unwrap();assert!(!is_foreign_file(&user_dsh),@@ -335,7 +360,7 @@ mod tests {fn write_shim_file_migrates_legacy_lf_only_cmd_shim() {let dir = temp_dir("legacy-lf-cmd");let target = dir.join("pnpm.cmd");- let current = build_pnpm_cmd_shim(&dir.join("app"));+ let current = build_pnpm_cmd_shim(&shim_paths_for(&dir.join("app")));assert!(current.contains("\r\n"));std::fs::write(&target, current.replace("\r\n", "\n")).unwrap();assert!(diff --git a/src-tauri/src/service/core/source.rs b/src-tauri/src/service/core/source.rsindex aaba0ff8..b66798b2 100644--- a/src-tauri/src/service/core/source.rs+++ b/src-tauri/src/service/core/source.rs@@ -75,15 +75,8 @@ pub struct HarnessCore {/// 基线告警只发一次:`active_source` 在启动、核心列表与插件操作中反复调用。static UNSUPPORTED_LOCAL_WARNED: OnceLock<()> = OnceLock::new();-/// 最低支持的核心版本。-///-/// 低于该版本的核心不再适配:`@deepseek-ai/dsh-client-store` 首版早于它、而内置插件-/// 依赖的平台种子词自 0.1.5 起才存在,核心低于该版本时 `resources/node_modules`-/// 的内置插件必然加载失败并把应用卡在启动阶段(issue #596)。版本号无法解析时按-/// 「达标」处理,宁可放行也不误判。-const MIN_SUPPORTED_CORE_VERSION: &str = "0.1.5-rc.1";--/// 版本是否达到最低支持基线;任一版本无法解析时按「达标」处理,宁可放行也不误判。+/// 版本是否达到最低支持基线(来自 `resources/manifest.jsonc` 的 `engines.dsh.minimum`);+/// 基线缺失或任一版本无法解析时按「达标」处理。fn meets_baseline(version: &str, baseline: &str) -> bool {match (semver::Version::parse(version),@@ -94,19 +87,25 @@ fn meets_baseline(version: &str, baseline: &str) -> bool {}}-/// 本地核心能否承载随包内置插件(见 [`MIN_SUPPORTED_CORE_VERSION`])。-pub(super) fn core_supports_bundled_plugins(version: &str) -> bool {- meets_baseline(version, MIN_SUPPORTED_CORE_VERSION)+/// 本地核心能否承载随包内置插件(基线取自清单 `engines.dsh.minimum`)。+///+/// 最低支持版本由随包清单声明;清单缺失(基线与版本都读不到)时不阻断,宁可放行+/// 也不把可用的本地核心判死——清单损坏的诊断由 `manifest` 模块记录。+pub(super) fn core_supports_bundled_plugins(version: &str, baseline: Option<&str>) -> bool {+ match baseline {+ Some(baseline) => meets_baseline(version, baseline),+ None => true,+ }}-fn warn_unsupported_local_core(version: &str) {+fn warn_unsupported_local_core(version: &str, baseline: Option<&str>) {if UNSUPPORTED_LOCAL_WARNED.set(()).is_err() {return;}log::warn!("CORE_LOCAL_UNSUPPORTED: local dsh {} is below the minimum supported core {}; using the bundled core instead (issue #596)",version,- MIN_SUPPORTED_CORE_VERSION,+ baseline.unwrap_or("<unset>"),);}@@ -118,15 +117,17 @@ fn warn_unsupported_local_core(version: &str) {pub fn active_source(app_handle: &AppHandle) -> CoreSource {let setting = config::get_store_dat_setting(app_handle);let local = local_core(app_handle);+ let baseline = config::manifest::minimum_dsh_version(app_handle);let local_usable = local.as_ref()- .is_some_and(|core| core_supports_bundled_plugins(&core.version));+ .is_some_and(|core| core_supports_bundled_plugins(&core.version, baseline.as_deref()));if local.is_some() && !local_usable {warn_unsupported_local_core(local.as_ref().map(|core| core.version.as_str()).unwrap_or_default(),+ baseline.as_deref(),);}match setting.active_core.as_deref().and_then(CoreSource::parse) {@@ -183,26 +184,38 @@ mod tests {#[test]fn baseline_gate_accepts_equal_or_newer_versions() {- assert!(meets_baseline("0.1.5-rc.1", MIN_SUPPORTED_CORE_VERSION));- assert!(meets_baseline("0.1.5-rc.2", MIN_SUPPORTED_CORE_VERSION));- assert!(meets_baseline("0.1.6-alpha.2", MIN_SUPPORTED_CORE_VERSION));+ let baseline = "0.1.5-rc.1";+ assert!(meets_baseline("0.1.5-rc.1", baseline));+ assert!(meets_baseline("0.1.5-rc.2", baseline));+ assert!(meets_baseline("0.1.6-alpha.2", baseline));}/// issue #596:更早的核心(0.1.2-rc.1 / 0.1.0-rc.7)早于内置插件依赖的平台/// 种子词,内置插件必然加载失败,不再支持。#[test]fn baseline_gate_rejects_older_versions() {- assert!(!meets_baseline("0.1.0-rc.7", MIN_SUPPORTED_CORE_VERSION));- assert!(!meets_baseline("0.1.2-rc.1", MIN_SUPPORTED_CORE_VERSION));- assert!(!meets_baseline("0.1.5-alpha.2", MIN_SUPPORTED_CORE_VERSION));+ let baseline = "0.1.5-rc.1";+ assert!(!meets_baseline("0.1.0-rc.7", baseline));+ assert!(!meets_baseline("0.1.2-rc.1", baseline));+ assert!(!meets_baseline("0.1.5-alpha.2", baseline));}/// 版本不可解析(旧安装记录/异常清单)时不阻断:漏放行只是回到修复前的行为,/// 误拦截会把可用的本地核心判死。#[test]fn baseline_gate_passes_unparsable_versions() {- assert!(meets_baseline("", MIN_SUPPORTED_CORE_VERSION));- assert!(meets_baseline("not-a-version", MIN_SUPPORTED_CORE_VERSION));+ assert!(meets_baseline("", "0.1.5-rc.1"));+ assert!(meets_baseline("not-a-version", "0.1.5-rc.1"));assert!(meets_baseline("0.1.0-rc.7", ""));}++ /// 清单缺失(读不到最低支持基线)时同样放行,避免资源损坏阻断本地核心。+ #[test]+ fn missing_baseline_keeps_local_core_usable() {+ assert!(core_supports_bundled_plugins("0.1.0-rc.7", None));+ assert!(!core_supports_bundled_plugins(+ "0.1.0-rc.7",+ Some("0.1.5-rc.1")+ ));+ }}diff --git a/src-tauri/src/service/core/version.rs b/src-tauri/src/service/core/version.rsindex c13a1f64..91174c7c 100644--- a/src-tauri/src/service/core/version.rs+++ b/src-tauri/src/service/core/version.rs@@ -14,8 +14,12 @@ use super::local::{find_user_dsh_bin, local_core};use super::source::{active_source, core_supports_bundled_plugins, CoreSource, HarnessCore};/// `dependencies` 目录(激活 `dsh` 与历史 `dsh-<tag>` 槽位的共同父级)。+///+/// 槽位是桌面端自己下载的产物,恒落在**托管根**之下:即使映射把激活核心指向+/// `resources/dsh` 或其它任意位置,历史版本仍收在 AppData 里,不会污染安装目录。fn dependencies_dir(app_handle: &AppHandle) -> PathBuf {- config::get_dsh_install_path(app_handle)+ let managed = config::dependencies::managed_root(app_handle, config::dependencies::DEP_DSH);+ managed.parent().map(Path::to_path_buf).unwrap_or_else(|| PathBuf::from("."))@@ -347,7 +351,8 @@ pub async fn set_active(app_handle: &AppHandle, id: &str) -> Result<HarnessCore,};// 低于最低支持版本的本地核心无法加载随包插件(issue #596):显式切换同样// 拒绝并给出可操作提示,而不是让用户切过去再撞一次启动失败。- if !core_supports_bundled_plugins(&core.version) {+ let baseline = config::manifest::minimum_dsh_version(app_handle);+ if !core_supports_bundled_plugins(&core.version, baseline.as_deref()) {return Err(format!("CORE_LOCAL_UNSUPPORTED: local dsh {} is below the minimum supported core; update it (`npm install -g @deepseek-ai/dsh@latest`) or keep a bundled version",core.version,@@ -357,6 +362,8 @@ pub async fn set_active(app_handle: &AppHandle, id: &str) -> Result<HarnessCore,let mut setting = config::get_store_dat_setting(app_handle);setting.active_core = Some(CoreSource::Local.as_str().to_string());config::set_store_dat_setting(app_handle, setting);+ // 映射表记录「该依赖由系统环境满足」(`null`),与清单的 `Path | null` 语义一致。+ config::dependencies::record(app_handle, config::dependencies::DEP_DSH, None);} else if id == "app" {if !config::get_dsh_binary_path(app_handle).exists() {return Err("CORE_APP_NOT_FOUND: bundled core is not installed".to_string());@@ -365,6 +372,8 @@ pub async fn set_active(app_handle: &AppHandle, id: &str) -> Result<HarnessCore,let mut setting = config::get_store_dat_setting(app_handle);setting.active_core = Some(CoreSource::App.as_str().to_string());config::set_store_dat_setting(app_handle, setting);+ // 切回预打包核心:托管根重新成为该依赖的安装根。+ record_managed_core(app_handle);} else if let Some(tag) = id.strip_prefix("app-") {switch_app_version(app_handle, tag).await?;} else {@@ -394,7 +403,8 @@ async fn switch_app_version(app_handle: &AppHandle, tag: &str) -> Result<(), Str// 重叠,也避免 launch 在状态检查后插入并从旧的 dependencies/dsh 加载 DLL。let _transition_guard = workflow::acquire_core_transition().await?;let deps = dependencies_dir(app_handle);- let active_dir = config::get_dsh_install_path(app_handle);+ // 槽位互换只在托管根内进行(映射可能把激活核心指向安装目录的捆绑副本)。+ let active_dir = config::dependencies::managed_root(app_handle, config::dependencies::DEP_DSH);fs_guard::validate_id(tag)?;let cur_tag = config::get_dsh_pkg_tag(app_handle);@@ -515,9 +525,23 @@ async fn switch_app_version(app_handle: &AppHandle, tag: &str) -> Result<(), Strsetting.dsh_pkg_commit = Some(c);}config::set_store_dat_setting(app_handle, setting);+ // 切换后的激活核心回到托管根;映射表随之写回,界面与解析链路保持一致。+ record_managed_core(app_handle);Ok(())}+/// 把 `dsh` 映射写回托管根(预打包核心的激活目录)。+fn record_managed_core(app_handle: &AppHandle) {+ config::dependencies::record(+ app_handle,+ config::dependencies::DEP_DSH,+ Some(config::dependencies::managed_root(+ app_handle,+ config::dependencies::DEP_DSH,+ )),+ );+}+/// 下载指定 tag 的预打包核心到历史槽位 `dependencies/<tag>`(不激活,切换由/// `set_active` 完成)。幂等:已下载时直接返回该版本行。pub async fn download_version(app_handle: &AppHandle, tag: &str) -> Result<HarnessCore, String> {diff --git a/src-tauri/src/service/download/installable.rs b/src-tauri/src/service/download/installable.rsindex d90401e1..31519d52 100644--- a/src-tauri/src/service/download/installable.rs+++ b/src-tauri/src/service/download/installable.rs@@ -15,6 +15,18 @@ pub enum InstallKind {Git,}+impl InstallKind {+ /// 对应的依赖映射键(见 `config::dependencies`)+ pub fn dependency_key(self) -> &'static str {+ match self {+ InstallKind::Node => config::dependencies::DEP_NODE,+ InstallKind::Dsh => config::dependencies::DEP_DSH,+ InstallKind::Pnpm => config::dependencies::DEP_PNPM,+ InstallKind::Git => config::dependencies::DEP_GIT,+ }+ }+}+#[async_trait]pub trait Installable: Send + Sync {fn kind(&self) -> InstallKind;@@ -22,6 +34,28 @@ pub trait Installable: Send + Sync {fn check_installed(&self, app: &AppHandle) -> bool;fn get_download_url(&self) -> Result<String, String>;fn get_install_path(&self, app: &AppHandle) -> PathBuf;+ /// 把该依赖当前解析出的安装根写回映射表(系统环境满足 → `null`)。+ ///+ /// 与 [`Installable::check_installed`] 同一套判定:检测到系统合规版本就不托管,+ /// 只有真正落到托管根的依赖才记录路径。+ fn record_mapping(&self, app: &AppHandle);+}++/// 依赖任务清单(唯一构造点:安装流程与映射回写共用同一组任务)。+pub fn tasks() -> Vec<Box<dyn Installable>> {+ #[cfg_attr(not(windows), allow(unused_mut))]+ let mut tasks: Vec<Box<dyn Installable>> =+ vec![Box::new(Nodejs), Box::new(Dsh), Box::new(Pnpm)];+ #[cfg(windows)]+ tasks.push(Box::new(Git));+ tasks+}++/// 回写全部依赖的映射(幂等;内容未变化时不落盘)。+pub fn record_mappings(app: &AppHandle) {+ for task in tasks() {+ task.record_mapping(app);+ }}// --- Node.js 实现 ---@@ -46,7 +80,8 @@ impl Installable for Nodejs {// 此时不能再以"本机有版本兼容的 node"为由跳过捆绑运行时,否则服务进程仍会// 用那个 ABI 不匹配的运行时启动。if config::prefer_bundled_node_runtime() {- return config::bundled_node_binary(app).is_some() && config::is_runtime_compatible(app);+ return config::bundled_node_binary(app).is_some()+ && config::is_runtime_compatible(app);}if let Some(local_node) = config::get_local_node_path() {log::info!(@@ -57,6 +92,17 @@ impl Installable for Nodejs {}config::get_node_binary_path(app).exists() && config::is_runtime_compatible(app)}+ fn record_mapping(&self, app: &AppHandle) {+ let managed = config::get_node_install_path(app);+ // ABI 探测要求捆绑运行时时不能把系统 node 记为可用(与实际拉起的进程一致)。+ let system =+ !config::prefer_bundled_node_runtime() && config::get_local_node_path().is_some();+ config::dependencies::record(+ app,+ InstallKind::Node.dependency_key(),+ (!system).then_some(managed),+ );+ }}// --- DeepSeek Harness 实现 ---@@ -79,6 +125,15 @@ impl Installable for Dsh {fn check_installed(&self, app: &AppHandle) -> bool {config::get_dsh_binary_path(app).exists()}+ fn record_mapping(&self, app: &AppHandle) {+ let managed = config::dependencies::managed_root(app, config::dependencies::DEP_DSH);+ if config::get_dsh_binary_path(app).is_file() {+ config::dependencies::record(app, InstallKind::Dsh.dependency_key(), Some(managed));+ } else if crate::service::core::active_version(app).is_some() {+ // 只有系统(本地)核心可用:该依赖由系统环境满足。+ config::dependencies::record(app, InstallKind::Dsh.dependency_key(), None);+ }+ }}// --- pnpm 实现(dsh 的 plugin 命令依赖) ---@@ -106,6 +161,17 @@ impl Installable for Pnpm {}config::get_pnpm_binary_path(app).exists()}+ fn record_mapping(&self, app: &AppHandle) {+ let managed = config::get_pnpm_install_path(app);+ let bundled_present = config::get_pnpm_binary_path(app).exists();+ // 捆绑版优先(`dsh plugin` 需要可校验的 pnpm):只有捆绑版缺失、且系统确有+ // 用户 pnpm 时才把该依赖记为「系统环境满足」;两者都缺失时不写,等下载后记录。+ if bundled_present {+ config::dependencies::record(app, InstallKind::Pnpm.dependency_key(), Some(managed));+ } else if crate::service::cli::find_user_pnpm(app).is_some() {+ config::dependencies::record(app, InstallKind::Pnpm.dependency_key(), None);+ }+ }}// --- Windows Git 实现(插件的 git 托管依赖需要) ---@@ -140,4 +206,14 @@ impl Installable for Git {}config::git_runtime_ready(app)}++ fn record_mapping(&self, app: &AppHandle) {+ let system = config::find_system_git_binary().is_some();+ let managed = config::get_mingit_install_path(app);+ config::dependencies::record(+ app,+ InstallKind::Git.dependency_key(),+ (!system).then_some(managed),+ );+ }}diff --git a/src-tauri/src/service/download/mod.rs b/src-tauri/src/service/download/mod.rsindex 1e88a270..9f5696c4 100644--- a/src-tauri/src/service/download/mod.rs+++ b/src-tauri/src/service/download/mod.rs@@ -16,9 +16,8 @@ pub use github::{};// 供核心面板切换版本时使用(跨模块内部接口,不进公共 API)pub(crate) use core::{remove_dir_with_retry, rename_with_retry};-#[cfg(windows)]-pub use installable::Git;-pub use installable::{Dsh, InstallKind, Installable, Nodejs, Pnpm};+// 依赖任务清单与映射回写:安装流程与启动检测共用同一组任务定义。+pub use installable::{record_mappings, tasks, 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/migrate.rs b/src-tauri/src/service/migrate.rsindex c0a995e5..bde5f59f 100644--- a/src-tauri/src/service/migrate.rs+++ b/src-tauri/src/service/migrate.rs@@ -129,6 +129,21 @@ pub fn migrate_app_data_dir(app_handle: &AppHandle) -> Result<(), String> {}migrate_impl(&legacy, &target)?;+ // 依赖映射表记录的是绝对安装根,整树搬迁后旧路径已失效:清掉映射,让启动时的+ // 依赖检测按新位置重新建立(映射缺失时解析回落清单默认托管根)。+ for candidate in [+ target.join(config::dependencies::MAPPING_FILE),+ target+ .join(config::APP_DATA_DEV_DIR_NAME)+ .join(config::dependencies::MAPPING_FILE),+ ] {+ if candidate.is_file() {+ match fs::remove_file(&candidate) {+ Ok(()) => log::info!("removed stale dependency mapping: {}", candidate.display()),+ Err(e) => log::warn!("remove {} failed: {e}", candidate.display()),+ }+ }+ }log::info!("app data dir migrated: {} -> {}",legacy.display(),diff --git a/src-tauri/src/service/plugin/install/pnpm.rs b/src-tauri/src/service/plugin/install/pnpm.rsindex d5cc9c19..b63b4151 100644--- a/src-tauri/src/service/plugin/install/pnpm.rs+++ b/src-tauri/src/service/plugin/install/pnpm.rs@@ -110,9 +110,11 @@ pub(super) async fn ensure_pnpm(.map_err(|e| format!("PNPM_INTEGRITY_FAILED: {e}"))?;let dest = download::Pnpm.get_install_path(app_handle);- download::ensure_extract(&tracker, name, buffer, dest)+ download::ensure_extract(&tracker, name, buffer, dest.clone()).await.map_err(|e| format!("PNPM_EXTRACT_FAILED: {e}"))?;+ // 捆绑 pnpm 落盘后,该依赖的安装根即托管根(映射表随之更新)。+ config::dependencies::record(app_handle, config::dependencies::DEP_PNPM, Some(dest));let _ = window.emit(PREINSTALL_LOG_EVENT,@@ -632,11 +634,7 @@ fn parse_pnpm_major_output(pnpm: &Path, output: &std::process::Output) -> Option/// 安装不同的 pnpm(Corepack / 转发型 shim 尤其明显),使选出的主版本与实际安装/// 的不一致;反过来,少了 `bin_dir` 这一层就会漏掉「按 PATH 解析回桌面 shim」的/// 间接层,得出与安装相反的结论。-fn pnpm_probe_path(- pnpm: &Path,- node: Option<&Path>,- bin_dir: Option<&Path>,-) -> Option<OsString> {+fn pnpm_probe_path(pnpm: &Path, node: Option<&Path>, bin_dir: Option<&Path>) -> Option<OsString> {let mut paths = Vec::new();if let Some(bin_dir) = bin_dir {paths.push(bin_dir.to_path_buf());@@ -1141,7 +1139,10 @@ virtualStoreDir: node_modules/.pnpmstrip_store_version("/Users/gao/Library/pnpm/store/v10/"),"/Users/gao/Library/pnpm/store");- assert_eq!(strip_store_version("D:\\.pnpm-store\\v3"), "D:\\.pnpm-store");+ assert_eq!(+ strip_store_version("D:\\.pnpm-store\\v3"),+ "D:\\.pnpm-store"+ );}#[test]@@ -1151,7 +1152,10 @@ virtualStoreDir: node_modules/.pnpmstrip_store_version("C:\\Users\\x\\pnpm\\store"),"C:\\Users\\x\\pnpm\\store");- assert_eq!(strip_store_version("/mnt/pnpm-store-v10"), "/mnt/pnpm-store-v10");+ assert_eq!(+ strip_store_version("/mnt/pnpm-store-v10"),+ "/mnt/pnpm-store-v10"+ );assert_eq!(strip_store_version("/mnt/v-store"), "/mnt/v-store");assert_eq!(strip_store_version("v10"), "v10");assert_eq!(strip_store_version(""), "");diff --git a/src-tauri/src/service/plugin/install/single.rs b/src-tauri/src/service/plugin/install/single.rsindex dfd8a1d7..7441a93e 100644--- a/src-tauri/src/service/plugin/install/single.rs+++ b/src-tauri/src/service/plugin/install/single.rs@@ -146,22 +146,24 @@ pub async fn remove(app_handle: &AppHandle, id: &str) -> Result<(), String> {/// 计算需要自动卸载的弃用插件已安装包名(纯函数,便于单测)。///-/// 命中条件:id 登记在弃用清单(`resources/deprecated-plugins.json`,见-/// [`super::super::preset::load_deprecated_ids`])且当前已安装。返回实际安装包名-/// ——离线卸载(`uninstall_recovery`)以它为键从 profile 清单与 `node_modules`-/// 精准移除(scoped 包名与预设 id 不一致时也能正确卸载)。+/// 命中条件:id 登记在弃用名单(`resources/manifest.jsonc` 的 `plugins.depercated`,+/// 见 [`super::super::preset::load_deprecated_ids`])且当前已安装,或插件被当前核心+/// 淘汰([`PreinstallPluginInfo::retire_on`]:核心已超出清单声明的版本区间、或已安装+/// 版本不再落在该核心对应的插件版本区间内)。返回实际安装包名——离线卸载+/// (`uninstall_recovery`)以它为键从 profile 清单与 `node_modules` 精准移除+/// (scoped 包名与预设 id 不一致时也能正确卸载)。////// 两条来源缺一不可:/// 1. 预设仍声明该 id:以 `installed_name`(实际 npm 包名)为准;内部插件由启动/// 自愈强制安装,不适用弃用语义,跳过。/// 2. 兜底——预设清单已不存在该 id(被整体删除,如 `dsh-tauri-panel` 并入核心后-/// 从 `internal-plugins.json` 移除):此时按弃用清单登记的 id 本身核对。少了+/// 从 `plugins.built-in` 移除):此时按弃用名单登记的 id 本身核对。少了/// 这一步,弃用名单对「连预设条目一起删掉」的插件永远无效,其 `link:` 目标还会/// 因安装目录残留而躲过失效链接清理,残留 bundle 直接拖垮启动。fn deprecated_installed_names(presets: &[PreinstallPluginInfo],deprecated_ids: &HashSet<String>,- unsupported_ids: &HashSet<String>,+ core_version: Option<&str>,installed: impl Fn(&str) -> bool,installed_version: impl Fn(&str) -> Option<String>,) -> Vec<String> {@@ -175,22 +177,7 @@ fn deprecated_installed_names(if !p.internal && deprecated_ids.contains(&p.id) {return true;}- if !unsupported_ids.contains(&p.id) {- return false;- }- let Some(limit) = p.version.as_deref() else {- return true;- };- let Some(actual) = installed_version(name) else {- return false;- };- match (- semver::Version::parse(&actual),- semver::Version::parse(limit),- ) {- (Ok(actual), Ok(limit)) => !actual.cmp_precedence(&limit).is_gt(),- _ => false,- }+ p.retire_on(core_version, installed_version(name).as_deref())}).map(|p| installed_name(p).to_string()).collect();@@ -222,17 +209,11 @@ pub(crate) async fn uninstall_deprecated_plugins(app_handle: &AppHandle) -> Resulet presets = load_presets(app_handle);let core_version = core::active_version(app_handle);let deprecated_ids = load_deprecated_ids(app_handle);- let mut unsupported_ids: HashSet<String> = HashSet::new();- for preset in &presets {- if preset.unsupported_on(core_version.as_deref()) {- unsupported_ids.insert(preset.id.clone());- }- }let profile = profile_dir(app_handle);let names = deprecated_installed_names(&presets,&deprecated_ids,- &unsupported_ids,+ core_version.as_deref(),|name| deprecated_residue_present(app_handle, name),|name| installed_package_version(&profile, name),);@@ -427,30 +408,48 @@ async fn run_single_plugin_command(#[cfg(test)]mod tests {use super::*;- /// 测试入口:只关心弃用清单时补一个空的 unsupported 集合。+ use crate::config::manifest::{PluginVersion, VersionPair};++ /// 测试入口:只关心弃用清单时补一个「未知核心版本 + 未知已安装版本」。fn deprecated_names(presets: &[PreinstallPluginInfo],ids: &HashSet<String>,installed: impl Fn(&str) -> bool,) -> Vec<String> {- deprecated_installed_names(presets, ids, &HashSet::new(), installed, |_| None)+ deprecated_installed_names(presets, ids, None, installed, |_| None)}- /// 内置插件被核心吸收后同样退役:只靠 `dshSupportedVersion` 判定,弃用清单不参与。+ /// 内置插件被核心吸收后同样退役:只靠清单声明的版本矩阵(`retire_on`)判定,+ /// 弃用清单不参与。#[test]fn unsupported_internal_entry_is_uninstalled() {- let internal = preset("dsh-internal", "[email protected]", true);- let unsupported: HashSet<String> = ["dsh-internal"].into_iter().map(String::from).collect();+ let mut entry = preset("dsh-internal", "[email protected]", true);+ entry.version = Some(PluginVersion::Matrix(vec![VersionPair {+ version: "^1.2.3".into(),+ dsh: "^0.1.5-rc.1".into(),+ }]));++ // 核心已超出声明区间,且已安装版本仍落在同代区间内 → 退役assert_eq!(deprecated_installed_names(- &[internal],+ &[entry.clone()],&HashSet::new(),- &unsupported,+ Some("0.2.0"),|name| name == "dsh-internal",- |_| None,+ |_| Some("1.2.3".into()),),vec!["dsh-internal".to_string()]);++ // 已安装版本比清单声明的更新 → 保留,不误删用户手上的修复版+ assert!(deprecated_installed_names(+ &[entry],+ &HashSet::new(),+ Some("0.2.0"),+ |name| name == "dsh-internal",+ |_| Some("2.0.0".into()),+ )+ .is_empty());}fn preset(id: &str, spec: &str, internal: bool) -> PreinstallPluginInfo {@@ -465,7 +464,6 @@ mod tests {fix: false,default_checked: false,default_unchecked: false,- dsh_supported_version: None,version: None,win_only: false,internal,@@ -473,70 +471,61 @@ mod tests {}#[test]- fn unsupported_cleanup_respects_installed_version_cap() {- for (cap, actual, remove) in [- (Some("1.2.0"), Some("1.1.9"), true),- (Some("1.2.0"), Some("1.2.0"), true),- (Some("1.2.0"), Some("1.2.1"), false),- (Some("1.2.0"), Some("1.10.0"), false),- (Some("1.2.0"), Some("1.2.0-rc.2"), true),- (Some("1.2.0-rc.2"), Some("1.2.0-rc.10"), false),- (Some("1.2.0-rc.2"), Some("1.2.0"), false),- (Some("1.2.0"), Some("1.2.0+reinstalled"), true),- (Some("1.2.0+original"), Some("1.2.0+rebuilt"), true),- (Some("1.2.0"), None, false),- (Some("1.2.0"), Some("invalid"), false),+ fn unsupported_cleanup_respects_declared_version_ranges() {+ let declared = vec![+ VersionPair {+ version: "^1.2.0".into(),+ dsh: "^0.1.5-rc.1".into(),+ },+ VersionPair {+ version: "^1.4.0".into(),+ dsh: "^0.1.7-rc.1".into(),+ },+ ];+ for (core, actual, remove) in [+ (Some("0.1.5-rc.3"), Some("1.2.0"), false),+ (Some("0.1.6"), Some("1.2.5"), false),+ (Some("0.1.6"), Some("1.4.0"), false),+ (Some("0.1.7-rc.2"), Some("1.4.0"), false),+ (Some("0.1.7-rc.2"), Some("1.2.0"), true),+ (Some("0.2.0"), Some("1.4.0"), true),+ (Some("0.2.0"), Some("2.0.0"), false),+ (Some("0.2.0"), Some("1.0.0"), false),+ (Some("0.2.0"), None, false),+ (Some("0.2.0"), Some("invalid"), false),+ (None, Some("1.2.0"), false),(Some("invalid"), Some("1.2.0"), false),- (Some(""), Some("1.2.0"), false),- (None, Some("9.0.0"), true),- (None, None, true),] {let mut entry = preset("probe", "@scope/probe", false);entry.package = Some("@scope/probe".into());- entry.version = cap.map(String::from);- entry.dsh_supported_version = Some("0.1.7".into());- for core in [- None,- Some("invalid"),- Some("0.1.6"),- Some("0.1.7"),- Some("0.1.8"),- ] {- let unsupported = if entry.unsupported_on(core) {- HashSet::from([entry.id.clone()])- } else {- HashSet::new()- };- let names = deprecated_installed_names(- &[entry.clone()],- &HashSet::new(),- &unsupported,- |name| name == "@scope/probe",- |name| {- assert_eq!(name, "@scope/probe");- actual.map(String::from)- },- );- let expected = if remove && core == Some("0.1.8") {- vec!["@scope/probe".to_string()]- } else {- Vec::new()- };- assert_eq!(- names, expected,- "core={core:?}, cap={cap:?}, actual={actual:?}"- );- }+ entry.version = Some(PluginVersion::Matrix(declared.clone()));+ let names = deprecated_installed_names(+ &[entry.clone()],+ &HashSet::new(),+ core,+ |name| name == "@scope/probe",+ |name| {+ assert_eq!(name, "@scope/probe");+ actual.map(String::from)+ },+ );+ let expected = if remove {+ vec!["@scope/probe".to_string()]+ } else {+ Vec::new()+ };+ assert_eq!(names, expected, "core={core:?}, actual={actual:?}");}}#[test]- fn explicit_deprecation_still_removes_versions_above_cap() {+ fn explicit_deprecation_removes_regardless_of_installed_version() {+ // 显式弃用是发布侧决策:与已安装版本、与核心版本都无关,一律卸载let mut entry = preset("probe", "probe", false);- entry.version = Some("1.2.0".into());+ entry.version = Some(PluginVersion::Declared("1.2.0".into()));let ids = HashSet::from(["probe".to_string()]);assert_eq!(- deprecated_installed_names(&[entry], &ids, &ids, |_| true, |_| Some("2.0.0".into()),),+ deprecated_installed_names(&[entry], &ids, None, |_| true, |_| Some("2.0.0".into()),),vec!["probe".to_string()]);}@@ -553,12 +542,14 @@ mod tests {.unwrap();let mut entry = preset("probe", "@scope/probe", false);entry.package = Some("@scope/probe".into());- entry.version = Some("1.2.0".into());- let unsupported = HashSet::from(["probe".to_string()]);+ entry.version = Some(PluginVersion::Matrix(vec![VersionPair {+ version: "^0.18.0".into(),+ dsh: "^0.1.5-rc.1".into(),+ }]));let names = deprecated_installed_names(&[entry],&HashSet::new(),- &unsupported,+ Some("0.2.0"),|_| true,|name| installed_package_version(&dir, name),);@@ -617,7 +608,7 @@ mod tests {#[test]fn deprecated_installed_falls_back_when_preset_entry_removed() {// 弃用条目已从预设清单整体删除(dsh-tauri-panel 并入核心后从- // internal-plugins.json 移除):预设驱动的循环命中不到,兜底按 id 卸载。+ // plugins.built-in 移除):预设驱动的循环命中不到,兜底按 id 卸载。let removed: HashSet<String> = ["dsh-tauri-panel"].into_iter().map(String::from).collect();assert_eq!(diff --git a/src-tauri/src/service/plugin/install/spec.rs b/src-tauri/src/service/plugin/install/spec.rsindex 31f26831..258e64f2 100644--- a/src-tauri/src/service/plugin/install/spec.rs+++ b/src-tauri/src/service/plugin/install/spec.rs@@ -159,7 +159,6 @@ mod tests {fix: false,default_checked: false,default_unchecked: false,- dsh_supported_version: None,version: None,win_only: false,internal,diff --git a/src-tauri/src/service/plugin/installed.rs b/src-tauri/src/service/plugin/installed.rsindex 981f82c5..1b6d1dcf 100644--- a/src-tauri/src/service/plugin/installed.rs+++ b/src-tauri/src/service/plugin/installed.rs@@ -103,10 +103,10 @@ pub(crate) fn installed_name(p: &PreinstallPluginInfo) -> &str {pub fn list(app_handle: &AppHandle) -> Vec<PreinstallPlugin> {let installed = list_installed(app_handle);let is_windows = cfg!(windows);- // 弃用插件(deprecated-plugins.json 登记)不再提供安装入口,启动时自动卸载,+ // 弃用插件(清单 `plugins.depercated` 登记)不再提供安装入口,启动时自动卸载,// 不进入首次引导清单。let deprecated_ids = load_deprecated_ids(app_handle);- // 当前活动核心版本:用于判定预设声明的 `dshSupportedVersion` 是否已被超越。+ // 当前活动核心版本:按预设声明的(插件版本 ↔ 核心版本)矩阵判定兼容性。let core_version = crate::service::core::active_version(app_handle);load_presets(app_handle)@@ -281,7 +281,6 @@ mod tests {fix: false,default_checked: true,default_unchecked: false,- dsh_supported_version: None,version: None,win_only: false,internal: false,diff --git a/src-tauri/src/service/plugin/internal/mod.rs b/src-tauri/src/service/plugin/internal/mod.rsindex eeac0ed8..097fd61d 100644--- a/src-tauri/src/service/plugin/internal/mod.rs+++ b/src-tauri/src/service/plugin/internal/mod.rs@@ -1,5 +1,5 @@//! 内置插件启动自愈:随安装包分发的内置插件(条目位于-//! `internal-plugins.json`,产物目录 `resources/node_modules/<name>` 由构建期+//! `plugins.built-in`,产物目录 `resources/node_modules/<name>` 由构建期//! `scripts/build-plugins.ts` 的 `pnpm deploy` 打包)在服务启动前核对//! 「是否已安装 + 安装路径是否仍指向当前捆绑目录」:未安装 / 路径不正确 / 用户//! 卸载后残留缺失 → 一律走常规安装流程强制重装,保证桌面外壳依赖的桥接层@@ -241,7 +241,7 @@ pub(crate) fn repair_loader_state(app_handle: &AppHandle) -> Result<(), String>pub(crate) async fn ensure(app_handle: &AppHandle) -> Result<(), String> {let presets = load_presets(app_handle);- // 被核心吸收的内置插件(声明了 dshSupportedVersion 且当前核心已超越)自愈不再装回,+ // 被核心吸收的内置插件(当前核心已超出其声明的全部核心版本区间)自愈不再装回,// 与 `uninstall_deprecated_plugins` 的退役判定同源,避免两边互相拉扯。let core_version = crate::service::core::active_version(app_handle);let internal: Vec<_> = presetsdiff --git a/src-tauri/src/service/plugin/mod.rs b/src-tauri/src/service/plugin/mod.rsindex c6048cf8..c0e8e19c 100644--- a/src-tauri/src/service/plugin/mod.rs+++ b/src-tauri/src/service/plugin/mod.rs@@ -6,13 +6,14 @@//! 启动时加载。进程输出逐行通过 `preinstall-log` 事件实时推送给前端日志面板。//! 调用 dsh 前会先按需补齐捆绑 pnpm(老版本升级后可能缺失,安装流程内自愈)。//!-//! 社区预设与内部插件分别存放在随安装包分发的 `resources/preset-plugins.json`-//! 和 `resources/internal-plugins.json`;新增条目无需改动 Rust 代码。+//! 社区预设与内部插件分别存放在随安装包分发的 `resources/manifest.jsonc` 的+//! `plugins.preset` 与 `plugins.built-in` 两节;新增条目无需改动 Rust 代码。//!-//! **重新进入引导的判定**:该 JSON 随安装包发布、每次安装都被强制覆盖,旧文件不可比对,-//! 因此引导结束(确认/跳过)时把文件内容指纹(FNV-1a)写入 app-data 的 `.store.dat`;-//! 每次启动重新计算当前指纹,不一致(清单有变更)即重新进入预设引导;老用户无基线时-//! 弹一次建立基线(见 [`preset::preinstall_pending`])。+//! **重新进入引导的判定**:清单随安装包发布、每次安装都被强制覆盖,旧内容不可比对,+//! 因此引导结束(确认/跳过)时把清单 `plugins` 节的内容指纹(FNV-1a)写入 app-data 的 `.store.dat`;+//! 每次启动重新计算当前指纹,不一致(插件节有变更)即重新进入预设引导;老用户无基线时+//! 弹一次建立基线(见 [`preset::preinstall_pending`])。指纹只覆盖插件节,改宠物或+//! 依赖映射不会把用户重新拉回引导。//!//! 模块划分(参考 `service/cli/`、`service/download/`)://! - [`preset`]:预设与内部插件清单读取、合并及资源目录定位@@ -21,7 +22,7 @@//! - [`verify`]:预装插件完整性自检(清单引用但 node_modules 产物缺失时 `pnpm install` 修复)//! - [`install`]:对外安装/升级/卸载编排(目录模块 `install/`:编排入口、spec 准备、//! 子进程环境、pnpm 选版、allowBuilds 白名单、错误诊断与产物核验),-//! 以及启动时对 `resources/deprecated-plugins.json` 登记的社区插件自动卸载+//! 以及启动时对 `plugins.depercated` 登记的社区插件自动卸载//! - [`errors`]:插件错误记录(安装/升级/卸载失败 + 页面运行期上报,持久化)//! - [`process`]:dsh 子进程启动与输出流逐行转发//! - [`recovery`]:插件异常定位与一键离线卸载diff --git a/src-tauri/src/service/plugin/preset.rs b/src-tauri/src/service/plugin/preset.rsindex f11b2fb2..4b21d9f1 100644--- a/src-tauri/src/service/plugin/preset.rs+++ b/src-tauri/src/service/plugin/preset.rs@@ -1,9 +1,7 @@-//! 插件清单:分别读取随安装包分发的 `resources/preset-plugins.json` 与-//! `resources/internal-plugins.json`,弃用名单单独维护在-//! `resources/deprecated-plugins.json`(只登记预设插件 id,不参与预设合并)。-//!-//! 社区预设与内部插件分开维护;运行时合并为统一结构供安装、展示与自愈逻辑使用。-//! 资源缺失/损坏时报错并回落为空清单,不阻断启动。+//! 插件清单:读取随安装包分发的 `resources/manifest.jsonc` 的 `plugins` 节+//! (`preset` 社区预设、`built-in` 内置插件、`depercated` 弃用名单分开维护);+//! 运行时合并为统一结构供安装、展示与自愈逻辑使用。+//! 清单缺失/损坏时报错并回落为空清单,不阻断启动。use serde::Deserialize;use std::collections::HashSet;@@ -11,72 +9,101 @@ use std::path::{Path, PathBuf};use tauri::{AppHandle, Manager};use crate::config;+use crate::config::manifest::{PluginEntry, PluginVersion};-/// 预设插件清单文件名-const PRESET_PLUGINS_FILE: &str = "preset-plugins.json";-/// 内部插件清单文件名-const INTERNAL_PLUGINS_FILE: &str = "internal-plugins.json";-/// 弃用插件清单文件名(只登记预设插件 id)-const DEPRECATED_PLUGINS_FILE: &str = "deprecated-plugins.json";--/// 插件静态信息,对应预设或内部插件清单中的条目-#[derive(Debug, Clone, Deserialize)]-#[serde(rename_all = "camelCase")]+/// 插件静态信息,对应清单中的条目+#[derive(Debug, Clone)]pub struct PreinstallPluginInfo {/// 前端主键 / 仓库跳转查找键pub id: String,/// 传给 `dsh plugin add` 的依赖形式(npm 包名或 git 依赖形式)pub spec: String,- #[serde(default)]- pub version: Option<String>,+ /// 版本区间声明:字符串形式或(插件版本区间 ↔ 核心版本区间)配对矩阵+ pub version: Option<PluginVersion>,/// 内置插件:条目来自发布清单,或 debug 下仓库根 `packages/*` 中带有/// 有效 `dsh` 对象的 workspace 包。内置插件固定从本地捆绑目录安装,启动时/// 强制核对「已安装 + 路径指向当前捆绑目录」,因此不出现在首次引导清单里。- #[serde(default)]pub internal: bool,/// 安装进 profile 后实际出现在 `dependencies`/`bundles` 里的包名。/// 默认与 `id` 相同;scoped 包或 id 与包名不同时显式指定。- #[serde(default)]pub package: Option<String>,pub name: String,pub description: String,pub repo_url: String,- /// 绿色「推荐」chip,默认勾选(普通推荐插件)- #[serde(default)]+ /// 绿色「推荐」chip,默认勾选pub recommended: bool,/// 黄色「修复」chip,默认勾选(Windows 极简模式修复项)- #[serde(default)]pub fix: bool,/// 无 chip 但默认勾选(不标「推荐」,首次引导仍直接勾上)- #[serde(default)]pub default_checked: bool,/// 显式声明首次引导不默认勾选:仍可标「推荐」chip,但不预选(如 dsh-im)- #[serde(default)]pub default_unchecked: bool,- #[serde(default)]- pub dsh_supported_version: Option<String>,/// 仅 Windows 平台列出- #[serde(default)]pub win_only: bool,}impl PreinstallPluginInfo {- /// 当前核心是否已高于该预设声明的支持上限。+ /// 当前核心是否已超出该预设声明的全部核心版本区间。////// 任一侧版本缺失或无法解析时按兼容处理:清单字段是发布侧提示,解析失败/// 不应把插件在界面上误标为「不支持当前核心」。pub(crate) fn unsupported_on(&self, core_version: Option<&str>) -> bool {- let (Some(core), Some(limit)) = (core_version, self.dsh_supported_version.as_deref())- else {+ self.version+ .as_ref()+ .is_some_and(|version| version.unsupported_on(core_version))+ }++ /// 核心驱动的退役判定(弃用 / 被核心吸收后自动卸载)。+ ///+ /// - 核心已超出声明区间:已安装版本落在任一同代区间内(旧版本)→ 退役;+ /// - 核心命中某区间:已安装版本不满足该区间的插件版本区间 → 退役(由安装流程+ /// 装回兼容版本);+ /// - 未声明区间 / 版本不可解析 → 不退役(宁可保留也不误删)。+ pub(crate) fn retire_on(+ &self,+ core_version: Option<&str>,+ installed_version: Option<&str>,+ ) -> bool {+ let Some(version) = self.version.as_ref() else {+ return false;+ };+ if version.unsupported_on(core_version) {+ return version.matches_any_declared(installed_version);+ }+ let Some(req) = version.plugin_req_for_core(core_version) else {return false;};- match (semver::Version::parse(core), semver::Version::parse(limit)) {- (Ok(core), Ok(limit)) => core > limit,+ match (+ semver::VersionReq::parse(req),+ installed_version.and_then(|value| semver::Version::parse(value).ok()),+ ) {+ (Ok(req), Some(installed)) => !req.matches(&installed),_ => false,}}}+/// 清单条目 → 统一插件信息:`checked` 是唯一真值,按前端预选语义派生出+/// 「默认勾选」与「显式不预选」两个标记。+fn plugin_info(entry: PluginEntry, internal: bool) -> PreinstallPluginInfo {+ let checked = entry.checked;+ PreinstallPluginInfo {+ id: entry.id,+ spec: entry.spec,+ version: entry.version,+ internal,+ package: entry.package,+ name: entry.name,+ description: entry.description,+ repo_url: entry.repo,+ recommended: entry.recommended,+ fix: entry.fix,+ default_checked: checked && !entry.recommended,+ default_unchecked: !checked,+ win_only: entry.win_only,+ }+}+/// debug workspace 插件 package.json 中用于生成内置元数据的字段。#[cfg(debug_assertions)]#[derive(Clone, Deserialize, Default)]@@ -208,7 +235,6 @@ fn discover_dev_internal_plugins_at(root: &Path) -> Vec<DevPluginCandidate> {fix: false,default_checked: false,default_unchecked: false,- dsh_supported_version: None,version: None,win_only: false,};@@ -234,7 +260,7 @@ fn dev_plugin_dir(id: &str) -> Option<PathBuf> {.map(|candidate| candidate.directory)}-/// 把仓库根 `packages/*` 发现的内置插件合并进静态 `internal-plugins.json` 清单。+/// 把仓库根 `packages/*` 发现的内置插件合并进清单的 `plugins.built-in` 静态条目。////// 同名 dev 候选覆盖静态条目(开发时以仓库源码为准,安装目标指到 `packages/`);/// 未在静态清单中出现的 dev 插件会被追加,保证 debug 观察到的内置插件集合@@ -257,11 +283,9 @@ fn merge_dev_internal_plugins_at(.collect();for plugin in internal.iter_mut() {if let Some(candidate) = by_id.remove(&plugin.id) {- // 上限是发布侧对核心的计划(清单声明),dev 候选不带该字段,覆盖时沿用静态条目。- let supported = plugin.dsh_supported_version.take();+ // 版本区间是发布侧对核心的计划(清单声明),dev 候选不带该字段,覆盖时沿用静态条目。let version = plugin.version.take();*plugin = candidate.info;- plugin.dsh_supported_version = supported;plugin.version = version;}}@@ -269,39 +293,6 @@ fn merge_dev_internal_plugins_at(internal}-/// 在资源根目录下查找清单:先探测扁平布局(exe 同级),再探测-/// `resources/` 子目录布局(Tauri 2 的 `bundle.resources` 按相对路径保留前缀)。-fn find_manifest_in_resource_root(root: &std::path::Path, file_name: &str) -> Option<PathBuf> {- let flat = root.join(file_name);- if flat.exists() {- return Some(flat);- }- let nested = root.join("resources").join(file_name);- nested.exists().then_some(nested)-}--/// 定位插件清单文件:优先使用随安装包分发的资源目录,回落到源码开发目录。-///-/// 注意:Tauri 2 在 Windows 上 `resource_dir()` 恒等于 exe 所在目录,而安装包-/// (NSIS/MSI)与开发产物都会把资源按 `resources/**` 前缀落盘到-/// `{resource_dir}/resources/` 子目录,因此必须探测该子目录;`CARGO_MANIFEST_DIR`-/// 是编译期路径,仅开发机有效(CI/发布版在本机不可用),只作最后兜底。-fn plugins_manifest_path(app_handle: &AppHandle, file_name: &str) -> Option<PathBuf> {- if let Ok(dir) = app_handle.path().resource_dir() {- if let Some(candidate) = find_manifest_in_resource_root(&dir, file_name) {- return Some(candidate);- }- }- let source = PathBuf::from(env!("CARGO_MANIFEST_DIR"))- .join("resources")- .join(file_name);- source.exists().then_some(source)-}--fn preset_plugins_path(app_handle: &AppHandle) -> Option<PathBuf> {- plugins_manifest_path(app_handle, PRESET_PLUGINS_FILE)-}-/// 旧版内置插件资源目录名。作为查找回退保留(已装旧布局插件的自愈仍能命中),/// 同时由 [`remove_legacy_bundled_plugins`] 在启动时清理升级残留的整目录副本。const BUNDLED_PLUGINS_DIR: &str = "internal-plugins";@@ -436,99 +427,47 @@ pub(crate) fn bundled_dep_spec(dir: &std::path::Path) -> String {format!("link:{}", normalized.trim_end_matches('/'))}-/// 解析插件清单 JSON,并由清单来源统一设置内部插件标记。-///-/// 清单边界是可信的产品分类:即使条目误带或遗漏 `internal` 字段,也不能让社区-/// 预设获得必装自愈权限,或让内部插件退出自愈流程,因此始终以文件来源覆盖该值。-fn parse_plugins(json: &str, internal: bool) -> Result<Vec<PreinstallPluginInfo>, String> {- let mut plugins: Vec<PreinstallPluginInfo> =- serde_json::from_str(json).map_err(|e| format!("PLUGIN_MANIFEST_INVALID_JSON: {e}"))?;- for plugin in &mut plugins {- plugin.internal = internal;- }- Ok(plugins)-}--/// 读取单个插件清单;资源缺失/损坏时记录错误并返回空清单。-///-/// 插件元数据不是桌面壳启动的硬依赖;降级为空列表可让核心服务继续启动,同时用-/// 明确日志保留发布资源缺失或损坏的诊断信息,避免清单故障导致应用整体不可用。-fn load_manifest(- app_handle: &AppHandle,- file_name: &str,- internal: bool,-) -> Vec<PreinstallPluginInfo> {- let Some(path) = plugins_manifest_path(app_handle, file_name) else {- log::warn!("PLUGIN_MANIFEST_MISSING: {file_name} not found in resource dir or source resources dir");- return Vec::new();- };-- let raw = match std::fs::read_to_string(&path) {- Ok(s) => s,- Err(e) => {- log::error!("PLUGIN_MANIFEST_READ_FAILED: {}: {e}", path.display());- return Vec::new();- }- };-- parse_plugins(&raw, internal).unwrap_or_else(|e| {- log::error!("PLUGIN_MANIFEST_PARSE_FAILED: {}: {e}", path.display());- Vec::new()- })-}--/// 读取预设与内部插件清单并合并;内部属性由文件归属决定,不依赖 JSON 字段。+/// 读取 `plugins.preset` / `plugins.built-in` 并合并;内部属性由清单节归属决定,+/// 不依赖条目字段。////// **开发覆盖(仅 debug 构建)**:仓库根 `packages/*` 中非私有且含 `dsh` 对象的-/// workspace 包会按 id 覆盖静态内部清单条目,未登记的新插件一并追加,因此开发时+/// workspace 包会按 id 覆盖静态内置清单条目,未登记的新插件一并追加,因此开发时/// 观察到的内置插件集合以仓库源码为准,与 release(只认随包清单)逻辑一致。pub(crate) fn load_presets(app_handle: &AppHandle) -> Vec<PreinstallPluginInfo> {- let mut plugins = load_manifest(app_handle, PRESET_PLUGINS_FILE, false);- let internal = load_manifest(app_handle, INTERNAL_PLUGINS_FILE, true);+ let Some(manifest) = config::manifest::read(app_handle) else {+ return Vec::new();+ };+ let mut plugins: Vec<PreinstallPluginInfo> = manifest+ .plugins+ .preset+ .into_iter()+ .map(|entry| plugin_info(entry, false))+ .collect();+ let internal: Vec<PreinstallPluginInfo> = manifest+ .plugins+ .built_in+ .into_iter()+ .map(|entry| plugin_info(entry, true))+ .collect();#[cfg(debug_assertions)]let internal = merge_dev_internal_plugins(internal);plugins.extend(internal);plugins}-/// 解析弃用插件清单 JSON(纯字符串数组),返回 id 集合(重复 id 自动去重)。-fn parse_deprecated_ids(json: &str) -> Result<HashSet<String>, String> {- let ids: Vec<String> = serde_json::from_str(json)- .map_err(|e| format!("DEPRECATED_PLUGINS_MANIFEST_INVALID_JSON: {e}"))?;- Ok(ids.into_iter().collect())-}--/// 读取弃用插件清单(`resources/deprecated-plugins.json`),返回已登记的预设-/// 插件 id 集合。+/// 读取弃用插件名单(`resources/manifest.jsonc` 的 `plugins.depercated`),返回+/// 已登记的预设插件 id 集合。///-/// 弃用是发布侧决策:某社区插件下架/被替换后,把它的 id 追加进该文件,桌面端-/// 每次启动核对「已安装 → 自动卸载」(见-/// [`super::install::uninstall_deprecated_plugins`])。与 `preset-plugins.json`-/// 分开维护:预设清单只描述「可安装项」,弃用清单只描述「不再提供安装入口的-/// 预设 id」,调整弃用名单不会让既有用户重新进入首次引导。资源缺失/损坏时-/// 记录错误并回落为空集合,不阻断启动(与其它清单同一降级策略)。+/// 弃用是发布侧决策:某社区插件下架/被替换后,把它的 id 追加进清单,桌面端每次+/// 启动核对「已安装 → 自动卸载」(见+/// [`super::install::uninstall_deprecated_plugins`])。与 `plugins.preset` 分开+/// 维护:预设清单只描述「可安装项」,弃用名单只描述「不再提供安装入口的预设 id」,+/// 调整弃用名单不会让既有用户重新进入首次引导。清单缺失/损坏时回落为空集合,+/// 不阻断启动(与其它清单同一降级策略)。pub(crate) fn load_deprecated_ids(app_handle: &AppHandle) -> HashSet<String> {- let Some(path) = plugins_manifest_path(app_handle, DEPRECATED_PLUGINS_FILE) else {- log::warn!("DEPRECATED_PLUGINS_MANIFEST_MISSING: {DEPRECATED_PLUGINS_FILE} not found in resource dir or source resources dir");- return HashSet::new();- };- let raw = match std::fs::read_to_string(&path) {- Ok(s) => s,- Err(e) => {- log::error!(- "DEPRECATED_PLUGINS_MANIFEST_READ_FAILED: {}: {e}",- path.display()- );- return HashSet::new();- }- };- parse_deprecated_ids(&raw).unwrap_or_else(|e| {- log::error!(- "DEPRECATED_PLUGINS_MANIFEST_PARSE_FAILED: {}: {e}",- path.display()- );- HashSet::new()- })+ config::manifest::read(app_handle)+ .map(|manifest| manifest.plugins.deprecated.into_iter().collect())+ .unwrap_or_default()}/// 预装清单中某 id 对应的仓库地址@@ -549,11 +488,14 @@ fn fnv1a(bytes: &[u8]) -> u64 {hash}-/// 当前 `preset-plugins.json` 内容指纹(十六进制 FNV-1a);文件缺失/不可读返回 None+/// 当前 `plugins` 节的内容指纹(十六进制 FNV-1a)。+///+/// 指纹只覆盖插件节:清单同时承载引擎版本、宠物与依赖映射规范,改宠物不应把用户+/// 重新拉回首次引导。清单缺失/不可读返回 None。pub(crate) fn current_preset_hash(app_handle: &AppHandle) -> Option<String> {- let path = preset_plugins_path(app_handle)?;- let raw = std::fs::read(&path).ok()?;- Some(format!("{:016x}", fnv1a(&raw)))+ let manifest = config::manifest::read(app_handle)?;+ let canonical = serde_json::to_string(&manifest.plugins).ok()?;+ Some(format!("{:016x}", fnv1a(canonical.as_bytes())))}/// 是否需要进入预装插件引导:@@ -579,25 +521,77 @@ pub(crate) fn preinstall_pending(app_handle: &AppHandle) -> bool {#[cfg(test)]mod tests {use super::*;+ use crate::config::manifest::{PluginVersion, VersionPair};- fn load_manifest_for_test(file_name: &str, internal: bool) -> Vec<PreinstallPluginInfo> {- let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))+ fn manifest_path_for_test() -> PathBuf {+ PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources")- .join(file_name);- let raw = std::fs::read_to_string(path).expect("plugin manifest should exist");- parse_plugins(&raw, internal).expect("plugin manifest should be valid JSON")+ .join(crate::config::manifest::MANIFEST_FILE)+ }++ fn load_manifest_for_test() -> crate::config::manifest::Manifest {+ crate::config::manifest::read_at(&manifest_path_for_test())+ .expect("resource manifest should exist and parse")+ }++ /// 解析内联清单文本并投影到统一插件信息(`preset` 或 `built-in` 节)。+ fn plugin_infos_from(raw: &str, internal: bool) -> Vec<PreinstallPluginInfo> {+ let manifest = crate::config::manifest::parse(raw).expect("manifest should parse");+ let entries = if internal {+ manifest.plugins.built_in+ } else {+ manifest.plugins.preset+ };+ entries+ .into_iter()+ .map(|entry| plugin_info(entry, internal))+ .collect()}fn load_presets_for_test() -> Vec<PreinstallPluginInfo> {- load_manifest_for_test(PRESET_PLUGINS_FILE, false)+ load_manifest_for_test()+ .plugins+ .preset+ .into_iter()+ .map(|entry| plugin_info(entry, false))+ .collect()+ }++ fn load_internal_for_test() -> Vec<PreinstallPluginInfo> {+ load_manifest_for_test()+ .plugins+ .built_in+ .into_iter()+ .map(|entry| plugin_info(entry, true))+ .collect()}fn load_all_plugins_for_test() -> Vec<PreinstallPluginInfo> {let mut plugins = load_presets_for_test();- plugins.extend(load_manifest_for_test(INTERNAL_PLUGINS_FILE, true));+ plugins.extend(load_internal_for_test());plugins}+ fn shipped_deprecated_ids() -> HashSet<String> {+ load_manifest_for_test()+ .plugins+ .deprecated+ .into_iter()+ .collect()+ }++ fn matrix(pairs: &[(&str, &str)]) -> PluginVersion {+ PluginVersion::Matrix(+ pairs+ .iter()+ .map(|(version, dsh)| VersionPair {+ version: (*version).to_string(),+ dsh: (*dsh).to_string(),+ })+ .collect(),+ )+ }+#[test]fn preset_list_contains_dshmarket() {let presets = load_presets_for_test();@@ -613,23 +607,30 @@ mod tests {}#[test]- fn preset_manifest_declares_core_and_automatic_removal_ceilings() {+ fn preset_manifest_declares_version_matrix_per_core() {let presets = load_presets_for_test();- let expected = [- ("dshmarket", "0.1.7", "1.58.0"),- ("dsh-better-sidebar", "0.1.5-rc.2", "0.19.1"),- ("dsh-rewind-plugin", "0.1.5-rc.2", "0.12.2"),- ("@xmanrui/dsh-im", "0.1.5-rc.2", "4.25.0"),+ let expected: [(&str, PluginVersion); 4] = [+ ("dshmarket", PluginVersion::Declared("latest".into())),+ (+ "dsh-better-sidebar",+ matrix(&[("^0.19.1", "^0.1.5-rc.1"), ("^0.21.1", "^0.1.7-rc.1")]),+ ),+ (+ "dsh-rewind-plugin",+ matrix(&[+ ("^0.12.2", "^0.1.5-rc.1"),+ ("^0.14.0-beta.1", "^0.1.7-rc.1"),+ ]),+ ),+ (+ "@xmanrui/dsh-im",+ matrix(&[("^4.25.0", "^0.1.5-rc.1"), ("^4.28.0", "^0.1.7-rc.1")]),+ ),];assert_eq!(presets.len(), expected.len());- for (id, core_ceiling, removal_ceiling) in expected {+ for (id, version) in expected {let preset = presets.iter().find(|p| p.id == id).expect(id);- assert_eq!(- preset.dsh_supported_version.as_deref(),- Some(core_ceiling),- "{id}"- );- assert_eq!(preset.version.as_deref(), Some(removal_ceiling), "{id}");+ assert_eq!(preset.version.as_ref(), Some(&version), "{id}");assert_eq!(preset.spec, id);}}@@ -637,19 +638,62 @@ mod tests {#[test]fn preset_supported_version_marks_newer_cores_unsupported() {let presets = load_presets_for_test();- for (id, equal, newer) in [- ("dshmarket", "0.1.7", "0.1.8-alpha.1"),- ("dsh-better-sidebar", "0.1.5-rc.2", "0.1.6-alpha.2"),- ("dsh-rewind-plugin", "0.1.5-rc.2", "0.1.7-alpha.1"),- ("@xmanrui/dsh-im", "0.1.5-rc.2", "0.1.7-alpha.1"),- ] {+ for id in ["dsh-better-sidebar", "dsh-rewind-plugin", "@xmanrui/dsh-im"] {let preset = presets.iter().find(|p| p.id == id).expect(id);- assert!(!preset.unsupported_on(Some("0.1.5-rc.1")), "{id}");- assert!(!preset.unsupported_on(Some(equal)), "{id}");- assert!(preset.unsupported_on(Some(newer)), "{id}");+ // 两代矩阵(^0.1.5-rc.1 / ^0.1.7-rc.1)覆盖当前 rc 线+ for supported in ["0.1.5-rc.1", "0.1.5-rc.3", "0.1.6", "0.1.7-rc.2"] {+ assert!(+ !preset.unsupported_on(Some(supported)),+ "{id} @ {supported}"+ );+ }+ // 超出全部区间:下一个 minor 与未声明代次的预发布版都不再支持+ assert!(preset.unsupported_on(Some("0.2.0")), "{id}");+ assert!(preset.unsupported_on(Some("0.1.8-alpha.1")), "{id}");assert!(!preset.unsupported_on(None), "{id}");assert!(!preset.unsupported_on(Some("not-a-version")), "{id}");}+ // 字符串声明(`latest`)不参与核心区间判定+ let market = presets+ .iter()+ .find(|p| p.id == "dshmarket")+ .expect("dshmarket");+ for core in [Some("0.1.5-rc.3"), Some("9.9.9"), None] {+ assert!(!market.unsupported_on(core));+ }+ }++ /// 核心驱动的退役判定:核心命中某区间 → 已安装版本不满足该区间才退役;核心+ /// 超出全部区间 → 已安装版本仍落在任一同代区间内才退役(新版本宁可保留)。+ #[test]+ fn retire_decision_matrix_follows_declared_ranges() {+ let declared = matrix(&[("^1.2.0", "^0.1.5-rc.1"), ("^1.4.0", "^0.1.7-rc.1")]);+ for (core, installed, retire) in [+ (Some("0.1.5-rc.3"), Some("1.2.0"), false),+ (Some("0.1.6"), Some("1.2.5"), false),+ (Some("0.1.6"), Some("1.4.0"), false),+ (Some("0.1.7-rc.2"), Some("1.4.0"), false),+ (Some("0.1.7-rc.2"), Some("1.2.0"), true),+ (Some("0.2.0"), Some("1.4.0"), true),+ (Some("0.2.0"), Some("1.2.0"), true),+ (Some("0.2.0"), Some("2.0.0"), false),+ (Some("0.2.0"), Some("1.0.0"), false),+ (Some("0.1.6"), None, false),+ (Some("0.1.6"), Some("invalid"), false),+ (None, Some("1.2.0"), false),+ (Some("invalid"), Some("1.2.0"), false),+ ] {+ let mut entry = load_presets_for_test()+ .into_iter()+ .find(|p| p.id == "dshmarket")+ .expect("dshmarket");+ entry.version = Some(declared.clone());+ assert_eq!(+ entry.retire_on(core, installed),+ retire,+ "core={core:?} installed={installed:?}"+ );+ }}#[test]@@ -657,38 +701,49 @@ mod tests {for (field, expected) in [("", None),(r#", "version": null"#, None),- (r#", "version": "1.58.0""#, Some("1.58.0")),- (r#", "version": "invalid""#, Some("invalid")),+ (+ r#", "version": "latest""#,+ Some(PluginVersion::Declared("latest".into())),+ ),+ (+ r#", "version": "1.2.3""#,+ Some(PluginVersion::Declared("1.2.3".into())),+ ),+ (+ r#", "version": [{"version": "^0.19.1", "dsh": "^0.1.5-rc.1"}]"#,+ Some(matrix(&[("^0.19.1", "^0.1.5-rc.1")])),+ ),] {let raw = format!(- r#"[{{"id":"dshmarket","spec":"dshmarket","name":"Market","description":"","repoUrl":""{field}}}]"#+ r#"{{"plugins":{{"preset":[{{"id":"dshmarket","spec":"dshmarket","name":"Market","description":"","repo":"u"{field}}}]}}}}"#);- let plugins = parse_plugins(&raw, false).expect("preset manifest should parse");+ let plugins = plugin_infos_from(&raw, false);assert_eq!(plugins.len(), 1);- assert_eq!(plugins[0].version.as_deref(), expected);+ assert_eq!(plugins[0].version, expected);assert_eq!(plugins[0].spec, "dshmarket");}}- /// 内置条目默认不声明上限、对任何核心版本都兼容;通用上限机制仍在生效——- /// 显式声明上限后依旧走 unsupported 判定,只是当前没有任何内置条目使用它。+ /// 内置条目默认不声明版本矩阵、对任何核心版本都兼容;通用矩阵机制仍在生效——+ /// 显式声明后依旧走 unsupported 判定,只是当前没有任何内置条目使用它。#[test]fn internal_manifest_defaults_to_compatible_and_honours_declared_ceiling() {- let internal = load_manifest_for_test(INTERNAL_PLUGINS_FILE, true);+ let internal = load_internal_for_test();assert!(!internal.is_empty());assert!(internal.iter()- .all(|p| p.dsh_supported_version.is_none() && !p.unsupported_on(Some("9.9.9"))),- "no internal entry declares a core ceiling, so every one stays compatible"+ .all(|p| p.version.is_none() && !p.unsupported_on(Some("9.9.9"))),+ "no internal entry declares a core matrix, so every one stays compatible");let mut capped = internal[0].clone();- capped.dsh_supported_version = Some("0.1.7-alpha.0".into());+ capped.version = Some(matrix(&[("^1.0.0", "^0.1.5-rc.1")]));assert!(!capped.unsupported_on(Some("0.1.5-rc.1")));- assert!(!capped.unsupported_on(Some("0.1.7-alpha.0")));- assert!(capped.unsupported_on(Some("0.1.7-alpha.1")));+ assert!(!capped.unsupported_on(Some("0.1.6")));+ assert!(capped.unsupported_on(Some("0.1.7-rc.1")));+ assert!(capped.unsupported_on(Some("0.2.0")));}#[test]@@ -704,57 +759,60 @@ mod tests {#[test]fn internal_manifest_marks_all_entries_internal() {- let plugins = load_manifest_for_test(INTERNAL_PLUGINS_FILE, true);+ let plugins = load_internal_for_test();assert!(!plugins.is_empty());assert!(plugins.iter().all(|plugin| plugin.internal));assert!(plugins.iter().any(|plugin| plugin.id == "dsh-tauri"));assert!(!load_presets_for_test().iter().any(|plugin| plugin.internal));}+ /// 回归:Windows 安装包(NSIS/MSI)与开发产物把资源按 `resources/**` 前缀落盘到+ /// `{resource_dir}/resources/` 子目录,而扁平布局(资源直接放 exe 同级)同样合法;+ /// 两种布局下的清单都必须能被读取解析(定位顺序见 `config::manifest::resource_root`)。#[test]- fn preset_discovery_finds_nested_resources_dir() {- // 回归:Windows 安装包(NSIS/MSI)与开发产物把资源按 `resources/**` 前缀- // 落盘到 `{resource_dir}/resources/` 子目录,此前只探测 exe 同级导致- // 发布版预装页恒为空清单。- let dir = std::env::temp_dir().join(format!("dsh-preset-layout-{}", std::process::id()));+ fn manifest_reads_in_both_flat_and_nested_resource_layouts() {+ let dir = std::env::temp_dir().join(format!("dsh-manifest-layout-{}", std::process::id()));+ std::fs::remove_dir_all(&dir).ok();let nested = dir.join("resources");std::fs::create_dir_all(&nested).expect("create temp resources dir");- std::fs::write(- nested.join(PRESET_PLUGINS_FILE),- r#"[{"id":"x","spec":"y","name":"X","description":"","repoUrl":"u"}]"#,- )- .expect("write temp preset file");-- let found = find_manifest_in_resource_root(&dir, PRESET_PLUGINS_FILE)- .expect("nested resources layout should be found");- assert_eq!(found, nested.join(PRESET_PLUGINS_FILE));+ let body = r#"{"plugins":{"preset":[{"id":"x","spec":"y","name":"X","description":"","repo":"u"}]}}"#;- std::fs::remove_dir_all(&dir).ok();- }-- #[test]- fn preset_discovery_prefers_flat_layout() {- // 扁平布局(资源直接放在 exe 同级)仍应优先命中。- let dir = std::env::temp_dir().join(format!("dsh-preset-flat-{}", std::process::id()));- std::fs::create_dir_all(&dir).expect("create temp dir");- std::fs::write(- dir.join(PRESET_PLUGINS_FILE),- r#"[{"id":"x","spec":"y","name":"X","description":"","repoUrl":"u"}]"#,- )- .expect("write temp preset file");+ std::fs::write(nested.join(crate::config::manifest::MANIFEST_FILE), body)+ .expect("write nested manifest");+ assert_eq!(+ crate::config::manifest::read_at(&nested.join(crate::config::manifest::MANIFEST_FILE))+ .expect("nested layout manifest should parse")+ .plugins+ .preset+ .len(),+ 1+ );- let found = find_manifest_in_resource_root(&dir, PRESET_PLUGINS_FILE)- .expect("flat layout should be found");- assert_eq!(found, dir.join(PRESET_PLUGINS_FILE));+ std::fs::write(dir.join(crate::config::manifest::MANIFEST_FILE), body)+ .expect("write flat manifest");+ assert_eq!(+ crate::config::manifest::read_at(&dir.join(crate::config::manifest::MANIFEST_FILE))+ .expect("flat layout manifest should parse")+ .plugins+ .preset+ .len(),+ 1+ );std::fs::remove_dir_all(&dir).ok();}#[test]fn deprecated_ids_parse_into_set() {- // 字符串数组解析为 id 集合;重复 id 去重- let raw = r#"["dsh-a","dsh-b","dsh-a"]"#;- let ids = parse_deprecated_ids(raw).expect("deprecated manifest should parse");+ // 弃用名单解析为 id 集合;重复 id 去重+ let ids: HashSet<String> = crate::config::manifest::parse(+ r#"{"plugins":{"depercated":["dsh-a","dsh-b","dsh-a"]}}"#,+ )+ .expect("deprecated manifest should parse")+ .plugins+ .deprecated+ .into_iter()+ .collect();assert_eq!(ids.len(), 2);assert!(ids.contains("dsh-a"));assert!(ids.contains("dsh-b"));@@ -762,56 +820,44 @@ mod tests {#[test]fn deprecated_ids_reject_non_string_entries() {- // 非法条目(非字符串)整体解析失败,调用方回落为空集合- let raw = r#"[42]"#;- assert!(parse_deprecated_ids(raw).is_err());- let raw = r#"{"id":"dsh-x"}"#;- assert!(parse_deprecated_ids(raw).is_err());+ // 非法条目(非字符串 / 非数组)整体解析失败,调用方回落为空集合+ assert!(crate::config::manifest::parse(r#"{"plugins":{"depercated":[42]}}"#).is_err());+ assert!(+ crate::config::manifest::parse(r#"{"plugins":{"depercated":{"id":"dsh-x"}}}"#).is_err()+ );}#[test]fn deprecated_manifest_lists_session_context_menu() {- // 随包分发的弃用清单应登记 dsh-session-context-menu(已被内部插件替代)- let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))- .join("resources")- .join(DEPRECATED_PLUGINS_FILE);- let raw = std::fs::read_to_string(path).expect("deprecated manifest should exist");- let ids = parse_deprecated_ids(&raw).expect("deprecated manifest should be valid JSON");- assert!(ids.contains("dsh-session-context-menu"));+ // 随包分发的弃用名单应登记 dsh-session-context-menu(已被内部插件替代)+ assert!(shipped_deprecated_ids().contains("dsh-session-context-menu"));}#[test]fn deprecated_manifest_lists_absorbed_panel() {- // 0.15.0 把 dsh-tauri-panel 并入核心,并从 internal-plugins.json 移除了条目,- // 升级用户只能靠弃用清单兜底卸载(残留 bundle 会导致无法进入软件页面)。- let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))- .join("resources")- .join(DEPRECATED_PLUGINS_FILE);- let raw = std::fs::read_to_string(path).expect("deprecated manifest should exist");- let ids = parse_deprecated_ids(&raw).expect("deprecated manifest should be valid JSON");- assert!(ids.contains("dsh-tauri-panel"));+ // 0.15.0 把 dsh-tauri-panel 并入核心,并从内置清单移除了条目,+ // 升级用户只能靠弃用名单兜底卸载(残留 bundle 会导致无法进入软件页面)。+ assert!(shipped_deprecated_ids().contains("dsh-tauri-panel"));}#[test]fn deprecated_manifest_lists_absorbed_connection() {- // dsh-tauri-connection 的载体鉴权适配已并入 dsh-tauri 核心插件,并从- // internal-plugins.json 移除了条目:升级用户的 link: 依赖与 bundle 引用- // 只能靠弃用清单兜底卸载(残留 bundle 会导致无法进入软件页面)。- let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))- .join("resources")- .join(DEPRECATED_PLUGINS_FILE);- let raw = std::fs::read_to_string(path).expect("deprecated manifest should exist");- let ids = parse_deprecated_ids(&raw).expect("deprecated manifest should be valid JSON");- assert!(ids.contains("dsh-tauri-connection"));+ // dsh-tauri-connection 的载体鉴权适配已并入 dsh-tauri 核心插件,并从内置+ // 清单移除了条目:升级用户的 link: 依赖与 bundle 引用只能靠弃用名单兜底+ // 卸载(残留 bundle 会导致无法进入软件页面)。+ assert!(shipped_deprecated_ids().contains("dsh-tauri-connection"));}#[test]fn manifest_source_overrides_internal_field() {- let raw =- r#"[{"id":"x","spec":"y","internal":true,"name":"X","description":"","repoUrl":"u"}]"#;- let preset = parse_plugins(raw, false).expect("preset manifest should parse");+ // 条目里的 `internal` 字段不参与判定:内部属性只由所在清单节决定+ let raw = r#"{"plugins":{+ "preset":[{"id":"x","spec":"y","internal":true,"name":"X","description":"","repo":"u"}],+ "built-in":[{"id":"x","spec":"y","internal":false,"name":"X","description":"","repo":"u"}]+ }}"#;+ let preset = plugin_infos_from(raw, false);assert!(!preset[0].internal);- let internal = parse_plugins(raw, true).expect("internal manifest should parse");+ let internal = plugin_infos_from(raw, true);assert!(internal[0].internal);}@@ -1132,7 +1178,6 @@ mod tests {fix: false,default_checked: false,default_unchecked: false,- dsh_supported_version: None,version: None,win_only: false,},@@ -1148,7 +1193,6 @@ mod tests {fix: false,default_checked: false,default_unchecked: false,- dsh_supported_version: None,version: None,win_only: false,},@@ -1164,16 +1208,17 @@ mod tests {std::fs::remove_dir_all(&root).ok();}- /// dev 候选覆盖静态条目时必须沿用清单声明的支持上限:退役判定读的是发布侧的+ /// dev 候选覆盖静态条目时必须沿用清单声明的版本矩阵:退役判定读的是发布侧的/// 核心计划,与当前 checkout 是否存在该包源码无关。#[cfg(debug_assertions)]#[test]- fn dev_merge_carries_static_core_and_automatic_removal_ceilings() {+ fn dev_merge_carries_static_version_declaration() {let root = temp_dev_root("merge-cap");write_dev_manifest(&root.join("dsh-tauri-running-changes"),"dsh-tauri-running-changes",);+ let declared = matrix(&[("^1.2.3", "^0.1.7-alpha.0")]);let static_internal = vec![PreinstallPluginInfo {id: "dsh-tauri-running-changes".into(),spec: "dsh-tauri-running-changes".into(),@@ -1186,8 +1231,7 @@ mod tests {fix: false,default_checked: false,default_unchecked: false,- dsh_supported_version: Some("0.1.7-alpha.0".into()),- version: Some("1.2.3".into()),+ version: Some(declared.clone()),win_only: false,}];@@ -1196,15 +1240,14 @@ mod tests {.iter().find(|p| p.id == "dsh-tauri-running-changes").expect("merged entry must exist");- assert_eq!(- renamed.dsh_supported_version.as_deref(),- Some("0.1.7-alpha.0")- );- assert_eq!(renamed.version.as_deref(), Some("1.2.3"));+ assert_eq!(renamed.version.as_ref(), Some(&declared));assert_eq!(renamed.spec, "dsh-tauri-running-changes");assert_eq!(renamed.description, "desc");- assert!(renamed.unsupported_on(Some("0.1.7-alpha.1")));- assert!(!renamed.unsupported_on(Some("0.1.6-alpha.2")));+ assert!(!renamed.unsupported_on(Some("0.1.7-alpha.0")));+ assert!(renamed.unsupported_on(Some("0.2.0")));+ assert!(!renamed.retire_on(Some("0.1.7-alpha.0"), Some("1.2.3")));+ assert!(renamed.retire_on(Some("0.2.0"), Some("1.2.3")));+ assert!(!renamed.retire_on(Some("0.2.0"), Some("2.0.0")));// dev 覆盖语义不变:条目仍来自仓库源码assert!(renamed.internal);std::fs::remove_dir_all(&root).ok();diff --git a/src-tauri/src/service/plugin/safe.rs b/src-tauri/src/service/plugin/safe.rsindex fb801dec..cde3be98 100644--- a/src-tauri/src/service/plugin/safe.rs+++ b/src-tauri/src/service/plugin/safe.rs@@ -44,7 +44,7 @@ fn user_plugin_names(installed: &HashSet<String>, builtin: &HashSet<String>) ->/// 内置插件包名集合(以实际安装包名为准,见 [`installed_name`])。///-/// 清单来自随包分发的 `resources/internal-plugins.json`,debug 下并入仓库根+/// 清单来自随包分发的 `resources/manifest.jsonc` 的 `plugins.built-in`,debug 下并入仓库根/// `packages/*` 发现的内置插件;内部属性由清单来源决定(见 `preset::load_presets`),/// 社区预设与内置插件在此处天然分流。fn builtin_plugin_names(app_handle: &AppHandle) -> HashSet<String> {@@ -109,21 +109,20 @@ pub(crate) fn purge_user_plugins_in_safe_profile(app_handle: &AppHandle) -> Resu#[cfg(test)]mod tests {- use super::super::preset::PreinstallPluginInfo;use super::*;+ use crate::config::manifest;use std::path::PathBuf;- /// 读取随包清单里的实际安装包名(与 [`builtin_plugin_names`] 同一套解析,- /// 但不依赖 AppHandle:清单文件位于源码 `src-tauri/resources/`)。- fn manifest_package_names(file_name: &str) -> Vec<String> {- let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))- .join("resources")- .join(file_name);- let raw = std::fs::read_to_string(path).expect("plugin manifest should exist");- serde_json::from_str::<Vec<PreinstallPluginInfo>>(&raw)- .expect("plugin manifest should be valid JSON")+ /// 读取随包清单里的实际安装包名(与生产链路同一套解析,但不依赖 AppHandle:+ /// 清单文件位于源码 `src-tauri/resources/`)。+ fn manifest_package_names(+ section: fn(&manifest::Plugins) -> &[manifest::PluginEntry],+ ) -> Vec<String> {+ let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/manifest.jsonc");+ let manifest = manifest::read_at(&path).expect("resource manifest should be valid");+ section(&manifest.plugins).iter()- .map(|plugin| installed_name(plugin).to_string())+ .map(|entry| entry.package.clone().unwrap_or_else(|| entry.id.clone())).collect()}@@ -170,8 +169,8 @@ mod tests {fn shipped_internal_manifest_is_protected() {// 随包内置插件清单(dsh-tauri 等)必须全部落在保留集里;社区预设// (dshmarket 等)属于用户插件,进入清除清单。- let builtin = manifest_package_names("internal-plugins.json");- let presets = manifest_package_names("preset-plugins.json");+ let builtin = manifest_package_names(|plugins| &plugins.built_in);+ let presets = manifest_package_names(|plugins| &plugins.preset);assert!(builtin.iter().any(|name| name == "dsh-tauri"));assert!(presets.iter().any(|name| name == "dshmarket"));diff --git a/src-tauri/src/service/plugin/verify.rs b/src-tauri/src/service/plugin/verify.rsindex 021d7dbd..9367e15e 100644--- a/src-tauri/src/service/plugin/verify.rs+++ b/src-tauri/src/service/plugin/verify.rs@@ -337,7 +337,6 @@ mod tests {fix: false,default_checked: false,default_unchecked: false,- dsh_supported_version: None,version: None,win_only: false,internal: false,diff --git a/src-tauri/src/service/plugin/watch.rs b/src-tauri/src/service/plugin/watch.rsindex 1dc61aa2..a95b0c09 100644--- a/src-tauri/src/service/plugin/watch.rs+++ b/src-tauri/src/service/plugin/watch.rs@@ -407,7 +407,6 @@ mod tests {fix: false,default_checked: false,default_unchecked: false,- dsh_supported_version: None,version: None,win_only: false,package: None,@@ -494,7 +493,6 @@ mod tests {fix: false,default_checked: false,default_unchecked: false,- dsh_supported_version: None,version: None,win_only: false,package: None,diff --git a/src-tauri/src/service/workflow/install.rs b/src-tauri/src/service/workflow/install.rsindex 45e1d4ae..2de83140 100644--- a/src-tauri/src/service/workflow/install.rs+++ b/src-tauri/src/service/workflow/install.rs@@ -47,14 +47,8 @@ pub async fn install(.get_webview_window("main").ok_or("Failed to get main window")?;log::debug!("Main window obtained");- // 仅 Windows 会继续 push MinGit 任务(见下方 `#[cfg(windows)]`),- // 异平台的 `mut` 因此多余,按平台放行。- #[cfg_attr(not(windows), allow(unused_mut))]- let mut tasks: Vec<Box<dyn download::Installable>> = vec![- Box::new(download::Nodejs),- Box::new(download::Dsh),- Box::new(download::Pnpm),- ];+ // 依赖任务清单的唯一构造点在下载层,安装流程与映射回写共用同一组任务。+ let tasks = download::tasks();// 必须在下载前解析 release 元数据:下载地址和摘要必须属于同一固定 tag。// 若先下载 latest、再因 API 限流从 Atom/HTML 解析 tag,latest 在两次请求间// 发生切换就会把另一份资产拿来匹配摘要,最终触发 INTEGRITY_CHECK_FAILED。@@ -92,8 +86,6 @@ pub async fn install(}// Windows Sandbox 等空白环境没有 Git;仅 Windows 加入第 4 项,若系统 Git// 可真实执行则 Installable 会跳过,不重复下载也不修改系统 PATH。- #[cfg(windows)]- tasks.push(Box::new(download::Git));// 每项均有下载/解压两个阶段,按实际平台任务数计算,避免进度提前到 100%。let mut tracker = download::ProgressTracker::new(&window, tasks.len() * 2);log::info!("Task list created, {} tasks total", tasks.len());@@ -132,6 +124,8 @@ pub async fn install("Task {} already installed and up to date, skipping",index + 1);+ // 已就绪也要落映射:系统环境满足记 `null`,托管版记安装根。+ task.record_mapping(app_handle);tracker.skip_phases(2);continue;}@@ -212,6 +206,8 @@ pub async fn install(log::debug!("Installation path: {:?}", dest);download::ensure_extract(&tracker, name, buffer, dest).await?;log::info!("Extraction completed");+ // 解压落盘即建立该依赖的路径映射(新用户 / 缺少内核的场景)。+ task.record_mapping(app_handle);tracker.end_phase();// 记录本次安装对应的 release tag 与 commit,供下次启动比对diff --git a/src-tauri/src/service/workflow/launch.rs b/src-tauri/src/service/workflow/launch.rsindex 49aa56cf..1b164999 100644--- a/src-tauri/src/service/workflow/launch.rs+++ b/src-tauri/src/service/workflow/launch.rs@@ -428,7 +428,7 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {if let Err(e) = crate::service::plugin::ensure_profile_npmrc(&app_handle) {log::warn!("ensure profile .npmrc failed: {e}");}- // 弃用插件自动卸载:`deprecated-plugins.json` 登记的社区插件若已安装,启动时+ // 弃用插件自动卸载:`manifest.jsonc` 的 `plugins.depercated` 登记的社区插件若已安装,启动时// 自动移除(避免残留插件继续在 profile 里加载、甚至导致启动失败)。最佳努力:// 失败只告警,不阻断启动。if let Err(e) = crate::service::plugin::uninstall_deprecated_plugins(&app_handle).await {diff --git a/src/pet/hooks/use-pet-source.ts b/src/pet/hooks/use-pet-source.tsindex 4c5b951f..0097dda2 100644--- a/src/pet/hooks/use-pet-source.ts+++ b/src/pet/hooks/use-pet-source.ts@@ -6,7 +6,7 @@ import { PET_CODEX_ASPECT, PET_DSH_ASPECT } from '../constants'import { reportPetIssue } from '../utils/log'/**- * `resources/preset-pets.json` 的条目(Rust `list_preset_pets` 原样返回)。+ * `resources/manifest.jsonc` 的 `pets.built-in`(Rust `list_preset_pets` 原样返回)。** 条目字段即 `dsh-pet-component` 的 `<Pet>` props:预设宠物不再下载/安装到本地,* 组件直连条目里的远端素材地址播放。diff --git a/src/store/modules/harness/store.ts b/src/store/modules/harness/store.tsindex 6228ad09..d81362e6 100644--- a/src/store/modules/harness/store.ts+++ b/src/store/modules/harness/store.ts@@ -574,9 +574,9 @@ export const harness = defineStore({}throw startupError('plugin-install', String(err), 'failed')}- // 预装插件引导:首次安装、老版本升级(无指纹基线)或 preset-plugins.json+ // 预装插件引导:首次安装、老版本升级(无指纹基线)或清单 plugins 节// 内容变更(社区新增推荐插件)时重新进入预设流程,装完/跳过后才拉起服务。- // preset-plugins.json 随安装包发布、每次安装被强制覆盖,旧文件不可比对,+ // 清单随安装包发布、每次安装被强制覆盖,旧内容不可比对,// 由 Rust 侧记录内容指纹到 app-data(.store.dat),启动时比对是否有变更。if (await invoke<boolean>('get_preinstall_pending')) {this.status = 'preinstall'diff --git a/src/store/modules/preinstall/store.ts b/src/store/modules/preinstall/store.tsindex f572d8ce..424f0673 100644--- a/src/store/modules/preinstall/store.ts+++ b/src/store/modules/preinstall/store.ts@@ -12,7 +12,7 @@ import { harnessUpdater } from '../harness-updater'const LOG_LIMIT = 200/**- * 预装插件引导模块:首次安装、老版本升级或 preset-plugins.json 内容变更后,+ * 预装插件引导模块:首次安装、老版本升级或资源清单 plugins 节内容变更后,* 展示推荐插件列表(可增选/减选),确认或跳过后继续启动服务。** 与 harness 模块的分工:本模块只负责「引导页的选择与安装」,diff --git a/src/types/core.ts b/src/types/core.tsindex cc3566d0..45480533 100644--- a/src/types/core.ts+++ b/src/types/core.ts@@ -20,7 +20,7 @@ export interface HarnessCore {active: boolean/** 是否预览版(GitHub Pre-release label 或 tag 命名判定):预览版不参与更新提示,仅列表展示 */preview: boolean- /** 是否高于 resources/version-recommend.json 中的推荐版本 */+ /** 是否高于资源清单 engines.dsh.recommend 中的推荐版本 */aboveRecommended: boolean/** 本地存在但 pkg 仓库已不再提供的历史槽位 */orphaned: booleandiff --git a/src/ui/config/core.tsx b/src/ui/config/core.tsxindex e6b7ba2f..37f34912 100644--- a/src/ui/config/core.tsx+++ b/src/ui/config/core.tsx@@ -489,7 +489,7 @@ function displayVersion(version: HarnessCore): string {/*** 本地核心是否低于最低支持基线。判据与「不兼容版本」分组完全一致(同一基线,* `isUnsupportedCore`),低于基线时随包内置插件无法加载(issue #596),桌面端自动- * 改用预打包核心。不可与推荐核心版本(`version-recommend.json`)混用——后者只用于+ * 改用预打包核心。不可与推荐核心版本(`engines.dsh.recommend`)混用——后者只用于* 更新提示,拿它当基线会把「高于基线、低于推荐版本」的可用本地核心误判为不兼容* (推荐版本为 0.1.7-alpha.1 时,0.1.5-rc.3 就是这么被挡下的)。*/diff --git a/src/utils/core-version.ts b/src/utils/core-version.tsindex cdf02a56..38ac9caf 100644--- a/src/utils/core-version.ts+++ b/src/utils/core-version.ts@@ -35,7 +35,7 @@ export function isCoreBreakingVersion(version: string): boolean {* 最低支持的核心版本(与 Rust `MIN_SUPPORTED_CORE_VERSION` 对齐)。低于它的核心缺少* 内置插件依赖的平台种子词,随包插件必然加载失败并把应用卡在启动阶段(issue #596)。*- * 这是兼容性的唯一基线:它低于推荐核心版本(`version-recommend.json`,仅用于更新+ * 这是兼容性的唯一基线:它低于推荐核心版本(`manifest.jsonc` 的 `engines.dsh.recommend`,仅用于更新* 提示),两者不可混用——拿推荐版本当基线会把「高于基线、低于推荐版本」的可用核心* 误判为不兼容(推荐版本为 0.1.7-alpha.1 时,0.1.5-rc.3 就是这么被挡下的)。*/diff --git a/test/core-local-unsupported.test.ts b/test/core-local-unsupported.test.tsindex e5649ec2..42137a43 100644--- a/test/core-local-unsupported.test.ts+++ b/test/core-local-unsupported.test.ts@@ -3,12 +3,15 @@ import { describe, expect, it } from 'vitest'import { compareVersions, isCoreUnsupported, MIN_SUPPORTED_CORE_VERSION } from '@/utils/core-version'const CORE_PANEL = new URL('../src/ui/config/core.tsx', import.meta.url)-const RECOMMEND_MANIFEST = new URL('../src-tauri/resources/version-recommend.json', import.meta.url)+const RESOURCE_MANIFEST = new URL('../src-tauri/resources/manifest.jsonc', import.meta.url)/** 随包推荐核心版本(前端核心面板的「更新」提示基线)。 */function recommendedVersion(): string {- const raw = JSON.parse(readFileSync(RECOMMEND_MANIFEST, 'utf8')) as { dsh: string }- return raw.dsh+ // 资源清单是 JSONC(允许行注释):解析前先剥掉行注释。+ const raw = JSON.parse(+ readFileSync(RESOURCE_MANIFEST, 'utf8').replace(/^\s*\/\/.*$/gm, ''),+ ) as { engines: { dsh: { recommend: string } } }+ return raw.engines.dsh.recommend}/** `isUnsupportedLocal` 的函数体源码(用于锁定它不再复用推荐版本当基线)。 */@@ -22,7 +25,8 @@ function localPredicateSource(): string {/*** 兼容性只由**最低支持基线**(0.1.5-rc.1)决定,与推荐核心版本无关。*- * 回归背景:本地核心的判定曾复用「推荐核心版本」(`version-recommend.json`,误报发生时+ * 回归背景:本地核心的判定曾复用「推荐核心版本」(`manifest.jsonc` 的+ * `engines.dsh.recommend`,误报发生时* 为 0.1.7-alpha.1)当基线,于是 0.1.5-rc.3 这类**高于最低支持基线**的本地核心被误判为* 「不兼容」:行内挂红标、激活被拒、提示文案还引用推荐版本号。最低支持基线独立于推荐* 版本(issue #596),两者不可混用。diff --git a/test/core-version.test.ts b/test/core-version.test.tsindex 00399613..0029b371 100644--- a/test/core-version.test.ts+++ b/test/core-version.test.ts@@ -9,7 +9,7 @@ import { isCoreUnsupported, MIN_SUPPORTED_CORE_VERSION } from '@/utils/core-vers* 后端据此回退预打包核心,前端核心面板据此标注「不兼容」并拒绝激活;这里锁住两侧* 共用的版本判定:低于基线为 true,等于/高于为 false,不可解析不误判。*- * 兼容性只看最低支持基线,与推荐核心版本(`version-recommend.json`)无关——推荐版本+ * 兼容性只看最低支持基线,与推荐核心版本(`manifest.jsonc` 的 `engines.dsh.recommend`)无关——推荐版本* 高于基线、仅用于更新提示。*/describe('isCoreUnsupported', () => {diff --git a/test/preinstall-uncheck.test.ts b/test/preinstall-uncheck.test.tsindex 9133961e..2ddfe438 100644--- a/test/preinstall-uncheck.test.ts+++ b/test/preinstall-uncheck.test.ts@@ -2,6 +2,12 @@ import type { Event } from '@tauri-apps/api/event'import { readFileSync } from 'node:fs'import { beforeEach, describe, expect, it, vi } from 'vitest'+/** 资源清单是 JSONC(允许行注释):解析前先剥掉行注释。 */+function readManifest(): { plugins: { preset: Array<{ id: string, recommended?: boolean, checked?: boolean }> } } {+ const raw = readFileSync(new URL('../src-tauri/resources/manifest.jsonc', import.meta.url), 'utf8')+ return JSON.parse(raw.replace(/^\s*\/\/.*$/gm, ''))+}+// ── Suite A — i18n keys exist (source assertion on JSON) ─────────────────────describe('preinstall can-uncheck hint i18n keys', () => {it('provides preinstall.can_uncheck_hint in en-US', () => {@@ -40,9 +46,9 @@ describe('preinstallSetup primary button morph', () => {})})-// ── Suite B2 — defaultUnchecked suppresses preselection (behavior) ────────────-// 推荐项仍显示「推荐」chip,但声明 defaultUnchecked 时首次引导不预选。-describe('defaultUnchecked suppresses first-run preselection', () => {+// ── Suite B2 — 未预选声明抑制首次预选(behavior) ──────────────────────────────+// 推荐项仍显示「推荐」chip,但清单声明 `checked: false` 时首次引导不预选。+describe('unchecked preset suppresses first-run preselection', () => {it('is honored by initialCheckedSet and keeps the recommended chip independent', () => {const source = readFileSync(new URL('../src/layout/components/setup-preinstall.tsx', import.meta.url), 'utf8')expect(source).toContain('p.defaultUnchecked')@@ -50,14 +56,12 @@ describe('defaultUnchecked suppresses first-run preselection', () => {expect(source.indexOf('p.defaultUnchecked')).toBeLessThan(source.indexOf('p.recommended || p.fix'))})- it('declares defaultUnchecked for the DSH IM preset entry', () => {- const presets = JSON.parse(- readFileSync(new URL('../src-tauri/resources/preset-plugins.json', import.meta.url), 'utf8'),- ) as Array<{ id: string, recommended?: boolean, defaultUnchecked?: boolean }>- const im = presets.find(p => p.id === '@xmanrui/dsh-im')+ it('declares the DSH IM preset as recommended but not pre-checked', () => {+ const im = readManifest().plugins.preset.find(p => p.id === '@xmanrui/dsh-im')expect(im).toBeDefined()- expect(im?.defaultUnchecked).toBe(true)expect(im?.recommended).toBe(true)+ // 资源清单是唯一真值:Rust 侧据此派生 defaultUnchecked(checked === false)+ expect(im?.checked).toBe(false)})})