Explorar o código

feat: 优化打包方式、启动速度

07akioni hai 2 semanas
pai
achega
8e4d3bab9f
Modificáronse 57 ficheiros con 1948 adicións e 2090 borrados
  1. 2 2
      .agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.i18n.yaml
  2. 5 7
      .agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md
  3. 5 7
      .agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md
  4. 6 0
      .agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.i18n.yaml
  5. 51 0
      .agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.md
  6. 51 0
      .agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md
  7. 6 0
      .agents/notes/proposed/feature/2026-09-08-desktop-uninstall-preserve-dsh-home.i18n.yaml
  8. 95 0
      .agents/notes/proposed/feature/2026-09-08-desktop-uninstall-preserve-dsh-home.md
  9. 95 0
      .agents/notes/proposed/feature/2026-09-08-desktop-uninstall-preserve-dsh-home.zh.md
  10. 19 15
      apps/desktop-host/src/index.ts
  11. 2 2
      apps/desktop/README.i18n.yaml
  12. 19 29
      apps/desktop/README.md
  13. 19 29
      apps/desktop/README.zh.md
  14. 3 1
      apps/desktop/electron-builder.config.d.mts
  15. 15 2
      apps/desktop/electron-builder.config.mjs
  16. 2 3
      apps/desktop/package.json
  17. 6 0
      apps/desktop/renderer/plugin-manager.html
  18. 17 2
      apps/desktop/renderer/plugin-manager.js
  19. 2 2
      apps/desktop/scripts/desktop-build-paths.d.mts
  20. 3 3
      apps/desktop/scripts/desktop-build-paths.mjs
  21. 43 0
      apps/desktop/scripts/macos-runtime.ts
  22. 0 413
      apps/desktop/scripts/macos-seed-store.ts
  23. 2 2
      apps/desktop/scripts/package-target.ts
  24. 150 0
      apps/desktop/scripts/prepare-dsh.ts
  25. 0 200
      apps/desktop/scripts/prepare-seed.ts
  26. 58 0
      apps/desktop/scripts/smoke-runtime.ts
  27. 6 6
      apps/desktop/scripts/verify-macos-signature.d.mts
  28. 11 11
      apps/desktop/scripts/verify-macos-signature.mjs
  29. 1 1
      apps/desktop/src/core-package-set.ts
  30. 9 4
      apps/desktop/src/host-process.ts
  31. 10 0
      apps/desktop/src/ipc.ts
  32. 14 0
      apps/desktop/src/locale.ts
  33. 48 17
      apps/desktop/src/main.ts
  34. 6 0
      apps/desktop/src/preload.ts
  35. 254 0
      apps/desktop/src/profile-packages.ts
  36. 155 189
      apps/desktop/src/project-manager.ts
  37. 2 2
      apps/desktop/src/release.ts
  38. 180 0
      apps/desktop/src/runtime-tree.ts
  39. 0 271
      apps/desktop/src/seed-store.ts
  40. 1 1
      apps/desktop/src/update-coordinator.ts
  41. 3 3
      apps/desktop/tests/desktop-build-paths.spec.ts
  42. 28 7
      apps/desktop/tests/host-process.spec.ts
  43. 48 0
      apps/desktop/tests/macos-runtime.spec.ts
  44. 0 245
      apps/desktop/tests/macos-seed-store.spec.ts
  45. 41 8
      apps/desktop/tests/macos-signature.spec.ts
  46. 1 1
      apps/desktop/tests/package-target.spec.ts
  47. 33 0
      apps/desktop/tests/plugin-manager.spec.ts
  48. 72 0
      apps/desktop/tests/plugin-pnpm.spec.ts
  49. 81 0
      apps/desktop/tests/profile-packages.spec.ts
  50. 171 346
      apps/desktop/tests/project-manager.spec.ts
  51. 42 0
      apps/desktop/tests/runtime-fixture.ts
  52. 46 0
      apps/desktop/tests/runtime-tree.spec.ts
  53. 0 167
      apps/desktop/tests/seed-store.spec.ts
  54. 2 2
      docs/architecture.i18n.yaml
  55. 2 2
      docs/architecture.md
  56. 2 2
      docs/architecture.zh.md
  57. 3 86
      pnpm-lock.yaml

+ 2 - 2
.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.i18n.yaml

@@ -2,5 +2,5 @@
 # side as of the last confirmed-consistent state. Both languages carry equal authority;
 # after editing either side, bring the other along and re-record with:
 #   pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md
-2026-08-25-electron-desktop-packaging-and-updates.md: 6d22777c8913911dbb1d89c09de9e891636873c8
-2026-08-25-electron-desktop-packaging-and-updates.zh.md: 5108492ba6f029847735f570aa77c2cb505f981c
+2026-08-25-electron-desktop-packaging-and-updates.md: fea2c419d73e4eff66de08483733cbc336b6f9af
+2026-08-25-electron-desktop-packaging-and-updates.zh.md: 88e2875cd35909c0111926377df83c9fe21841dc

A diferenza do arquivo foi suprimida porque é demasiado grande
+ 5 - 7
.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md


A diferenza do arquivo foi suprimida porque é demasiado grande
+ 5 - 7
.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md


+ 6 - 0
.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.i18n.yaml

@@ -0,0 +1,6 @@
+# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
+# side as of the last confirmed-consistent state. Both languages carry equal authority;
+# after editing either side, bring the other along and re-record with:
+#   pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.md
+2026-09-08-desktop-bundled-runtime-and-external-plugins.md: 8278107fb3c37aca909541886d9379a1bfd64bac
+2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md: b29eb1e6cbe19d4a5b4ea23a5d6159cfd3973bcd

+ 51 - 0
.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.md

@@ -0,0 +1,51 @@
+# Agent Note: Bundle the Desktop runtime and retain external plugins
+
+Status: implemented
+
+English | [中文](2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md)
+
+## Problem
+
+Installing the core dependency graph during Desktop initialization repeats work already done by the release builder. An offline store eliminates downloads but retains extraction, package-manager startup, and installation costs. Users need the application to start with its production packages present while retaining ordinary npm plugin installation and plugin state across application upgrades.
+
+Separate package directories can load duplicate Cordis or service modules. Retaining plugin files also does not prove compatibility with a new host API or Node runtime.
+
+## Decision
+
+[Runtime preparation](../../../../apps/desktop/scripts/prepare-dsh.ts) materializes the production graph once at build time and ships it through `extraResources/dsh`. The Electron shell stays in ASAR. A bundled upstream Node process runs the private Desktop Host from resources and loads enabled plugins from `$DSH_HOME/profiles/desktop`.
+
+Desktop has not been released. This is its first installation format; there are no readers or migrations for the unpublished seed-based profile. This note supersedes core seed installation and single-project dependency ownership in the [Desktop packaging decision](2026-08-25-electron-desktop-packaging-and-updates.md). That note continues to own release identity, signing, portless transport, process ownership, and Electron-only plugin authorization. No existing note is fully superseded or archived.
+
+## Package ownership
+
+The resource descriptor records the exact release, Node version, platform, architecture, shared package versions, and final file hashes. The runtime tree contains ordinary files and directories, without links back to pnpm’s build store. Native Mach-O files are signed before hashing; the application signer preserves their bytes and checks the inventory after signing. An explicit `dsh/node_modules` resource mapping bypasses electron-builder’s root `node_modules` exclusion, and the copied tree is verified before any signing or notarization.
+
+Every first-party package in the dsh and private Host production closures is shared. The profile contains directory symlinks to those resource packages, or junctions on Windows. Links resolve to real host package directories under normal Node resolution. Host and plugin imports therefore share the same module instance for each resolved export. Distinct ESM and CommonJS conditional exports remain distinct entry points; a link cannot merge a package’s dual implementations.
+
+External plugins declare shared host packages as peers. Ordinary dependencies remain plugin-owned and may differ from the versions used by dsh. Validation rejects incompatible enabled peers, nested or aliased copies of shared packages, private package links, and dependency resolution through CLI or other ancestor directories. A third-party package requiring host-wide instance identity must be explicitly added to the runtime’s shared inventory; matching version numbers alone are insufficient.
+
+The profile manifest records exact installed plugin dependencies separately from its enabled bundle list. Disabling a plugin preserves its package, lockfile entry, and user configuration. The shared links are Desktop-owned derived state, recorded separately from pnpm; package-manager operations run without those links, then Desktop recreates and validates them.
+
+## Transactions and upgrades
+
+First launch creates profile metadata and host links without running pnpm. A compatible release change or application relocation copies plugin files into staging, refreshes links, validates enabled peers, and boots the staged backend. Node version, platform, or architecture changes reinstall the locked plugin graph before activation. Writable staging and rollback files are independent copies, never hardlinks into the active profile.
+
+Dependency mutations install with scripts disabled, validate the plugin graph and host links, run the reviewed pending lifecycle builds, and validate again. This permits approved native dependencies to resolve host peers while preventing accidental duplicate host packages from reaching startup. The `allowBuilds` policy remains explicit; unsupported build-requiring dependencies fail the transaction.
+
+The transaction journal records source and target runtime identities and directory-move phases. Desktop waits for pnpm exit and stops the active backend before replacement. A failed or interrupted activation restores a complete profile. A runtime identity mismatch prevents the restored profile from booting under a different application release. The journal covers profile files, not arbitrary plugin startup effects or durable Session writes.
+
+An Electron-owned recovery window remains available when the backend cannot start. Users can update, remove, disable, or re-enable plugins and retry startup. Incompatible plugins are not silently deleted or automatically downgraded. Application rollback and profile rollback are separate operations; each backend launch requires the current runtime identity.
+
+## Alternatives considered
+
+- **Install the bundled offline seed at startup.** This preserves an ordinary pnpm installation procedure but repeats core extraction and installation on every affected machine. Materialized resources remove that work at the cost of more application files and release-builder responsibility.
+- **Link all host dependencies into plugins.** This unnecessarily couples ordinary plugin dependencies to the host. Only the explicit shared inventory is linked; private packages retain independent versions.
+- **Use hardlinks.** They cannot represent directories, may not cross volumes, share writable bytes, and retain old inodes after application replacement. Directory symlinks and Windows junctions express the intended package target.
+- **Use `NODE_PATH` or preserve symlink paths.** These do not provide uniform ESM resolution or shared module identity. Normal package lookup through explicit links is directly testable.
+- **Keep core packages in ASAR.** The backend uses upstream Node rather than Electron’s patched filesystem. Ordinary `extraResources` also preserves native loading and subprocess paths.
+
+## Consequences
+
+Core package installation is absent from first launch and compatible upgrades. Runtime integrity verification and a complete backend health check still cost startup time; no release latency or download-size improvement is claimed without measurement. Plugin preservation is conditional on host API and native runtime compatibility, with a visible recovery path when that condition fails.
+
+The [Desktop README](../../../../apps/desktop/README.md) owns operational guidance. Focused tests cover real pnpm installation and approved builds, shared ESM instance identity, private dependency versions, relocation, disabled plugins, native rebuild selection, activation failures, and transaction locking. Signed installed-artifact upgrades, macOS notarization, Windows junction/native behavior, release size and startup benchmarks, and real-model GUI recordings remain release-environment qualification requirements; unit fixtures do not substitute for them.

+ 51 - 0
.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md

@@ -0,0 +1,51 @@
+# Agent Note: 内置 Desktop 运行时并保留外部插件
+
+Status: implemented
+
+[English](2026-09-08-desktop-bundled-runtime-and-external-plugins.md) | 中文
+
+## 问题
+
+Desktop 初始化时安装核心依赖图,会重复发布构建器已经完成的工作。离线 store 消除了下载,但仍有解压、包管理器启动和安装成本。用户需要应用在生产依赖已就绪时启动,同时保留普通 npm 插件安装能力,以及跨应用升级的插件状态。
+
+分离的包目录可能加载重复的 Cordis 或服务模块。仅保留插件文件也不能证明它与新的宿主 API 或 Node 运行时兼容。
+
+## 决策
+
+[运行时准备](../../../../apps/desktop/scripts/prepare-dsh.ts)在构建时物化一次生产依赖图,并通过 `extraResources/dsh` 分发。Electron 壳保留在 ASAR 中。内置上游 Node 进程从资源启动私有 Desktop Host,并从 `$DSH_HOME/profiles/desktop` 加载已启用插件。
+
+Desktop 尚未发布。这是它的第一种安装格式;不提供未发布 seed profile 的读取器或迁移。本记录取代 [Desktop 打包决策](2026-08-25-electron-desktop-packaging-and-updates.zh.md)中的核心 seed 安装和单项目依赖归属部分。该记录继续负责发布身份、签名、无端口传输、进程归属和仅限 Electron 的插件授权。没有现有记录被完全取代或归档。
+
+## 包归属
+
+资源描述文件记录精确发布版本、Node 版本、平台、架构、共享包版本和最终文件哈希。运行时树包含普通文件和目录,不包含指回 pnpm 构建 store 的链接。原生 Mach-O 文件先签名再哈希;应用签名器保留其字节,并在签名后检查清单。明确的 `dsh/node_modules` 资源映射绕过 electron-builder 对根 `node_modules` 的排除,并在任何签名或公证前验证复制后的依赖树。
+
+dsh 与私有 Host 生产闭包中的每个第一方包都共享。profile 包含指向这些资源包的目录软链接,在 Windows 上使用 junction。正常 Node 解析会把链接解析到实际宿主包目录。因此,宿主与插件对每个已解析导出的导入共享同一模块实例。不同的 ESM 与 CommonJS 条件导出仍是不同入口;链接不能合并包的两套实现。
+
+外部插件把共享宿主包声明为 peer。普通依赖由插件拥有,可以不同于 dsh 使用的版本。验证拒绝已启用插件的不兼容 peer、共享包的嵌套或别名副本、私有包链接,以及通过 CLI 或其他祖先目录解析依赖。如果第三方包需要宿主范围的实例身份,必须明确加入运行时共享清单;版本号相同并不足够。
+
+profile manifest 分别记录精确的已安装插件依赖和已启用 bundle 列表。停用插件会保留其包、锁文件条目和用户配置。共享链接是 Desktop 拥有的派生状态,独立于 pnpm 记录;包管理器操作不携带这些链接,随后 Desktop 重建并验证它们。
+
+## 事务与升级
+
+首次启动创建 profile 元数据和宿主链接,不运行 pnpm。兼容的发布变化或应用移动会把插件文件复制到 staging,刷新链接,验证已启用的 peer,并启动 staging 后端。Node 版本、平台或架构变化时,激活前会重新安装锁定的插件依赖图。可写 staging 与回滚文件使用独立副本,不使用指向活动 profile 的硬链接。
+
+依赖修改先禁用脚本安装,验证插件依赖图和宿主链接,运行经过审查的待执行生命周期构建,再次验证。这允许已批准的原生依赖解析宿主 peer,同时阻止意外的重复宿主包进入启动过程。`allowBuilds` 策略保持明确;不受支持且需要构建的依赖会使事务失败。
+
+事务日志记录源与目标运行时身份以及目录移动阶段。Desktop 等待 pnpm 退出,并在替换前停止活动后端。失败或中断的激活会恢复完整 profile。运行时身份不匹配会阻止恢复的 profile 在其他应用版本下启动。事务日志覆盖 profile 文件,不覆盖任意插件启动副作用或持久 Session 写入。
+
+后端无法启动时,Electron 拥有的恢复窗口仍可使用。用户可以更新、移除、停用或重新启用插件,并重试启动。不兼容插件不会被静默删除或自动降级。应用回滚与 profile 回滚是独立操作;每次后端启动都要求当前运行时身份。
+
+## 考虑过的替代方案
+
+- **启动时安装内置离线 seed。** 这保留普通 pnpm 安装流程,但会在每台受影响机器上重复核心解压与安装。物化资源消除了这部分工作,代价是更多应用文件和发布构建器责任。
+- **把所有宿主依赖链接给插件。** 这会让普通插件依赖与宿主产生不必要的耦合。只链接明确的共享清单;私有包保留独立版本。
+- **使用硬链接。** 它不能表示目录,可能无法跨卷,共享可写字节,并在应用替换后保留旧 inode。目录软链接和 Windows junction 能表达预期的包目标。
+- **使用 `NODE_PATH` 或保留软链接路径。** 它们不能提供统一的 ESM 解析或共享模块身份。通过明确链接进行正常包查找可以直接测试。
+- **把核心包留在 ASAR。** 后端使用上游 Node,而不是 Electron 修改过的文件系统。普通 `extraResources` 也能保留原生加载和子进程路径。
+
+## 影响
+
+首次启动和兼容升级不安装核心包。运行时完整性验证和完整后端健康检查仍需要启动时间;没有测量前,不声称发布启动延迟或下载体积改善。插件保留以宿主 API 和原生运行时兼容为条件,条件不满足时提供可见的恢复入口。
+
+[Desktop README](../../../../apps/desktop/README.zh.md)负责操作说明。定向测试覆盖真实 pnpm 安装与已批准构建、共享 ESM 实例身份、私有依赖版本、应用移动、停用插件、原生重建选择、激活失败和事务锁。签名安装产物升级、macOS 公证、Windows junction 与原生行为、发布体积与启动基准,以及真实模型 GUI 录制仍是发布环境验收要求;单元夹具不能替代这些验证。

+ 6 - 0
.agents/notes/proposed/feature/2026-09-08-desktop-uninstall-preserve-dsh-home.i18n.yaml

@@ -0,0 +1,6 @@
+# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
+# side as of the last confirmed-consistent state. Both languages carry equal authority;
+# after editing either side, bring the other along and re-record with:
+#   pnpm run verify-translation-pairing --write .agents/notes/proposed/feature/2026-09-08-desktop-uninstall-preserve-dsh-home.md
+2026-09-08-desktop-uninstall-preserve-dsh-home.md: e1c2435814a4563f1fed6652d521928200d4ade7
+2026-09-08-desktop-uninstall-preserve-dsh-home.zh.md: 27fd7c8cbec360db35cadc75ff26b575629ad571

+ 95 - 0
.agents/notes/proposed/feature/2026-09-08-desktop-uninstall-preserve-dsh-home.md

@@ -0,0 +1,95 @@
+# Agent Note: Uninstall Desktop while preserving the Harness home
+
+Status: proposed
+
+English | [中文](2026-09-08-desktop-uninstall-preserve-dsh-home.zh.md)
+
+## Problem
+
+Users need Desktop uninstallation to remove its application files and external application state while retaining the complete Harness home. Removing an application directory does not account for browser storage, cached installers, or native updater state. Browser storage also contains unsent drafts and UI preferences, so removing it changes more than disk cache usage.
+
+The [packaging configuration](../../../../apps/desktop/electron-builder.config.mjs), [desktop entry](../../../../apps/desktop/src/main.ts), and [update coordinator](../../../../apps/desktop/src/update-coordinator.ts) are the inspection inputs. Source inspection identifies cleanup candidates; installed-artifact observation must establish the complete supported inventory before implementation is accepted. No uninstall experiment has yet established an exhaustive Windows or macOS inventory.
+
+## Proposal
+
+Provide an uninstall operation whose successful result leaves the complete default `~/.dsh` and any configured `DSH_HOME` intact, removes Desktop-owned files outside those homes, and removes the selected application installation. Preserve plugin files, package-manager state, sessions, settings, and credentials within the retained homes. Do not launch or repair the Desktop profile during cleanup.
+
+Windows Control Panel and Settings uninstallation will run this operation through NSIS. macOS will expose a localized **Uninstall and keep Harness data** action backed by a signed cleanup helper. Finder drag-to-Trash alone cannot invoke this operation; document that limitation and provide the same helper as a signed standalone uninstaller for users who already removed the application. A plain drag operation must not be advertised as complete cleanup.
+
+User-created projects, separately installed CLI software, user-saved downloads and exports, arbitrary third-party plugin/tool outputs, and OS-maintained audit/security records are outside application cleanup. Do not search the disk for names containing `dsh` or `DeepSeek`. The success promise concerns application-owned state, not deletion of user work or erasure of OS history.
+
+### 1. Establish ownership and actual paths
+
+Use disposable Windows and macOS accounts to capture filesystem and relevant registration differences across installation, first launch, draft editing, plugin installation, update download, update installation, and uninstallation. Inspect the packaged `package.json`, macOS `Info.plist`, `app-update.yml`, and runtime `app.getPath()` values. Include failed/interrupted updates. Record discovered owners and cleanup locations beside the desktop implementation, with fixture evidence rather than a dynamically accepted list of arbitrary absolute paths.
+
+| Candidate | Windows | macOS | Required treatment |
+|---|---|---|---|
+| Electron user/session data | Runtime `userData` and `sessionData`, normally under `%APPDATA%` | Runtime `userData` and `sessionData`, normally under `~/Library/Application Support` | Remove browser storage, preferences, cache, and `.updaterId`; disclose loss of unsent drafts. |
+| Installer/update cache | `%LOCALAPPDATA%/<updaterCacheDirName>` | `~/Library/Caches/<updaterCacheDirName>` | Remove cached installers, ZIPs, blockmaps, pending downloads, and metadata; include the NSIS installer copy created during installation. |
+| Native updater state | Any additional paths proved by the installed NSIS flow | App-specific Squirrel and `<appId>.ShipIt` cache/state/log directories | Stop the owned updater job and remove its remaining state after it exits. |
+| Other native application state | App-owned files/registrations proved by observation | App-specific preferences, saved state, logs, or diagnostics proved by observation | Add only established ownership; an Electron path API alone does not prove a file is created. |
+| Application and integration | Installation directory, installed shortcuts, installation/uninstallation registration | Selected `.app` and helper-owned integration | Use the native uninstall flow and validate the selected installation identity. |
+| Harness home | Default `.dsh` and configured `DSH_HOME` | Default `.dsh` and configured `DSH_HOME` | Preserve the complete trees, including Desktop-only subdirectories. |
+
+Create one small application-owned cleanup inventory, consumed by packaging and cleanup implementations. Derive identity and updater cache names from the release metadata. The same inventory must explain test expectations. Verify any existing distributed release before adding a legacy path; do not introduce migrations for unpublished development layouts.
+
+### 2. Implement shared preservation and cleanup rules
+
+Resolve targets for the installation owner, not the elevated administrator's home. Preserve the default home even when an override is active, and protect configured homes recorded by Desktop as well as the current override. Validate any persisted record at this file boundary; it may protect a location but may never authorize deletion of an arbitrary location.
+
+Reject deletion of a protected home, its ancestor, or its contents. Account for case-insensitive paths, symlinks, Windows junctions/reparse points, and path replacement during cleanup. Do not follow a link into another tree. An installation or cache location containing a protected home is a conflict: stop before recursive removal and report the remaining path. Keep these checks in the actual native removal path, not only in a preview.
+
+Stop new windows, updates, and plugin mutations; finish or safely stop active operations; stop the owned Host/process tree; then wait for exit and released files before removal. Do not kill processes solely by executable name. Perform an ownership/path preflight before destructive steps. Treat missing targets as success, and support retry after partial cleanup. Report locked or inaccessible paths explicitly; a queued reboot deletion or partial result is not complete cleanup.
+
+Keep `.dsh` free of cleanup journals or receipts. Any temporary helper/state must live in a private temporary directory, avoid executable-search-path lookup, and have a bounded self-cleanup path. Verify that cleanup does not recreate Electron user data after it has been removed. Cancellation before removal leaves the installation usable.
+
+### 3. Windows implementation
+
+Keep the assisted NSIS installer (`oneClick: false`). Extend its custom uninstall hooks and removal ordering rather than replacing the complete installer. Do not depend on `deleteAppDataOnUninstall` to cover updater caches, custom paths, or protected homes. Apply preservation checks before the default installation-directory removal as well as before extra cleanup.
+
+Normal Control Panel, Settings, direct uninstaller, and silent uninstall must share the same cleanup rules and useful exit status. Automatic update/replacement must skip destructive user-state cleanup; validate the actual electron-updater flags and NSIS update condition with a real upgrade. A failed upgrade must retain browser data and `.dsh`.
+
+Per-user uninstall cleans that installation owner's Desktop state. All-user uninstall must identify each affected local user profile and clean its Desktop-owned state while preserving every Harness home, under the required Windows privileges. Do not resolve all users through one `$APPDATA` expansion. If an affected profile is inaccessible or another installation still owns a shared path, report that condition instead of deleting shared state or claiming complete cleanup. Include this distinction in the uninstall UI and silent result.
+
+Let NSIS remove the application, its installed shortcuts, and installation registration. Explicitly remove the application-owned cache/user-data inventory, including the cached copy of the installer. Preserve existing signing requirements for installer, uninstaller, and any added executable. Add a build-time check that custom hooks and the cleanup inventory are actually packaged.
+
+### 4. macOS implementation
+
+Add the localized uninstall action to the Electron-owned menu/recovery UI so it remains available when the Host cannot boot. Before proceeding, show that `.dsh` is retained and unsent drafts/UI preferences outside it are deleted. Complete cleanup must include removal of the selected application bundle; if only moving it to Trash, report that disk space remains until Trash is emptied.
+
+Use a signed helper that can finish after Electron and the Host exit. Verify bundle identity and the selected path before removing it; handle `/Applications`, `~/Applications`, and a relocated writable bundle. Obtain authorization only for paths requiring it. Coordinate with Squirrel/ShipIt, remove only this application's updater jobs/state, and delete the discovered external application directories and preferences. Include helper staging files in completion verification.
+
+Package the same cleanup implementation as a signed, notarized standalone uninstaller for the already-deleted-app case. It must not require the removed bundle or a working `.dsh` profile. A read-only mounted DMG is not an installed writable application; provide an actionable result rather than attempting to alter it. For a shared application installation, account for affected users and privileges as on Windows; report any state that could not be cleaned.
+
+### 5. Verification and documentation
+
+Add focused tests for target ownership, protected-home overlap, link/reparse-point traversal, identity mismatch, arbitrary-path rejection, custom/absent `DSH_HOME`, another installation sharing data, and inaccessible profiles. Exercise cancellation, active Host/update/plugin processes, interruption between removals, retries, and self-cleanup without using the developer's real home. Follow the [CI reliability workflow](../../../skills/dsh-ci-test-reliability/SKILL.md) when implementing process and filesystem tests.
+
+Run installed-artifact e2e checks on Windows and both shipped macOS architectures. Cover first installation without updates, one downloaded/installed update, failed update, per-user/shared installation, relocated application, and standalone macOS cleanup after drag deletion. Compare filesystem/registration inventories independently of the uninstaller's success response. Hash retained `.dsh` content after the app and CLI are quiescent and before removal; require identical content, paths, and link entries afterward. Do not require preserved runtime links to resolve after their application target is removed.
+
+Add owner-local expected output for uninstall UI and failure results. Add a keyless recorded-session scenario proving an existing conversation survives uninstall/reinstall; keep purely installer/UI expectations outside the top-level Session tree. Record the required real-server/model GUI GIF for the implementation PR. Update the [Desktop README](../../../../apps/desktop/README.md), its Chinese counterpart, user instructions, locale dictionaries, JSDoc, and this proposal's lifecycle when implementation ships. Select focused checks through [dsh-pre-push-checks](../../../skills/dsh-pre-push-checks/SKILL.md); signed packaging and real OS uninstall evidence are required, not replaceable by unit tests.
+
+## Alternatives considered
+
+**Keep the default uninstallers.** They do not establish removal of application-owned state outside the application directory and therefore do not meet the requested outcome.
+
+**Move all Electron and update data under `.dsh`.** This can simplify file placement but preserves caches and browser state instead of cleaning them, and does not by itself cover Squirrel/native state or existing external files. It is not the cleanup solution proposed here.
+
+**Detect Finder deletion with a permanent background watcher.** This adds a resident component that itself needs removal and cannot reliably cover deletion while it is stopped. Use an explicit uninstall operation.
+
+**Delete `.dsh/desktop` or `.dsh/profiles/desktop`.** These paths contain Desktop-specific state, but the requested retention rule preserves the whole Harness home rather than only conversations.
+
+## Acceptance criteria
+
+- A successful supported uninstall removes the selected application, its owned registrations, and every external application-owned path established by the installed-artifact inventory; no cleanup helper or updater process remains.
+- Default and configured Harness homes retain identical content and links after quiescence. User projects and independent CLI installations remain intact.
+- Windows Control Panel/Settings and silent uninstall satisfy the same retention rule. An actual automatic upgrade retains browser state and Harness data.
+- macOS's explicit and standalone uninstallers satisfy the cleanup rule. Documentation accurately distinguishes them from Finder drag deletion and from merely moving files to Trash.
+- Every unremoved owned path is reported with a retry/recovery action. Unavailable privileges, an inaccessible user profile, and shared ownership never produce a false full-success result.
+- Fresh install and uninstall/reinstall tests prove no untracked outside-home application state survives and that retained conversations can be reopened. Native OS inventories, not only mocked API calls, establish completion.
+
+## Risks
+
+Deleting browser storage loses unsent drafts and UI preferences. Whole-home preservation deliberately retains Desktop plugins, pnpm state, and possibly dangling links until reinstall repairs them. Custom data paths and shared installations can prevent complete removal without additional privileges or path relocation; the operation must report that limitation rather than violate retention.
+
+OS-owned security/audit history and user-created files cannot be covered by a promise of erasing all traces. The [Desktop packaging decision](../../implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md) and [bundled runtime/external plugin decision](../../implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.md) remain independent authorities for packaging and data ownership; this proposal supersedes neither and archives no active note.

+ 95 - 0
.agents/notes/proposed/feature/2026-09-08-desktop-uninstall-preserve-dsh-home.zh.md

@@ -0,0 +1,95 @@
+# Agent Note: 卸载 Desktop 并保留 Harness 主目录
+
+Status: proposed
+
+[English](2026-09-08-desktop-uninstall-preserve-dsh-home.md) | 中文
+
+## 问题
+
+用户需要 Desktop 卸载删除应用文件及外部应用状态,同时保留完整的 Harness 主目录。删除应用目录并不能覆盖浏览器存储、安装器缓存或原生更新器状态。浏览器存储还包含未发送草稿和界面偏好,因此清理它不只是释放磁盘缓存。
+
+[打包配置](../../../../apps/desktop/electron-builder.config.mjs)、[桌面入口](../../../../apps/desktop/src/main.ts)和[更新协调器](../../../../apps/desktop/src/update-coordinator.ts)是代码检查依据。源码检查用于识别清理候选项;实现验收前,必须通过已安装产物的观察确定受支持的完整清单。目前尚未通过卸载实验建立完整的 Windows 或 macOS 清单。
+
+## 提案
+
+提供卸载操作:成功后保留完整的默认 `~/.dsh` 和已配置的 `DSH_HOME`,删除这些主目录之外由 Desktop 拥有的文件,并移除选定的应用安装。保留主目录内的插件文件、包管理器状态、会话、设置和凭据。清理期间不得启动或修复 Desktop profile。
+
+Windows 控制面板和设置中的卸载将通过 NSIS 执行此操作。macOS 将提供本地化的**卸载并保留 Harness 数据**操作,由签名的清理辅助程序完成;单纯通过 Finder 拖进废纸篓不能调用此操作,文档必须说明这一限制,并将同一辅助程序作为签名的独立卸载器提供给已经删除应用的用户。不得把单纯拖拽宣传为完整清理。
+
+用户创建的项目、单独安装的 CLI(命令行界面)软件、用户保存的下载文件和导出文件、任意第三方插件或工具的输出,以及操作系统维护的审计和安全记录,不属于应用清理范围。不得按文件名包含 `dsh` 或 `DeepSeek` 全盘搜索。成功承诺针对应用拥有的状态,不包括删除用户工作成果或抹除系统历史。
+
+### 1. 确定归属和实际路径
+
+使用一次性 Windows 和 macOS 账户,记录安装、首次启动、编辑草稿、安装插件、下载更新、安装更新及卸载前后的文件系统和相关注册信息差异。检查打包后的 `package.json`、macOS `Info.plist`、`app-update.yml` 和运行时 `app.getPath()` 值。覆盖更新失败和中断。将发现的归属与清理位置记录在桌面实现附近,提供 fixture(测试前置数据)证据,不采用动态接收任意绝对路径的清单。
+
+| 候选项 | Windows | macOS | 处理要求 |
+|---|---|---|---|
+| Electron 用户及会话数据 | 运行时 `userData` 和 `sessionData`,通常位于 `%APPDATA%` 下 | 运行时 `userData` 和 `sessionData`,通常位于 `~/Library/Application Support` 下 | 删除浏览器存储、偏好、缓存和 `.updaterId`;说明未发送草稿会丢失。 |
+| 安装器及更新缓存 | `%LOCALAPPDATA%/<updaterCacheDirName>` | `~/Library/Caches/<updaterCacheDirName>` | 删除安装器副本、ZIP、blockmap、待处理下载和元数据;包括 NSIS 安装期间创建的安装器缓存副本。 |
+| 原生更新器状态 | 通过实际安装的 NSIS 流程证实的其他路径 | 应用专属的 Squirrel 和 `<appId>.ShipIt` 缓存、状态及日志目录 | 停止所属更新任务,等待退出后删除残留状态。 |
+| 其他原生应用状态 | 观察证实由应用拥有的文件和注册信息 | 观察证实的应用专属偏好、窗口恢复状态、日志或诊断数据 | 只加入归属已确定的项目;存在 Electron 路径 API 不足以证明文件会产生。 |
+| 应用及系统集成 | 安装目录、安装的快捷方式、安装和卸载注册信息 | 选定的 `.app` 及辅助程序拥有的系统集成 | 使用原生卸载流程,并验证选定安装的身份。 |
+| Harness 主目录 | 默认 `.dsh` 和已配置的 `DSH_HOME` | 默认 `.dsh` 和已配置的 `DSH_HOME` | 保留完整目录树,包括 Desktop 专属子目录。 |
+
+建立一份精简的应用清理清单,由打包和清理实现共同使用。应用身份与更新缓存名称从发布元数据推导。同一清单必须对应测试期望。加入旧路径前先核查实际已分发版本,不为未发布的开发布局增加迁移。
+
+### 2. 实现共用的保留与清理规则
+
+按安装所属用户解析目标,不能使用提权管理员的主目录。即使覆盖路径已启用,也保留默认主目录;同时保护 Desktop 已记录的配置主目录和当前覆盖路径。持久化记录在文件边界进行校验;记录可以保护位置,但绝不能授权删除任意位置。
+
+拒绝删除受保护主目录、其祖先目录或其内容。处理路径大小写不敏感、符号链接、Windows junction/reparse point,以及清理期间路径被替换的情况。不得沿链接进入其他目录树。如果安装或缓存目录包含受保护主目录,则视为冲突:递归删除前停止,并报告剩余路径。这些检查必须位于实际原生删除流程中,不能只放在预览阶段。
+
+阻止新窗口、更新和插件变更;完成或安全停止正在进行的操作;停止所属 Host 和进程树;等待进程退出并释放文件后再删除。不得仅凭可执行文件名终止进程。破坏性步骤前先检查归属和路径。目标不存在视为成功,部分清理后允许重试。明确报告被占用或无法访问的路径;已安排重启后删除或部分完成,不等于完整清理。
+
+不得在 `.dsh` 写入清理日志或回执。临时辅助程序和状态必须位于私有临时目录,避免通过可执行文件搜索路径寻找程序,并具有有界的自行清理流程。验证清理不会在删除后重新创建 Electron 用户数据。删除开始前取消操作应保持安装可用。
+
+### 3. Windows 实现
+
+保留向导式 NSIS 安装器(`oneClick: false`)。扩展自定义卸载钩子和删除顺序,不替换整个安装器。不得依赖 `deleteAppDataOnUninstall` 覆盖更新缓存、自定义路径或主目录保护。在默认安装目录删除和额外清理前都应用保留检查。
+
+正常控制面板、设置、直接运行卸载器和静默卸载必须共用清理规则,并返回有用的退出状态。自动更新或替换安装必须跳过破坏性的用户状态清理;通过实际升级验证 electron-updater 参数和 NSIS 更新条件。升级失败必须保留浏览器数据和 `.dsh`。
+
+按用户安装的卸载清理该安装所属用户的 Desktop 状态。全用户卸载必须识别每个受影响的本地用户配置目录,在具备所需 Windows 权限的情况下清理其中由 Desktop 拥有的状态,并保留每个 Harness 主目录。不能用一次 `$APPDATA` 展开代表所有用户。如果受影响的用户目录无法访问,或另一个安装仍拥有共享路径,应报告该情况,不得删除共享状态或宣称完整清理。卸载界面和静默执行结果都要体现这一区别。
+
+由 NSIS 删除应用、安装的快捷方式和安装注册信息。显式删除清单中的应用缓存和用户数据,包括缓存的安装器副本。维持安装器、卸载器及新增可执行文件的签名要求。增加构建期检查,证明自定义钩子和清理清单确实进入产物。
+
+### 4. macOS 实现
+
+在 Electron 拥有的菜单和恢复界面加入本地化卸载操作,保证 Host 无法启动时仍可使用。执行前说明保留 `.dsh`,并删除主目录外的未发送草稿和界面偏好。完整清理必须包括移除选定应用包;如果只是移入废纸篓,应说明清空废纸篓前仍占用磁盘。
+
+使用签名的辅助程序,在 Electron 和 Host 退出后完成清理。删除前验证应用包身份和选定路径;覆盖 `/Applications`、`~/Applications` 及移动后的可写应用包。仅对需要权限的路径请求授权。协调 Squirrel/ShipIt,只移除本应用的更新任务和状态,再删除已识别的外部应用目录及偏好。完成验证必须包括辅助程序的临时文件。
+
+把同一清理实现打包为签名、公证的独立卸载器,支持应用已被删除的情况。它不能依赖已删除的应用包或可启动的 `.dsh` profile。只读挂载的 DMG 不属于已安装的可写应用;应给出可操作的结果,不能尝试修改它。共享应用安装和 Windows 一样需要处理受影响用户及权限,并报告未能清理的状态。
+
+### 5. 验证和文档
+
+增加针对性测试,覆盖目标归属、受保护主目录重叠、链接和 reparse point 遍历、身份不匹配、任意路径拒绝、自定义或未设置的 `DSH_HOME`、另一安装共享数据,以及无法访问的用户配置目录。覆盖取消、活跃 Host/更新/插件进程、删除步骤间中断、重试及自行清理,禁止使用开发者真实主目录。实现进程和文件系统测试时遵循 [CI 可靠性工作流](../../../skills/dsh-ci-test-reliability/SKILL.md)。
+
+在 Windows 和两个已发布 macOS 架构上执行已安装产物的 e2e 检查。覆盖首次安装且未更新、下载并安装一次更新、更新失败、按用户或共享安装、移动应用,以及拖拽删除后的独立 macOS 清理。独立比较文件系统和注册信息清单,不以卸载器的成功响应代替验证。应用和 CLI 静止后、删除前对保留的 `.dsh` 内容计算哈希;要求删除后内容、路径和链接条目完全一致。应用目标被删除后,不要求保留的运行时链接仍可解析。
+
+为卸载界面和失败结果增加归属模块旁的预期输出。增加无密钥的录制会话场景,证明已有会话能跨卸载和重装保留;纯安装器或界面预期不放入顶层 Session 树。为实现 PR(Pull Request)录制规则要求的真实服务器和模型 GUI GIF。实现交付时更新 [Desktop README](../../../../apps/desktop/README.zh.md)、英文对应文档、用户说明、语言字典、JSDoc 和本提案的生命周期。通过 [dsh-pre-push-checks](../../../skills/dsh-pre-push-checks/SKILL.md) 选择针对性检查;签名打包和真实操作系统卸载证据为必需项,不能由单元测试替代。
+
+## 考虑过的替代方案
+
+**维持默认卸载器。** 它们不能证明应用目录之外的应用状态已被移除,因此不满足要求。
+
+**把全部 Electron 和更新数据移到 `.dsh`。** 这能简化文件位置,但会保留缓存和浏览器状态而不是清理它们,而且自身不能覆盖 Squirrel/原生状态或已有的外部文件。本提案不采用它作为清理方案。
+
+**通过常驻后台监视器检测 Finder 删除。** 这会增加一个本身也需要卸载的常驻组件,并且不能可靠覆盖监视器停止期间发生的删除。采用显式卸载操作。
+
+**删除 `.dsh/desktop` 或 `.dsh/profiles/desktop`。** 这些路径包含 Desktop 专属状态,但要求保留的是整个 Harness 主目录,而不只是会话。
+
+## 验收标准
+
+- 受支持的卸载成功后,选定应用、它拥有的注册信息,以及已安装产物清单确定的每个外部应用路径均已移除;没有清理辅助程序或更新器进程残留。
+- 静止后,默认和已配置 Harness 主目录的内容及链接完全保留。用户项目和独立 CLI 安装保持完整。
+- Windows 控制面板、设置及静默卸载满足同一保留规则。实际自动升级保留浏览器状态和 Harness 数据。
+- macOS 显式操作和独立卸载器满足清理规则。文档准确区分它们与 Finder 拖拽删除,以及仅移入废纸篓的情况。
+- 每个未移除的所属路径都报告重试或恢复方式。权限不足、用户配置目录不可访问和共享归属均不得产生虚假的完整成功结果。
+- 首次安装及卸载重装测试证明,没有未纳入清单的主目录外应用状态残留,且能重新打开保留的会话。通过原生操作系统清单验证完成,不能只依赖模拟 API 调用。
+
+## 风险
+
+删除浏览器存储会丢失未发送草稿和界面偏好。完整保留主目录意味着有意保留 Desktop 插件、pnpm 状态,以及可能在重装修复前悬空的链接。自定义数据路径和共享安装可能需要额外权限或移动路径才能完整删除;操作必须报告限制,不能违反保留规则。
+
+操作系统拥有的安全和审计历史,以及用户创建的文件,不能被“抹除所有痕迹”的承诺覆盖。[Desktop 打包决策](../../implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md)和[内置运行时与外部插件决策](../../implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md)继续分别拥有打包和数据归属规则;本提案不取代这两份记录,也不归档任何活跃记录。

+ 19 - 15
apps/desktop-host/src/index.ts

@@ -149,12 +149,12 @@ function isProjectPath(projectDir: string, target: string): boolean {
   return path === root || path.startsWith(root + sep)
 }
 
-function desktopPatches(projectDir: string, allowLinkedPackages: boolean): PatchOptions[] {
-  const dshRoot = dirname(packageManifestPath(projectDir, '@deepseek-ai/dsh'))
+function desktopPatches(runtimeDir: string, projectDir: string, allowLinkedPackages: boolean): PatchOptions[] {
+  const dshRoot = dirname(packageManifestPath(runtimeDir, '@deepseek-ai/dsh'))
   const profile = loadProfileDirectory('dsh desktop', projectDir, join(dshRoot, 'package.json'))
   for (const layer of profile.layers) {
-    if (!allowLinkedPackages && !isProjectPath(projectDir, layer.packageDir)) {
-      throw new Error(`dsh desktop: profile bundle ${JSON.stringify(layer.packageName)} resolved outside the desktop profile`)
+    if (!allowLinkedPackages && !isProjectPath(projectDir, layer.packageDir) && !isProjectPath(runtimeDir, layer.packageDir)) {
+      throw new Error(`dsh desktop: profile bundle ${JSON.stringify(layer.packageName)} resolved outside the Desktop runtime and profile`)
     }
   }
   const layers = [
@@ -176,14 +176,14 @@ function desktopPatches(projectDir: string, allowLinkedPackages: boolean): Patch
   return layers.flat()
 }
 
-function dshVersion(projectDir: string): string {
-  const manifest = readManifest(packageManifestPath(projectDir, '@deepseek-ai/dsh'))
+function dshVersion(runtimeDir: string): string {
+  const manifest = readManifest(packageManifestPath(runtimeDir, '@deepseek-ai/dsh'))
   if (typeof manifest.version !== 'string') throw new Error('dsh desktop: installed dsh manifest has no version')
   return manifest.version
 }
 
-function assetHandler(ctx: Context, projectDir: string): ConnectionFetchHandler {
-  const require = createRequire(join(projectDir, 'package.json'))
+function assetHandler(ctx: Context, runtimeDir: string): ConnectionFetchHandler {
+  const require = createRequire(join(runtimeDir, 'package.json'))
   const distIndex = require.resolve('@deepseek-ai/dsh-web-frontend/dist/index.html')
   const distRoot = realpathSync(dirname(distIndex))
   const renderIndex = async (): Promise<Response> => {
@@ -270,12 +270,14 @@ interface NodeRequestInit extends RequestInit {
 
 /**
  * Boot one installed desktop npm project.
+ * @param runtimeDir - immutable dsh packages supplied by the Electron application.
  * @param projectDir - active or staged Electron-owned desktop profile.
  * @param writeResponse - serialized response-pipe writer that applies byte backpressure.
  * @param options - development-only allowance for workspace-linked bundle packages.
  * @returns controller after every Host and client-manifest row is active.
  */
 export async function runDesktopHost(
+  runtimeDir: string,
   projectDir: string,
   writeResponse: (frame: Buffer) => Promise<void>,
   options: { allowLinkedPackages?: boolean } = {},
@@ -287,6 +289,7 @@ export async function runDesktopHost(
   const environment = loadLayeredEnv('dsh desktop')
   let current: Context | undefined
   const ctx = await boot('dsh desktop', rootConfig, structuredClone(desktopPatches(
+    resolve(runtimeDir),
     absoluteProject,
     options.allowLinkedPackages === true,
   )), (hostCtx) => {
@@ -303,7 +306,7 @@ export async function runDesktopHost(
     throw new Error('dsh desktop: composition did not provide connection, typertGateway, and clientModules')
   }
   const api = connection.createSharedFetchHandler('/api')
-  const assets = assetHandler(ctx, absoluteProject)
+  const assets = assetHandler(ctx, resolve(runtimeDir))
   const streams = remoteStreamHandler(ctx)
   const requests = new Map<number, AbortController>()
   let disposing: Promise<void> | undefined
@@ -319,7 +322,7 @@ export async function runDesktopHost(
   }
 
   return {
-    dshVersion: dshVersion(absoluteProject),
+    dshVersion: dshVersion(resolve(runtimeDir)),
     cancel(streamId) {
       requests.get(streamId)?.abort()
     },
@@ -374,11 +377,12 @@ export async function runDesktopHost(
 }
 
 async function main(): Promise<void> {
-  const projectDir = process.argv[2]
-  if (projectDir === undefined || process.send === undefined) {
-    throw new Error('dsh desktop: expected project directory, byte pipes, and a Node IPC channel')
+  const runtimeDir = process.argv[2]
+  const projectDir = process.argv[3]
+  if (runtimeDir === undefined || projectDir === undefined || process.send === undefined) {
+    throw new Error('dsh desktop: expected runtime and profile directories, byte pipes, and a Node IPC channel')
   }
-  const option = process.argv[3]
+  const option = process.argv[4]
   if (option !== undefined && option !== '--allow-linked-profile') {
     throw new Error(`dsh desktop: unsupported internal option ${JSON.stringify(option)}`)
   }
@@ -403,7 +407,7 @@ async function main(): Promise<void> {
       if ((error as NodeJS.ErrnoException).code !== 'ERR_IPC_CHANNEL_CLOSED') throw error
     }
   }
-  const controller = await runDesktopHost(projectDir, writeResponse, { allowLinkedPackages: option !== undefined })
+  const controller = await runDesktopHost(runtimeDir, projectDir, writeResponse, { allowLinkedPackages: option !== undefined })
   send({
     type: 'ready',
     protocolVersion: DESKTOP_HOST_PROTOCOL_VERSION,

+ 2 - 2
apps/desktop/README.i18n.yaml

@@ -2,5 +2,5 @@
 # side as of the last confirmed-consistent state. Both languages carry equal authority;
 # after editing either side, bring the other along and re-record with:
 #   pnpm run verify-translation-pairing --write apps/desktop/README.md
-README.md: cf350a9d5e9577f5cf52c4371b32f16e278133f9
-README.zh.md: df48eb5903e21cae9ff041626c28d41d12e5c632
+README.md: b2a51010dc37bcca7c7846819b72ababdc227496
+README.zh.md: 241a1e1d900fef49042a7526d29fc473ef568088

A diferenza do arquivo foi suprimida porque é demasiado grande
+ 19 - 29
apps/desktop/README.md


A diferenza do arquivo foi suprimida porque é demasiado grande
+ 19 - 29
apps/desktop/README.zh.md


+ 3 - 1
apps/desktop/electron-builder.config.d.mts

@@ -6,12 +6,14 @@ export interface DesktopElectronBuilderConfig {
   }
   readonly extraResources: readonly [
     { readonly from: string, readonly to: 'runtime' },
-    { readonly from: string, readonly to: 'seed' },
+    { readonly from: string, readonly to: 'dsh' },
+    { readonly from: string, readonly to: 'dsh/node_modules' },
   ]
   readonly mac: {
     readonly identity: string | undefined
     readonly forceCodeSigning: boolean
     readonly notarize: boolean
+    readonly signIgnore: readonly string[]
   }
   readonly dmg: {
     readonly sign: boolean

+ 15 - 2
apps/desktop/electron-builder.config.mjs

@@ -1,3 +1,4 @@
+import { join } from 'node:path'
 import {
   resolveDesktopAppId,
   resolveMacOSNotarizationEnvironment,
@@ -59,13 +60,17 @@ export function createElectronBuilderConfig(
     ],
     extraResources: [
       { from: buildPaths.runtime, to: 'runtime' },
-      { from: buildPaths.seed, to: 'seed' },
+      { from: buildPaths.dsh, to: 'dsh' },
+      // electron-builder excludes a source directory's root node_modules.
+      { from: join(buildPaths.dsh, 'node_modules'), to: 'dsh/node_modules' },
     ],
     mac: {
       category: 'public.app-category.developer-tools',
       identity: macOSSigning?.signingIdentity,
       forceCodeSigning: true,
       hardenedRuntime: true,
+      // Runtime files are signed before their integrity inventory is sealed.
+      signIgnore: ['/Contents/Resources/dsh(?:/|$)'],
       notarize: true,
       target: ['dmg', 'zip'],
     },
@@ -73,8 +78,16 @@ export function createElectronBuilderConfig(
       sign: true,
       writeUpdateInfo: false,
     },
-    afterSign: context => {
+    afterPack: async context => {
+      const { verifyDesktopRuntime } = await import('./lib/types/runtime-tree.js')
+      verifyDesktopRuntime(join(context.packager.getResourcesDir(context.appOutDir), 'dsh'),
+        context.packager.appInfo.version, { platform: resolvedPlatform, arch: resolvedArch })
+    },
+    afterSign: async context => {
       if (context.electronPlatformName !== 'darwin') return
+      const { verifyDesktopRuntime } = await import('./lib/types/runtime-tree.js')
+      verifyDesktopRuntime(join(context.appOutDir, `${context.packager.appInfo.productFilename}.app`, 'Contents', 'Resources', 'dsh'),
+        context.packager.appInfo.version, { platform: 'darwin', arch: resolvedArch })
       verifyMacOSSignatureAfterSign(context, macOSSigning ?? resolveMacOSSigningEnvironment(env))
     },
     artifactBuildCompleted: artifact => {

+ 2 - 3
apps/desktop/package.json

@@ -1,6 +1,6 @@
 {
   "name": "@deepseek-ai/dsh-desktop",
-  "description": "Electron desktop shell for an isolated pnpm-installed dsh runtime",
+  "description": "Electron desktop shell for a bundled dsh runtime and external plugins",
   "version": "0.1.3-alpha.2",
   "private": true,
   "license": "MIT",
@@ -12,7 +12,7 @@
     "start": "tsx scripts/dev.ts --skip-build",
     "prepare:runtime": "tsx scripts/prepare-runtime.ts",
     "prepare:packages": "tsx scripts/prepare-package-set.ts",
-    "prepare:seed": "tsx scripts/prepare-seed.ts",
+    "prepare:dsh": "tsx scripts/prepare-dsh.ts",
     "prepare:package": "tsx scripts/package-target.ts --prepare-only",
     "verify:mac-signature": "node scripts/verify-macos-signature.mjs",
     "package": "tsx scripts/package-target.ts",
@@ -43,7 +43,6 @@
     "electron-builder": "^26.15.3",
     "extract-zip": "^2.0.1",
     "js-yaml": "^4.2.0",
-    "msgpackr": "2.0.4",
     "pnpm": "11.7.0",
     "tar": "^7.5.0",
     "typescript": "^6.0.3"

+ 6 - 0
apps/desktop/renderer/plugin-manager.html

@@ -16,6 +16,12 @@
         </div>
         <button id="refresh" class="quiet" type="button"></button>
       </header>
+      <section id="recovery" hidden>
+        <p id="recovery-description"></p>
+        <p id="startup-error" role="alert"></p>
+        <button id="retry" type="button"></button>
+        <button id="disable-all" type="button"></button>
+      </section>
       <form id="install-form">
         <label id="package-label" for="package-spec"></label>
         <div class="install-row">

+ 17 - 2
apps/desktop/renderer/plugin-manager.js

@@ -14,6 +14,10 @@ async function main() {
   document.querySelector('#installed-heading').textContent = messages.installed
   document.querySelector('#empty').textContent = messages.noPlugins
 
+  document.querySelector('#recovery-description').textContent = messages.recoveryDescription
+  document.querySelector('#retry').textContent = messages.retry
+  document.querySelector('#disable-all').textContent = messages.disableAll
+
   const list = document.querySelector('#plugins')
   const empty = document.querySelector('#empty')
   const status = document.querySelector('#status')
@@ -27,13 +31,16 @@ async function main() {
   }
 
   async function render() {
+    const backend = await api.backend.status()
+    document.querySelector('#recovery').hidden = backend.ready
+    document.querySelector('#startup-error').textContent = backend.error ?? ''
     const plugins = await api.plugins.list()
     list.replaceChildren(...plugins.map(plugin => {
       const item = document.createElement('li')
       const identity = document.createElement('span')
       const version = document.createElement('span')
       version.className = 'package-version'
-      version.textContent = plugin.version
+      version.textContent = plugin.enabled ? plugin.version : `${plugin.version} · ${messages.disabled}`
       identity.append(document.createTextNode(plugin.name), version)
       const remove = document.createElement('button')
       remove.type = 'button'
@@ -52,7 +59,13 @@ async function main() {
       })
       const actions = document.createElement('span')
       actions.className = 'package-actions'
-      actions.append(update, remove)
+      const toggle = document.createElement('button')
+      toggle.type = 'button'
+      toggle.textContent = plugin.enabled ? messages.disable : messages.enable
+      toggle.addEventListener('click', () => void run(
+        () => api.plugins.toggle(plugin.name, !plugin.enabled), messages.changingActivation,
+      ))
+      actions.append(toggle, update, remove)
       item.append(identity, actions)
       return item
     }))
@@ -93,6 +106,8 @@ async function main() {
       input.value = ''
     }, message('installing', { spec }))
   })
+  document.querySelector('#retry').addEventListener('click', () => void run(() => api.backend.retry(), messages.retry))
+  document.querySelector('#disable-all').addEventListener('click', () => void run(() => api.plugins.disableAll(), messages.changingActivation))
   refresh.addEventListener('click', () => void load(messages.refreshing, messages.refreshed))
 
   await load(messages.loadingPlugins, '')

+ 2 - 2
apps/desktop/scripts/desktop-build-paths.d.mts

@@ -6,8 +6,8 @@ export interface DesktopTargetBuildPaths {
   readonly artifacts: string
   readonly runtime: string
   readonly packageSet: string
-  readonly seed: string
-  readonly seedPnpm: string
+  readonly dsh: string
+  readonly dshPnpm: string
   readonly nodeExtract: string
   readonly packedDsh: string
   readonly packedVendor: string

+ 3 - 3
apps/desktop/scripts/desktop-build-paths.mjs

@@ -31,7 +31,7 @@ export function resolveDesktopBuildTarget(
 /**
  * Return the mutable preparation and artifact directories owned by one release target.
  * @param {'mac-arm64' | 'mac-x64' | 'win-x64'} target - Supported Desktop target name.
- * @returns {{ root: string, artifacts: string, runtime: string, packageSet: string, seed: string, seedPnpm: string, nodeExtract: string, packedDsh: string, packedVendor: string, packedLandlock: string, downloads: string }} Target paths plus the shared immutable download cache.
+ * @returns {{ root: string, artifacts: string, runtime: string, packageSet: string, dsh: string, dshPnpm: string, nodeExtract: string, packedDsh: string, packedVendor: string, packedLandlock: string, downloads: string }} Target paths plus the shared immutable download cache.
  */
 export function desktopTargetBuildPaths(target) {
   if (!SUPPORTED_TARGETS.has(target)) {
@@ -44,8 +44,8 @@ export function desktopTargetBuildPaths(target) {
     artifacts: join(root, 'artifacts'),
     runtime: join(root, 'runtime'),
     packageSet: join(root, 'package-set'),
-    seed: join(root, 'seed'),
-    seedPnpm: join(root, 'seed-pnpm'),
+    dsh: join(root, 'dsh'),
+    dshPnpm: join(root, 'dsh-pnpm'),
     nodeExtract: join(root, 'node-extract'),
     packedDsh: join(packed, 'dsh'),
     packedVendor: join(packed, 'vendor'),

+ 43 - 0
apps/desktop/scripts/macos-runtime.ts

@@ -0,0 +1,43 @@
+/** Sign final native runtime files before the enclosing Desktop application is signed. */
+
+import { createHash } from 'node:crypto'
+import { closeSync, openSync, readSync } from 'node:fs'
+import { join } from 'node:path'
+import { inventoryDesktopRuntime } from '../src/runtime-tree.ts'
+import type { MacOSSigningEnvironment } from './desktop-release-environment.mjs'
+import { signMacOSRuntimeCode, verifyMacOSRuntimeCode } from './verify-macos-signature.mjs'
+
+const MACH_O_MAGICS = new Set(['cafebabe', 'cafebabf', 'cefaedfe', 'cffaedfe', 'feedface', 'feedfacf', 'bebafeca', 'bfbafeca'])
+
+function isMachO(path: string): boolean {
+  const descriptor = openSync(path, 'r')
+  try {
+    const header = Buffer.alloc(4)
+    return readSync(descriptor, header, 0, 4, 0) === 4 && MACH_O_MAGICS.has(header.toString('hex'))
+  } finally { closeSync(descriptor) }
+}
+
+/**
+ * Sign and verify every materialized Mach-O file, awaiting all signers on failure.
+ * @param root - Self-contained production runtime without symlinks.
+ * @param appId - Release application identifier.
+ * @param expected - Required signing identity.
+ * @returns Number of signed native files.
+ */
+export async function signMacOSRuntime(root: string, appId: string, expected: MacOSSigningEnvironment): Promise<number> {
+  const files = inventoryDesktopRuntime(root).map(file => file.path).filter(path => isMachO(join(root, path)))
+  let next = 0
+  const workers = Array.from({ length: Math.min(4, files.length) }, async () => {
+    for (;;) {
+      const path = files[next++]
+      if (path === undefined) return
+      const identifier = `${appId}.runtime.${createHash('sha256').update(path).digest('hex')}`
+      await signMacOSRuntimeCode(join(root, path), identifier, expected)
+      verifyMacOSRuntimeCode(join(root, path), expected)
+    }
+  })
+  const results = await Promise.allSettled(workers)
+  const errors = results.filter(result => result.status === 'rejected').map(result => result.reason as unknown)
+  if (errors.length > 0) throw new AggregateError(errors, 'desktop runtime: native signing failed')
+  return files.length
+}

+ 0 - 413
apps/desktop/scripts/macos-seed-store.ts

@@ -1,413 +0,0 @@
-/** Sign Mach-O content in a pnpm CAS without invalidating the store index. */
-
-import { createHash } from 'node:crypto'
-import {
-  chmodSync,
-  closeSync,
-  copyFileSync,
-  existsSync,
-  mkdirSync,
-  mkdtempSync,
-  openSync,
-  readFileSync,
-  readSync,
-  readdirSync,
-  rmSync,
-  unlinkSync,
-  writeFileSync,
-} from 'node:fs'
-import { availableParallelism, tmpdir } from 'node:os'
-import { basename, dirname, join, relative, sep } from 'node:path'
-import { DatabaseSync } from 'node:sqlite'
-import { Packr } from 'msgpackr'
-import type { MacOSSigningEnvironment } from './desktop-release-environment.mjs'
-import { signMacOSSeedCode, verifyMacOSSeedCode } from './verify-macos-signature.mjs'
-
-const MACH_O_MAGICS = new Set([
-  'cafebabe',
-  'cafebabf',
-  'cefaedfe',
-  'cffaedfe',
-  'feedface',
-  'feedfacf',
-  'bebafeca',
-  'bfbafeca',
-])
-const CAS_PATH_PATTERN = /^([0-9a-f]{2})\/([0-9a-f]{126})(-exec)?$/u
-const MAX_CONCURRENT_CODE_SIGNERS = 4
-const packr = new Packr({ moreTypes: true, useRecords: true })
-
-interface PnpmStoreFileRecord {
-  checkedAt: number
-  digest: string
-  mode: number
-  size: number
-}
-
-interface PnpmSideEffectsRecord {
-  readonly added?: Map<string, PnpmStoreFileRecord>
-}
-
-interface PnpmPackageIndexRecord {
-  readonly algo?: string
-  readonly files?: Map<string, PnpmStoreFileRecord>
-  readonly sideEffects?: Map<string, PnpmSideEffectsRecord>
-}
-
-interface DecodedIndexRow {
-  readonly key: string
-  readonly value: PnpmPackageIndexRecord
-  changed: boolean
-}
-
-interface CasFile {
-  readonly path: string
-  readonly digest: string
-  readonly executable: boolean
-}
-
-interface FileReference {
-  readonly row: DecodedIndexRow
-  readonly record: PnpmStoreFileRecord
-}
-
-interface SigningWork {
-  readonly file: CasFile
-  readonly references: readonly FileReference[]
-  readonly temporaryPath: string
-}
-
-/** Summary of native code rewritten in one pnpm store. */
-export interface MacOSSeedStoreSigningResult {
-  readonly signedFiles: number
-  readonly prunedOrphans: number
-  readonly updatedIndexRows: number
-}
-
-/** A signer used to make one writable Mach-O copy release-valid. */
-export type MacOSSeedCodeSigner = (path: string, identifier: string) => Promise<void>
-
-/** A verifier used to check one Mach-O file after packaging transport. */
-export type MacOSSeedCodeVerifier = (path: string) => void
-
-/** Optional execution controls for seed-store code signing. */
-export interface MacOSSeedStoreSigningOptions {
-  readonly signer?: MacOSSeedCodeSigner
-  readonly concurrency?: number
-}
-
-function isRecord(value: unknown): value is Record<string, unknown> {
-  return typeof value === 'object' && value !== null
-}
-
-function isStoreFileRecord(value: unknown): value is PnpmStoreFileRecord {
-  if (!isRecord(value)) return false
-  return typeof value.checkedAt === 'number'
-    && typeof value.digest === 'string'
-    && /^[0-9a-f]{128}$/u.test(value.digest)
-    && Number.isSafeInteger(value.mode)
-    && Number.isSafeInteger(value.size)
-}
-
-function packageFileMaps(value: unknown, key: string): readonly Map<string, PnpmStoreFileRecord>[] {
-  if (!isRecord(value)) throw new Error(`desktop seed signing: invalid pnpm index record ${key}`)
-  const record = value as PnpmPackageIndexRecord
-  if (record.algo !== undefined && record.algo !== 'sha512') {
-    throw new Error(`desktop seed signing: unsupported pnpm index algorithm in ${key}`)
-  }
-  const maps: Map<string, PnpmStoreFileRecord>[] = []
-  if (record.files !== undefined) {
-    if (!(record.files instanceof Map)) throw new Error(`desktop seed signing: invalid pnpm file map in ${key}`)
-    maps.push(record.files)
-  }
-  if (record.sideEffects !== undefined) {
-    if (!(record.sideEffects instanceof Map)) {
-      throw new Error(`desktop seed signing: invalid pnpm side-effects map in ${key}`)
-    }
-    for (const effect of record.sideEffects.values()) {
-      if (!isRecord(effect)) throw new Error(`desktop seed signing: invalid pnpm side effect in ${key}`)
-      if (effect.added === undefined) continue
-      if (!(effect.added instanceof Map)) {
-        throw new Error(`desktop seed signing: invalid pnpm side-effect file map in ${key}`)
-      }
-      maps.push(effect.added)
-    }
-  }
-  for (const files of maps) {
-    for (const file of files.values()) {
-      if (!isStoreFileRecord(file)) throw new Error(`desktop seed signing: invalid pnpm file record in ${key}`)
-    }
-  }
-  return maps
-}
-
-function isExecutableMode(mode: number): boolean {
-  return (mode & 0o111) !== 0
-}
-
-function referenceKey(digest: string, executable: boolean): string {
-  return `${digest}:${executable ? 'exec' : 'nonexec'}`
-}
-
-function isMachO(path: string): boolean {
-  const descriptor = openSync(path, 'r')
-  try {
-    const header = Buffer.alloc(4)
-    return readSync(descriptor, header, 0, header.length, 0) === header.length
-      && MACH_O_MAGICS.has(header.toString('hex'))
-  } finally {
-    closeSync(descriptor)
-  }
-}
-
-function visitFiles(root: string): readonly string[] {
-  const files: string[] = []
-  const visit = (directory: string): void => {
-    for (const entry of readdirSync(directory, { withFileTypes: true })) {
-      const path = join(directory, entry.name)
-      if (entry.isSymbolicLink()) {
-        throw new Error(`desktop seed signing: pnpm store contains a symbolic link: ${relative(root, path)}`)
-      }
-      if (entry.isDirectory()) visit(path)
-      else if (entry.isFile()) files.push(path)
-      else throw new Error(`desktop seed signing: unsupported pnpm store entry: ${relative(root, path)}`)
-    }
-  }
-  visit(root)
-  return files.sort((left, right) => left.localeCompare(right))
-}
-
-function versionRoots(storeRoot: string): readonly string[] {
-  return readdirSync(storeRoot, { withFileTypes: true })
-    .filter(entry => entry.isDirectory() && /^v\d+$/u.test(entry.name))
-    .map(entry => join(storeRoot, entry.name))
-    .filter(root => existsSync(join(root, 'files')))
-    .sort((left, right) => left.localeCompare(right))
-}
-
-function casFiles(versionRoot: string): readonly CasFile[] {
-  const filesRoot = join(versionRoot, 'files')
-  const result: CasFile[] = []
-  for (const path of visitFiles(filesRoot)) {
-    if (!isMachO(path)) continue
-    const normalized = relative(filesRoot, path).split(sep).join('/')
-    const match = CAS_PATH_PATTERN.exec(normalized)
-    if (match === null) {
-      throw new Error(`desktop seed signing: Mach-O content has an unsupported pnpm CAS path: ${normalized}`)
-    }
-    result.push({
-      path,
-      digest: `${match[1]}${match[2]}`,
-      executable: match[3] !== undefined,
-    })
-  }
-  return result
-}
-
-function readIndexRows(database: DatabaseSync): readonly DecodedIndexRow[] {
-  const rows: DecodedIndexRow[] = []
-  for (const row of database.prepare('SELECT key, data FROM package_index').iterate() as Iterable<{
-    key: string
-    data: Uint8Array
-  }>) {
-    rows.push({ key: row.key, value: packr.unpack(row.data) as PnpmPackageIndexRecord, changed: false })
-  }
-  return rows
-}
-
-function fileReferences(rows: readonly DecodedIndexRow[]): ReadonlyMap<string, readonly FileReference[]> {
-  const references = new Map<string, FileReference[]>()
-  for (const row of rows) {
-    for (const files of packageFileMaps(row.value, row.key)) {
-      for (const record of files.values()) {
-        const key = referenceKey(record.digest, isExecutableMode(record.mode))
-        const values = references.get(key) ?? []
-        values.push({ row, record })
-        references.set(key, values)
-      }
-    }
-  }
-  return references
-}
-
-function writeCasFile(path: string, body: Buffer, mode: number): void {
-  mkdirSync(dirname(path), { recursive: true })
-  try {
-    writeFileSync(path, body, { flag: 'wx', mode })
-  } catch (error) {
-    if (!isRecord(error) || error.code !== 'EEXIST' || !readFileSync(path).equals(body)) throw error
-  }
-  chmodSync(path, mode)
-}
-
-function signedCasPath(versionRoot: string, digest: string, executable: boolean): string {
-  return join(
-    versionRoot,
-    'files',
-    digest.slice(0, 2),
-    `${digest.slice(2)}${executable ? '-exec' : ''}`,
-  )
-}
-
-async function runConcurrent<T>(
-  values: readonly T[],
-  concurrency: number,
-  run: (value: T) => Promise<void>,
-): Promise<void> {
-  let next = 0
-  const failure: { error?: unknown; failed: boolean } = { failed: false }
-  const worker = async (): Promise<void> => {
-    while (!failure.failed) {
-      const index = next
-      if (index >= values.length) return
-      next += 1
-      try {
-        await run(values[index] as T)
-      } catch (error) {
-        if (!failure.failed) {
-          failure.failed = true
-          failure.error = error
-        }
-      }
-    }
-  }
-  const workers = Array.from(
-    { length: Math.min(concurrency, values.length) },
-    async () => worker(),
-  )
-  await Promise.all(workers)
-  if (failure.failed) throw failure.error
-}
-
-async function rewriteVersionStore(
-  versionRoot: string,
-  appId: string,
-  signer: MacOSSeedCodeSigner,
-  concurrency: number,
-): Promise<MacOSSeedStoreSigningResult> {
-  const databasePath = join(versionRoot, 'index.db')
-  if (!existsSync(databasePath)) {
-    throw new Error(`desktop seed signing: pnpm store has no package index: ${databasePath}`)
-  }
-  const database = new DatabaseSync(databasePath)
-  const workRoot = mkdtempSync(join(tmpdir(), 'dsh-desktop-seed-signing-'))
-  const obsoleteFiles = new Set<string>()
-  let prunedOrphans = 0
-  let rows: readonly DecodedIndexRow[] = []
-  try {
-    rows = readIndexRows(database)
-    const references = fileReferences(rows)
-    const signingWork: SigningWork[] = []
-    for (const file of casFiles(versionRoot)) {
-      const body = readFileSync(file.path)
-      const actualDigest = createHash('sha512').update(body).digest('hex')
-      if (actualDigest !== file.digest) {
-        throw new Error(`desktop seed signing: pnpm CAS digest mismatch at ${file.path}`)
-      }
-      const fileReferences = references.get(referenceKey(file.digest, file.executable)) ?? []
-      if (fileReferences.length === 0) {
-        obsoleteFiles.add(file.path)
-        prunedOrphans += 1
-        continue
-      }
-      const temporary = join(workRoot, `${signingWork.length.toString().padStart(4, '0')}-${basename(file.path)}`)
-      copyFileSync(file.path, temporary)
-      chmodSync(temporary, 0o755)
-      signingWork.push({ file, references: fileReferences, temporaryPath: temporary })
-    }
-    await runConcurrent(signingWork, concurrency, async (work) => {
-      await signer(work.temporaryPath, `${appId}.seed.${work.file.digest.slice(0, 32)}`)
-    })
-    for (const work of signingWork) {
-      const signedBody = readFileSync(work.temporaryPath)
-      if (!isMachO(work.temporaryPath)) {
-        throw new Error(`desktop seed signing: signer produced non-Mach-O content for ${work.file.path}`)
-      }
-      const signedDigest = createHash('sha512').update(signedBody).digest('hex')
-      const mode = work.file.executable ? 0o755 : 0o644
-      const destination = signedCasPath(versionRoot, signedDigest, work.file.executable)
-      writeCasFile(destination, signedBody, mode)
-      const checkedAt = Date.now()
-      for (const reference of work.references) {
-        reference.record.checkedAt = checkedAt
-        reference.record.digest = signedDigest
-        reference.record.mode = mode
-        reference.record.size = signedBody.length
-        reference.row.changed = true
-      }
-      if (destination !== work.file.path) obsoleteFiles.add(work.file.path)
-    }
-    const changedRows = rows.filter(row => row.changed)
-    database.exec('BEGIN IMMEDIATE')
-    let committed = false
-    try {
-      const statement = database.prepare('INSERT OR REPLACE INTO package_index (key, data) VALUES (?, ?)')
-      for (const row of changedRows) statement.run(row.key, packr.pack(row.value))
-      database.exec('COMMIT')
-      committed = true
-    } finally {
-      if (!committed) database.exec('ROLLBACK')
-    }
-    for (const path of obsoleteFiles) unlinkSync(path)
-    database.exec('VACUUM')
-    return { signedFiles: signingWork.length, prunedOrphans, updatedIndexRows: changedRows.length }
-  } finally {
-    database.close()
-    rmSync(workRoot, { recursive: true, force: true })
-  }
-}
-
-/**
- * Replace every Mach-O CAS object with a Developer ID signed object and update pnpm's SHA-512 index.
- * A signer rejection leaves the original CAS objects and package index unchanged.
- * @param storeRoot - Loose pnpm store prepared for the packaged seed.
- * @param appId - Electron application ID used as the signing identifier prefix.
- * @param expected - Company Developer ID identity and Team ID.
- * @param options - Optional signer and worker bound used by focused tests.
- * @returns Counts for release diagnostics after every signer completes and the index transaction commits.
- */
-export async function signMacOSSeedStore(
-  storeRoot: string,
-  appId: string,
-  expected: MacOSSigningEnvironment,
-  options: MacOSSeedStoreSigningOptions = {},
-): Promise<MacOSSeedStoreSigningResult> {
-  const roots = versionRoots(storeRoot)
-  if (roots.length === 0) throw new Error(`desktop seed signing: no pnpm store versions found in ${storeRoot}`)
-  const concurrency = options.concurrency ?? Math.min(MAX_CONCURRENT_CODE_SIGNERS, availableParallelism())
-  if (!Number.isSafeInteger(concurrency) || concurrency < 1) {
-    throw new Error(`desktop seed signing: concurrency must be a positive integer; received ${String(concurrency)}`)
-  }
-  const signer = options.signer ?? (async (path, identifier) => {
-    await signMacOSSeedCode(path, identifier, expected)
-  })
-  const results: MacOSSeedStoreSigningResult[] = []
-  for (const root of roots) results.push(await rewriteVersionStore(root, appId, signer, concurrency))
-  return results.reduce((total, current) => ({
-    signedFiles: total.signedFiles + current.signedFiles,
-    prunedOrphans: total.prunedOrphans + current.prunedOrphans,
-    updatedIndexRows: total.updatedIndexRows + current.updatedIndexRows,
-  }), { signedFiles: 0, prunedOrphans: 0, updatedIndexRows: 0 })
-}
-
-/**
- * Verify that every Mach-O CAS object has the expected Developer ID, timestamp, and hardened runtime.
- * @param storeRoot - Loose or extracted pnpm store.
- * @param expected - Company Developer ID identity and Team ID.
- * @param verifier - Injectable signature verifier used by focused tests.
- * @returns Number of verified Mach-O files.
- */
-export function verifyMacOSSeedStore(
-  storeRoot: string,
-  expected: MacOSSigningEnvironment,
-  verifier: MacOSSeedCodeVerifier = (path) => { verifyMacOSSeedCode(path, expected) },
-): number {
-  let count = 0
-  for (const root of versionRoots(storeRoot)) {
-    for (const file of casFiles(root)) {
-      verifier(file.path)
-      count += 1
-    }
-  }
-  return count
-}

+ 2 - 2
apps/desktop/scripts/package-target.ts

@@ -1,4 +1,4 @@
-/** Build one release target with matching Electron, Node.js, and seed architecture. */
+/** Build one release target with matching Electron, Node.js, and dsh architecture. */
 
 import { spawn } from 'node:child_process'
 import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
@@ -276,7 +276,7 @@ async function main(): Promise<void> {
   ], buildEnv, REPOSITORY_ROOT)
   await runPnpm(['run', 'prepare:runtime'], targetEnv)
   await runPnpm(['run', 'prepare:packages'], targetEnv)
-  await runPnpm(['run', 'prepare:seed'], targetEnv)
+  await runPnpm(['run', 'prepare:dsh'], targetEnv)
   if (invocation.prepareOnly) return
   await runPnpm(desktopElectronBuilderArguments(target, invocation.directory), electronBuilderEnv)
   if (!invocation.directory) writeReleaseRecord(target, electronBuilderEnv, buildPaths.artifacts)

+ 150 - 0
apps/desktop/scripts/prepare-dsh.ts

@@ -0,0 +1,150 @@
+/** Materialize the complete production runtime before publishing Desktop resources. */
+
+import { spawn } from 'node:child_process'
+import { copyFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { delimiter, dirname, join, resolve } from 'node:path'
+import { createRuntimeProjectMetadata } from '../src/project-manager.ts'
+import { DESKTOP_HOST_PROTOCOL_VERSION } from '../src/host-protocol.ts'
+import { parseDesktopRelease, type DesktopRelease } from '../src/release.ts'
+import {
+  DESKTOP_HOST_PACKAGE,
+  DESKTOP_HOST_RUNTIME_FILES,
+  DESKTOP_PACKAGES_DIR,
+  DESKTOP_PACKAGE_SET_FILE,
+  readDesktopCorePackageSet,
+  verifyDesktopCoreLockfile,
+} from '../src/core-package-set.ts'
+import { smokeDesktopRuntime } from './smoke-runtime.ts'
+import { writeDesktopRuntime, verifyDesktopRuntime } from '../src/runtime-tree.ts'
+import {
+  resolveDesktopAppId,
+  resolveMacOSSigningEnvironment,
+} from './desktop-release-environment.mjs'
+import {
+  signMacOSRuntime,
+} from './macos-runtime.ts'
+import { resolveDesktopBuildTarget, resolveDesktopTargetBuildPaths } from './desktop-build-paths.mjs'
+
+const APP_ROOT = resolve(import.meta.dirname, '..')
+const BUILD_PATHS = resolveDesktopTargetBuildPaths()
+const DSH_OUTPUT_ROOT = BUILD_PATHS.dsh
+const BUILD_ROOT = mkdtempSync(join(tmpdir(), 'dsh-desktop-runtime-'))
+const STORE_ROOT = join(BUILD_ROOT, 'store')
+const RUNTIME_ROOT = BUILD_PATHS.runtime
+const PNPM_BUILD_STATE = BUILD_PATHS.dshPnpm
+const PACKAGE_SET_ROOT = BUILD_PATHS.packageSet
+const NODE = join(RUNTIME_ROOT, 'node', process.platform === 'win32' ? 'node.exe' : 'node')
+const PNPM = join(RUNTIME_ROOT, 'pnpm', 'bin', 'pnpm.mjs')
+
+function manifestVersion(path: string, subject: string): string {
+  const manifest = JSON.parse(readFileSync(path, 'utf8')) as { version?: unknown }
+  if (typeof manifest.version !== 'string') throw new Error(`desktop runtime: ${subject} has no version`)
+  return manifest.version
+}
+
+function desktopRelease(): DesktopRelease {
+  const version = manifestVersion(join(APP_ROOT, 'package.json'), 'desktop package')
+  const dshVersion = manifestVersion(resolve(APP_ROOT, '..', '..', 'package.json'), 'root dsh package')
+  if (version !== dshVersion) {
+    throw new Error(`desktop runtime: Electron ${version} must bind the same version of @deepseek-ai/dsh, found ${dshVersion}`)
+  }
+  const runtime = JSON.parse(readFileSync(join(RUNTIME_ROOT, 'versions.json'), 'utf8')) as Record<string, unknown>
+  return parseDesktopRelease({
+    schemaVersion: 1,
+    version,
+    hostProtocolVersion: DESKTOP_HOST_PROTOCOL_VERSION,
+    nodeVersion: runtime.node,
+    pnpmVersion: runtime.pnpm,
+  })
+}
+
+function runPnpm(args: readonly string[]): Promise<void> {
+  return new Promise((resolvePromise, reject) => {
+    const [command, ...commandArgs] = args
+    if (command === undefined) throw new Error('desktop runtime: pnpm command is required')
+    const config = join(PNPM_BUILD_STATE, 'config')
+    const userConfig = join(config, 'npmrc')
+    mkdirSync(config, { recursive: true })
+    writeFileSync(userConfig, '')
+    const child = spawn(NODE, [
+      PNPM,
+      '--config.registry=https://registry.npmjs.org/',
+      `--config.store-dir=${STORE_ROOT}`,
+      '--config.enable-global-virtual-store=false',
+      `--config.userconfig=${userConfig}`,
+      command,
+      ...commandArgs,
+    ], {
+      cwd: BUILD_ROOT,
+      env: {
+        ...Object.fromEntries(Object.entries(process.env).filter(([name]) => (
+          name !== 'NODE_OPTIONS' && name !== 'NODE_PATH' && !/^DSH_DESKTOP_/u.test(name) && !/^(?:npm|pnpm|corepack)_/iu.test(name)
+        ))),
+        NPM_CONFIG_REGISTRY: 'https://registry.npmjs.org/',
+        NPM_CONFIG_STORE_DIR: STORE_ROOT,
+        NPM_CONFIG_USERCONFIG: userConfig,
+        PATH: `${dirname(NODE)}${delimiter}${process.env.PATH ?? ''}`,
+        XDG_CACHE_HOME: join(PNPM_BUILD_STATE, 'cache'),
+        XDG_CONFIG_HOME: config,
+        XDG_STATE_HOME: join(PNPM_BUILD_STATE, 'state'),
+      },
+      stdio: 'inherit',
+    })
+    child.once('error', reject)
+    child.once('close', (code, signal) => {
+      if (code === 0) resolvePromise()
+      else reject(new Error(`desktop runtime: pnpm exited with ${String(code ?? signal)}`))
+    })
+  })
+}
+
+async function main(): Promise<void> {
+  rmSync(DSH_OUTPUT_ROOT, { recursive: true, force: true })
+  rmSync(PNPM_BUILD_STATE, { recursive: true, force: true })
+  mkdirSync(STORE_ROOT, { recursive: true })
+  try {
+    const release = desktopRelease()
+    copyFileSync(join(PACKAGE_SET_ROOT, DESKTOP_PACKAGE_SET_FILE), join(BUILD_ROOT, DESKTOP_PACKAGE_SET_FILE))
+    cpSync(join(PACKAGE_SET_ROOT, DESKTOP_PACKAGES_DIR), join(BUILD_ROOT, DESKTOP_PACKAGES_DIR), { recursive: true })
+    createRuntimeProjectMetadata(BUILD_ROOT, release)
+    await runPnpm(['install', '--lockfile-only'])
+    verifyDesktopCoreLockfile(
+      readFileSync(join(BUILD_ROOT, 'pnpm-lock.yaml'), 'utf8'),
+      readDesktopCorePackageSet(BUILD_ROOT, release.version),
+    )
+    await runPnpm(['install', '--prod', '--frozen-lockfile', '--trust-lockfile'])
+    const packageSet = readDesktopCorePackageSet(BUILD_ROOT, release.version)
+    mkdirSync(DSH_OUTPUT_ROOT, { recursive: true })
+    cpSync(join(BUILD_ROOT, 'node_modules'), join(DSH_OUTPUT_ROOT, 'node_modules'), {
+      recursive: true, dereference: true,
+      filter: source => !source.split(/[\\/]/u).some(part => part === '.bin' || part === '.pnpm' || part === '.modules.yaml' || part === '.pnpm-workspace-state-v1.json'),
+    })
+    writeFileSync(join(DSH_OUTPUT_ROOT, 'package.json'), `${JSON.stringify({
+      name: '@deepseek-ai/dsh-desktop-runtime', private: true, version: release.version, type: 'module',
+      dependencies: Object.fromEntries(packageSet.packages.map(entry => [entry.name, entry.version])),
+    }, undefined, 2)}\n`)
+    for (const file of DESKTOP_HOST_RUNTIME_FILES) {
+      if (!existsSync(join(DSH_OUTPUT_ROOT, 'node_modules', DESKTOP_HOST_PACKAGE, file))) {
+        throw new Error(`desktop runtime: missing private Host file ${file}`)
+      }
+    }
+    if (process.platform === 'darwin') {
+      await signMacOSRuntime(DSH_OUTPUT_ROOT, resolveDesktopAppId(process.env), resolveMacOSSigningEnvironment(process.env))
+    }
+    const targetName = resolveDesktopBuildTarget()
+    const target = { platform: process.platform, arch: targetName.endsWith('arm64') ? 'arm64' : 'x64' }
+    writeDesktopRuntime(DSH_OUTPUT_ROOT, release, packageSet.packages.map(entry => entry.name), target)
+    const descriptor = verifyDesktopRuntime(DSH_OUTPUT_ROOT, release.version, target)
+    await smokeDesktopRuntime(DSH_OUTPUT_ROOT, NODE, descriptor)
+    verifyDesktopRuntime(DSH_OUTPUT_ROOT, release.version, target)
+  } catch (error) {
+    rmSync(DSH_OUTPUT_ROOT, { recursive: true, force: true })
+    throw error
+  } finally {
+    rmSync(BUILD_ROOT, { recursive: true, force: true })
+    rmSync(PNPM_BUILD_STATE, { recursive: true, force: true })
+  }
+}
+
+await main()

+ 0 - 200
apps/desktop/scripts/prepare-seed.ts

@@ -1,200 +0,0 @@
-/** Build the release seed through the same embedded pnpm used on first launch. */
-
-import { spawn } from 'node:child_process'
-import { createHash } from 'node:crypto'
-import { copyFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
-import { tmpdir } from 'node:os'
-import { delimiter, dirname, join, relative, resolve, sep } from 'node:path'
-import { createSeedMetadata } from '../src/project-manager.ts'
-import { DESKTOP_HOST_PROTOCOL_VERSION } from '../src/host-protocol.ts'
-import { parseDesktopRelease, type DesktopRelease } from '../src/release.ts'
-import {
-  DESKTOP_HOST_PACKAGE,
-  DESKTOP_HOST_RUNTIME_FILES,
-  DESKTOP_PACKAGES_DIR,
-  DESKTOP_PACKAGE_SET_FILE,
-  readDesktopCorePackageSet,
-  verifyDesktopCoreLockfile,
-} from '../src/core-package-set.ts'
-import {
-  archivePnpmStore,
-  extractPnpmStoreArchives,
-  removePnpmProjectRegistrations,
-} from '../src/seed-store.ts'
-import {
-  resolveDesktopAppId,
-  resolveMacOSSigningEnvironment,
-} from './desktop-release-environment.mjs'
-import {
-  signMacOSSeedStore,
-  verifyMacOSSeedStore,
-} from './macos-seed-store.ts'
-import { resolveDesktopTargetBuildPaths } from './desktop-build-paths.mjs'
-
-const APP_ROOT = resolve(import.meta.dirname, '..')
-const BUILD_PATHS = resolveDesktopTargetBuildPaths()
-const SEED_OUTPUT_ROOT = BUILD_PATHS.seed
-const SEED_ROOT = mkdtempSync(join(tmpdir(), 'dsh-desktop-seed-'))
-const STORE_ROOT = join(SEED_ROOT, 'store')
-const RUNTIME_ROOT = BUILD_PATHS.runtime
-const PNPM_BUILD_STATE = BUILD_PATHS.seedPnpm
-const PACKAGE_SET_ROOT = BUILD_PATHS.packageSet
-const NODE = join(RUNTIME_ROOT, 'node', process.platform === 'win32' ? 'node.exe' : 'node')
-const PNPM = join(RUNTIME_ROOT, 'pnpm', 'bin', 'pnpm.mjs')
-
-function manifestVersion(path: string, subject: string): string {
-  const manifest = JSON.parse(readFileSync(path, 'utf8')) as { version?: unknown }
-  if (typeof manifest.version !== 'string') throw new Error(`desktop seed: ${subject} has no version`)
-  return manifest.version
-}
-
-function desktopRelease(): DesktopRelease {
-  const version = manifestVersion(join(APP_ROOT, 'package.json'), 'desktop package')
-  const dshVersion = manifestVersion(resolve(APP_ROOT, '..', '..', 'package.json'), 'root dsh package')
-  if (version !== dshVersion) {
-    throw new Error(`desktop seed: Electron ${version} must bind the same version of @deepseek-ai/dsh, found ${dshVersion}`)
-  }
-  const runtime = JSON.parse(readFileSync(join(RUNTIME_ROOT, 'versions.json'), 'utf8')) as Record<string, unknown>
-  return parseDesktopRelease({
-    schemaVersion: 1,
-    version,
-    hostProtocolVersion: DESKTOP_HOST_PROTOCOL_VERSION,
-    nodeVersion: runtime.node,
-    pnpmVersion: runtime.pnpm,
-  })
-}
-
-function runPnpm(args: readonly string[]): Promise<void> {
-  return new Promise((resolvePromise, reject) => {
-    const [command, ...commandArgs] = args
-    if (command === undefined) throw new Error('desktop seed: pnpm command is required')
-    const config = join(PNPM_BUILD_STATE, 'config')
-    const userConfig = join(config, 'npmrc')
-    mkdirSync(config, { recursive: true })
-    writeFileSync(userConfig, '')
-    const child = spawn(NODE, [
-      PNPM,
-      '--config.registry=https://registry.npmjs.org/',
-      `--config.store-dir=${STORE_ROOT}`,
-      '--config.enable-global-virtual-store=false',
-      `--config.userconfig=${userConfig}`,
-      command,
-      ...commandArgs,
-    ], {
-      cwd: SEED_ROOT,
-      env: {
-        ...Object.fromEntries(Object.entries(process.env).filter(([name]) => (
-          !/^DSH_DESKTOP_/u.test(name) && !/^(?:npm|pnpm|corepack)_/iu.test(name)
-        ))),
-        NPM_CONFIG_REGISTRY: 'https://registry.npmjs.org/',
-        NPM_CONFIG_STORE_DIR: STORE_ROOT,
-        NPM_CONFIG_USERCONFIG: userConfig,
-        PATH: `${dirname(NODE)}${delimiter}${process.env.PATH ?? ''}`,
-        XDG_CACHE_HOME: join(PNPM_BUILD_STATE, 'cache'),
-        XDG_CONFIG_HOME: config,
-        XDG_STATE_HOME: join(PNPM_BUILD_STATE, 'state'),
-      },
-      stdio: 'inherit',
-    })
-    child.once('error', reject)
-    child.once('close', (code, signal) => {
-      if (code === 0) resolvePromise()
-      else reject(new Error(`desktop seed: pnpm exited with ${String(code ?? signal)}`))
-    })
-  })
-}
-
-function inventory(root: string): readonly { path: string; bytes: number; sha256: string }[] {
-  const files: string[] = []
-  const visit = (dir: string): void => {
-    for (const entry of readdirSync(dir, { withFileTypes: true })) {
-      const path = join(dir, entry.name)
-      if (entry.isDirectory()) visit(path)
-      else if (entry.isFile()) files.push(path)
-      else throw new Error(`desktop seed: unsupported filesystem entry ${relative(root, path)}`)
-    }
-  }
-  visit(root)
-  return files.sort().map((path) => {
-    const body = readFileSync(path)
-    return {
-      path: relative(root, path).split(sep).join('/'),
-      bytes: statSync(path).size,
-      sha256: createHash('sha256').update(body).digest('hex'),
-    }
-  })
-}
-
-async function verifyOfflineInstallation(release: DesktopRelease): Promise<void> {
-  const installedModules = join(SEED_ROOT, 'node_modules')
-  try {
-    await runPnpm(['install', '--offline', '--frozen-lockfile', '--trust-lockfile'])
-    const hostRoot = join(installedModules, ...DESKTOP_HOST_PACKAGE.split('/'))
-    for (const file of DESKTOP_HOST_RUNTIME_FILES) {
-      if (!existsSync(join(hostRoot, file))) {
-        throw new Error(`desktop seed: local ${DESKTOP_HOST_PACKAGE}@${release.version} does not contain ${file}`)
-      }
-    }
-  } finally {
-    rmSync(installedModules, { recursive: true, force: true })
-  }
-}
-
-async function main(): Promise<void> {
-  rmSync(SEED_OUTPUT_ROOT, { recursive: true, force: true })
-  rmSync(PNPM_BUILD_STATE, { recursive: true, force: true })
-  mkdirSync(STORE_ROOT, { recursive: true })
-  try {
-    const release = desktopRelease()
-    copyFileSync(join(PACKAGE_SET_ROOT, DESKTOP_PACKAGE_SET_FILE), join(SEED_ROOT, DESKTOP_PACKAGE_SET_FILE))
-    cpSync(join(PACKAGE_SET_ROOT, DESKTOP_PACKAGES_DIR), join(SEED_ROOT, DESKTOP_PACKAGES_DIR), { recursive: true })
-    createSeedMetadata(SEED_ROOT, release)
-    await runPnpm(['install', '--lockfile-only'])
-    verifyDesktopCoreLockfile(
-      readFileSync(join(SEED_ROOT, 'pnpm-lock.yaml'), 'utf8'),
-      readDesktopCorePackageSet(SEED_ROOT, release.version),
-    )
-    const installedModules = join(SEED_ROOT, 'node_modules')
-    await runPnpm(['install', '--prod', '--frozen-lockfile', '--trust-lockfile', '--ignore-scripts'])
-    rmSync(installedModules, { recursive: true, force: true })
-    rmSync(PNPM_BUILD_STATE, { recursive: true, force: true })
-    await verifyOfflineInstallation(release)
-    const targetPlatform = process.env.DSH_DESKTOP_TARGET_PLATFORM ?? process.platform
-    let signedMachOFiles: number | undefined
-    let macOSSigning: ReturnType<typeof resolveMacOSSigningEnvironment> | undefined
-    if (targetPlatform === 'darwin') {
-      macOSSigning = resolveMacOSSigningEnvironment(process.env)
-      const signing = await signMacOSSeedStore(
-        STORE_ROOT,
-        resolveDesktopAppId(process.env),
-        macOSSigning,
-      )
-      signedMachOFiles = signing.signedFiles
-      process.stdout.write(
-        `desktop seed: signed ${signing.signedFiles} Mach-O files, updated ${signing.updatedIndexRows} pnpm index records, and pruned ${signing.prunedOrphans} native orphans\n`,
-      )
-      await verifyOfflineInstallation(release)
-    }
-    removePnpmProjectRegistrations(STORE_ROOT)
-    archivePnpmStore(SEED_ROOT, STORE_ROOT)
-    if (macOSSigning !== undefined && signedMachOFiles !== undefined) {
-      const extractedStore = mkdtempSync(join(tmpdir(), 'dsh-desktop-seed-verification-'))
-      try {
-        extractPnpmStoreArchives(SEED_ROOT, extractedStore)
-        const verified = verifyMacOSSeedStore(extractedStore, macOSSigning)
-        if (verified !== signedMachOFiles) {
-          throw new Error(`desktop seed: archived store contains ${verified} signed Mach-O files; expected ${signedMachOFiles}`)
-        }
-      } finally {
-        rmSync(extractedStore, { recursive: true, force: true })
-      }
-    }
-    const records = inventory(SEED_ROOT).filter(entry => entry.path !== 'integrity.json')
-    writeFileSync(join(SEED_ROOT, 'integrity.json'), `${JSON.stringify({ schemaVersion: 2, files: records }, undefined, 2)}\n`)
-    cpSync(SEED_ROOT, SEED_OUTPUT_ROOT, { recursive: true })
-  } finally {
-    rmSync(SEED_ROOT, { recursive: true, force: true })
-  }
-}
-
-await main()

+ 58 - 0
apps/desktop/scripts/smoke-runtime.ts

@@ -0,0 +1,58 @@
+/** Boot the materialized target runtime without access to a user's Harness profile. */
+
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { DesktopHostProcess } from '../src/host-process.ts'
+import { createPluginProfile } from '../src/project-manager.ts'
+import { linkDesktopHostPackages, validateDesktopPluginGraph } from '../src/profile-packages.ts'
+import type { DesktopRuntimeDescriptor } from '../src/runtime-tree.ts'
+
+/**
+ * Prove the final resource tree boots and serves its matching Web frontend.
+ * @param root - Materialized dsh resources.
+ * @param node - Prepared target Node executable.
+ * @param runtime - Verified resource descriptor.
+ */
+export async function smokeDesktopRuntime(root: string, node: string, runtime: DesktopRuntimeDescriptor): Promise<void> {
+  const home = mkdtempSync(join(tmpdir(), 'dsh-desktop-smoke-'))
+  const profile = join(home, 'profiles', 'desktop')
+  const host = new DesktopHostProcess(node, root, profile, undefined, { ...process.env, DSH_HOME: home })
+  try {
+    createPluginProfile(profile)
+    const pluginName = 'desktop-runtime-smoke-plugin'
+    const plugin = join(profile, 'node_modules', pluginName)
+    mkdirSync(plugin, { recursive: true })
+    const cordis = runtime.sharedPackages.find(entry => entry.name === '@deepseek-ai/cordis')
+    if (cordis === undefined) throw new Error('desktop runtime: missing shared Cordis package')
+    writeFileSync(join(plugin, 'package.json'), JSON.stringify({
+      name: pluginName, version: '1.0.0', type: 'module', exports: './index.js',
+      peerDependencies: { '@deepseek-ai/cordis': cordis.version }, dsh: { bundle: { patch: './bundle.yml' } },
+    }))
+    writeFileSync(join(plugin, 'index.js'), `
+import { Context } from '@deepseek-ai/cordis'
+export function apply(ctx) {
+  if (!(ctx instanceof Context)) throw new Error('desktop runtime: external plugin loaded another Cordis instance')
+}
+`)
+    writeFileSync(join(plugin, 'bundle.yml'), '- insert:\n    - id: desktop-runtime-smoke-plugin\n      name: desktop-runtime-smoke-plugin\n')
+    const manifest = JSON.parse(readFileSync(join(profile, 'package.json'), 'utf8')) as {
+      dependencies: Record<string, string>
+      dsh: { profile: { bundles: string[] } }
+    }
+    manifest.dependencies[pluginName] = '1.0.0'
+    manifest.dsh.profile.bundles.push(pluginName)
+    writeFileSync(join(profile, 'package.json'), JSON.stringify(manifest))
+    linkDesktopHostPackages(profile, root, runtime)
+    validateDesktopPluginGraph(profile, root, runtime, [pluginName])
+    const ready = await host.start()
+    if (ready.dshVersion !== runtime.release.version) throw new Error('desktop runtime: Host reported another dsh release')
+    const response = await host.fetch(new Request('dsh-app://app/'))
+    if (response.status !== 200 || !(await response.text()).includes('<html')) {
+      throw new Error('desktop runtime: packaged frontend smoke failed')
+    }
+  } finally {
+    await host.stop()
+    rmSync(home, { recursive: true, force: true })
+  }
+}

+ 6 - 6
apps/desktop/scripts/verify-macos-signature.d.mts

@@ -8,31 +8,31 @@ import type { MacOSSigningEnvironment } from './desktop-release-environment.mjs'
 export function assertMacOSSignatureDetails(details: string, expected: MacOSSigningEnvironment): void
 
 /**
- * Require the signature properties Apple validates for executable seed content.
+ * Require the signature properties Apple validates for executable runtime content.
  * @param details - Output from `codesign --display --verbose=4`.
  * @param expected - Public release identity.
  */
-export function assertMacOSSeedSignatureDetails(details: string, expected: MacOSSigningEnvironment): void
+export function assertMacOSRuntimeSignatureDetails(details: string, expected: MacOSSigningEnvironment): void
 
 /**
- * Sign one Mach-O file embedded in the seed store.
+ * Sign one Mach-O file embedded in the runtime tree.
  * @param path - Writable standalone Mach-O file.
  * @param identifier - Stable code-signing identifier derived from the release app ID and CAS digest.
  * @param expected - Public release identity.
  * @returns Resolves after codesign exits successfully.
  */
-export function signMacOSSeedCode(
+export function signMacOSRuntimeCode(
   path: string,
   identifier: string,
   expected: MacOSSigningEnvironment,
 ): Promise<void>
 
 /**
- * Verify one Mach-O file embedded in the seed store.
+ * Verify one Mach-O file embedded in the runtime tree.
  * @param path - Mach-O file to inspect.
  * @param expected - Public release identity.
  */
-export function verifyMacOSSeedCode(path: string, expected: MacOSSigningEnvironment): void
+export function verifyMacOSRuntimeCode(path: string, expected: MacOSSigningEnvironment): void
 
 /**
  * Verify the full application signature and its release owner.

+ 11 - 11
apps/desktop/scripts/verify-macos-signature.mjs

@@ -1,4 +1,4 @@
-/** Sign seed code and verify that packaged macOS artifacts carry the company release identity. */
+/** Sign runtime code and verify that packaged macOS artifacts carry the company release identity. */
 
 import { spawn, spawnSync } from 'node:child_process'
 import { resolve } from 'node:path'
@@ -21,19 +21,19 @@ export function assertMacOSSignatureDetails(details, expected) {
 }
 
 /**
- * Require the signature properties Apple validates for executable seed content.
+ * Require the signature properties Apple validates for executable runtime content.
  * @param {string} details - Output from `codesign --display --verbose=4`.
  * @param {{ signingIdentity: string, teamId: string }} expected - Public release identity.
  * @returns {void}
  */
-export function assertMacOSSeedSignatureDetails(details, expected) {
+export function assertMacOSRuntimeSignatureDetails(details, expected) {
   assertMacOSSignatureDetails(details, expected)
   const fields = details.split(/\r?\n/u).map(line => line.trim())
   if (!fields.some(line => /^Timestamp=.+/u.test(line))) {
-    throw new Error('desktop macOS signing: seed signature has no secure timestamp')
+    throw new Error('desktop macOS signing: runtime signature has no secure timestamp')
   }
   if (!fields.some(line => /\bflags=0x[0-9a-f]+\(runtime\)(?:\s|$)/iu.test(line))) {
-    throw new Error('desktop macOS signing: seed signature does not enable hardened runtime')
+    throw new Error('desktop macOS signing: runtime signature does not enable hardened runtime')
   }
 }
 
@@ -60,7 +60,7 @@ function runAppleCommand(command, args, label) {
 }
 
 /**
- * Execute one Apple release tool without blocking other independent seed signers.
+ * Execute one Apple release tool without blocking other independent runtime signers.
  * @param {string} command - Absolute executable path.
  * @param {readonly string[]} args - Tool arguments.
  * @param {string} label - Stable diagnostic name.
@@ -106,13 +106,13 @@ function runCodeSign(args) {
 }
 
 /**
- * Sign one Mach-O file embedded in the seed store.
+ * Sign one Mach-O file embedded in the runtime tree.
  * @param {string} path - Writable standalone Mach-O file.
  * @param {string} identifier - Stable code-signing identifier derived from the release app ID and CAS digest.
  * @param {{ signingIdentity: string, teamId: string }} expected - Public release identity.
  * @returns {Promise<void>} Resolves after codesign exits successfully.
  */
-export async function signMacOSSeedCode(path, identifier, expected) {
+export async function signMacOSRuntimeCode(path, identifier, expected) {
   await runAppleCommandAsync('/usr/bin/codesign', [
     '--force',
     '--sign', expected.signingIdentity,
@@ -124,15 +124,15 @@ export async function signMacOSSeedCode(path, identifier, expected) {
 }
 
 /**
- * Verify one Mach-O file embedded in the seed store.
+ * Verify one Mach-O file embedded in the runtime tree.
  * @param {string} path - Mach-O file to inspect.
  * @param {{ signingIdentity: string, teamId: string }} expected - Public release identity.
  * @returns {void}
  */
-export function verifyMacOSSeedCode(path, expected) {
+export function verifyMacOSRuntimeCode(path, expected) {
   runCodeSign(['--verify', '--strict', '--verbose=2', path])
   const details = runCodeSign(['--display', '--verbose=4', path])
-  assertMacOSSeedSignatureDetails(details, expected)
+  assertMacOSRuntimeSignatureDetails(details, expected)
 }
 
 /**

+ 1 - 1
apps/desktop/src/core-package-set.ts

@@ -124,7 +124,7 @@ export function desktopDshPackageSpec(packageSet: DesktopCorePackageSet): string
 
 /**
  * Verify every local tarball and reject extra package files before pnpm executes them.
- * @param projectDir - Seed or profile directory containing the package set.
+ * @param projectDir - Build directory containing the package set.
  * @param expectedReleaseVersion - Exact dsh and Desktop Host version bound to Electron.
  * @returns The verified package set.
  */

+ 9 - 4
apps/desktop/src/host-process.ts

@@ -86,28 +86,33 @@ export class DesktopHostProcess {
 
   /**
    * @param node - absolute bundled upstream Node.js executable.
-   * @param projectDir - active or staged desktop npm project.
+   * @param runtimeDir - immutable packages carried by the current application.
+   * @param projectDir - active or staged desktop plugin profile.
    * @param inspectPort - optional loopback inspector port for workspace development.
+   * @param environment - Child environment; runtime and package-manager overrides are removed.
    */
   constructor(
     private readonly node: string,
+    private readonly runtimeDir: string,
     private readonly projectDir: string,
     private readonly inspectPort?: number,
+    private readonly environment: NodeJS.ProcessEnv = process.env,
   ) {}
 
   /** Start the child once and resolve only after its complete composition is active. */
   async start(): Promise<DesktopHostReady> {
     if (this.child !== undefined) return this.readyPromise
-    const entry = join(this.projectDir, 'node_modules', '@deepseek-ai', 'dsh-desktop-host', 'lib', 'index.js')
+    const entry = join(this.runtimeDir, 'node_modules', '@deepseek-ai', 'dsh-desktop-host', 'lib', 'index.js')
     const child = spawn(this.node, [
       ...(this.inspectPort === undefined ? [] : [`--inspect=127.0.0.1:${String(this.inspectPort)}`]),
       entry,
+      this.runtimeDir,
       this.projectDir,
       ...(this.inspectPort === undefined ? [] : ['--allow-linked-profile']),
     ], {
       cwd: this.projectDir,
-      env: Object.fromEntries(Object.entries(process.env).filter(([name]) => (
-        name !== 'NODE_OPTIONS' && !/^DSH_DESKTOP_/u.test(name) && !/^(?:npm|pnpm|corepack)_/iu.test(name)
+      env: Object.fromEntries(Object.entries(this.environment).filter(([name]) => (
+        name !== 'NODE_OPTIONS' && name !== 'NODE_PATH' && !/^DSH_DESKTOP_/u.test(name) && !/^(?:npm|pnpm|corepack)_/iu.test(name)
       ))),
       stdio: ['ignore', 'pipe', 'pipe', 'pipe', 'pipe', 'ipc'],
     })

+ 10 - 0
apps/desktop/src/ipc.ts

@@ -10,6 +10,10 @@ export const DESKTOP_IPC = {
   pluginsAdd: 'dsh-desktop:plugins-add',
   pluginsRemove: 'dsh-desktop:plugins-remove',
   pluginsUpdate: 'dsh-desktop:plugins-update',
+  pluginsToggle: 'dsh-desktop:plugins-toggle',
+  pluginsDisableAll: 'dsh-desktop:plugins-disable-all',
+  backendStatus: 'dsh-desktop:backend-status',
+  backendRetry: 'dsh-desktop:backend-retry',
   updatesCheck: 'dsh-desktop:updates-check',
   updatesInstall: 'dsh-desktop:updates-install',
   updatesState: 'dsh-desktop:updates-state',
@@ -31,6 +35,12 @@ export interface DshDesktopApi {
     add(spec: string): Promise<void>
     remove(name: string): Promise<void>
     update(name: string, version: string): Promise<void>
+    toggle(name: string, enabled: boolean): Promise<void>
+    disableAll(): Promise<void>
+  }
+  readonly backend: {
+    status(): Promise<{ readonly ready: boolean; readonly error?: string }>
+    retry(): Promise<void>
   }
   readonly updates: {
     check(): Promise<DesktopUpdateState>

+ 14 - 0
apps/desktop/src/locale.ts

@@ -20,6 +20,13 @@ export const en = {
   pluginWindowTitle: 'DeepSeek Harness — Desktop Plugins',
   pluginManagerDescription: 'Plugins are installed only in the Desktop node_modules and are managed by the bundled pnpm.',
   refresh: 'Refresh',
+  enable: 'Enable',
+  disable: 'Disable',
+  disabled: 'Disabled',
+  retry: 'Retry startup',
+  disableAll: 'Disable all plugins and retry',
+  recoveryDescription: 'The backend could not start. Update or disable incompatible plugins, then retry. Installed plugins and configuration are retained.',
+  changingActivation: 'Changing plugin activation…',
   npmPackage: 'npm package',
   install: 'Install',
   installed: 'Installed',
@@ -59,6 +66,13 @@ export const zh = {
   pluginWindowTitle: 'DeepSeek Harness — 桌面插件',
   pluginManagerDescription: '插件只安装到桌面端自己的 node_modules,并由内置 pnpm 管理。',
   refresh: '刷新',
+  enable: '启用',
+  disable: '禁用',
+  disabled: '已禁用',
+  retry: '重试启动',
+  disableAll: '禁用全部插件并重试',
+  recoveryDescription: '后端无法启动。请更新或禁用不兼容插件,然后重试。已安装插件和配置会保留。',
+  changingActivation: '正在更改插件启用状态…',
   npmPackage: 'npm 包',
   install: '安装',
   installed: '已安装',

+ 48 - 17
apps/desktop/src/main.ts

@@ -49,7 +49,7 @@ const MIME: Readonly<Record<string, string>> = {
 interface RuntimeResources {
   readonly node: string
   readonly pnpm: string
-  readonly seed: string
+  readonly dsh: string
 }
 
 function runtimeResources(): RuntimeResources {
@@ -58,8 +58,8 @@ function runtimeResources(): RuntimeResources {
     ?? join(process.resourcesPath, 'runtime', 'node', process.platform === 'win32' ? 'node.exe' : 'node')
   const pnpm = (development ? process.env.DSH_DESKTOP_PNPM_ENTRY : undefined)
     ?? join(process.resourcesPath, 'runtime', 'pnpm', 'bin', 'pnpm.mjs')
-  const seed = (development ? process.env.DSH_DESKTOP_SEED_DIR : undefined) ?? join(process.resourcesPath, 'seed')
-  return { node, pnpm, seed }
+  const dsh = (development ? process.env.DSH_DESKTOP_DSH_DIR : undefined) ?? join(process.resourcesPath, 'dsh')
+  return { node, pnpm, dsh }
 }
 
 function developmentProject(): string | undefined {
@@ -137,8 +137,8 @@ async function main(): Promise<void> {
   const activeProject = development ?? paths.profile
   const hostInspectPort = developmentHostInspectPort(development !== undefined)
   const manager = new DesktopProjectManager(paths, resources)
-  if (development === undefined) manager.recover()
   let host: DesktopHostProcess | undefined
+  let startupError: string | undefined
   let mainWindow: BrowserWindow | undefined
   let pluginWindow: BrowserWindow | undefined
   let shellInstallerOwnsQuit = false
@@ -157,9 +157,15 @@ async function main(): Promise<void> {
   }
 
   const startHost = async (projectDir = activeProject): Promise<DesktopHostProcess> => {
-    const next = new DesktopHostProcess(resources.node, projectDir, hostInspectPort)
-    await next.start()
-    return next
+    if (development === undefined) manager.assertProfileRuntime(projectDir)
+    const next = new DesktopHostProcess(resources.node, development ?? resources.dsh, projectDir, hostInspectPort)
+    try {
+      await next.start()
+      return next
+    } catch (error) {
+      await next.stop()
+      throw error
+    }
   }
   const hooks: DesktopProjectHooks = {
     healthCheck: async (projectDir) => {
@@ -202,14 +208,18 @@ async function main(): Promise<void> {
     },
   }
 
-  if (development === undefined) {
-    await manager.applyRelease(resources.seed, app.getVersion(), {
-      ...hooks,
-      beforeActivate: async () => {},
-      afterActivate: async () => {},
-    })
+  const reconcileBackend = async (): Promise<void> => {
+    try {
+      if (development === undefined) {
+        await manager.applyRelease(app.getVersion(), { ...hooks, beforeActivate: async () => {}, afterActivate: async () => {} })
+      }
+      host = await startHost()
+      startupError = undefined
+    } catch (error) {
+      startupError = errorOf(error, messages.startupFailed).message
+      throw error
+    }
   }
-  host = await startHost()
 
   const updates = new DesktopUpdateCoordinator(
     publishUpdate,
@@ -236,7 +246,9 @@ async function main(): Promise<void> {
       throw new Error('dsh desktop: plugin package changes require a packaged application')
     }
     await manager.mutate(mutation, hooks)
+    startupError = undefined
     if (mainWindow !== undefined && !mainWindow.isDestroyed()) mainWindow.webContents.reload()
+    else focusPrimaryWindow()
   }
   ipcMain.handle(DESKTOP_IPC.localeGet, (event) => {
     assertDesktopSender(event, ['shell'])
@@ -261,6 +273,20 @@ async function main(): Promise<void> {
     }
     return mutate(event, { type: 'plugin-update', name, version })
   })
+  ipcMain.handle(DESKTOP_IPC.pluginsToggle, (event, name: unknown, enabled: unknown) => {
+    if (typeof name !== 'string' || typeof enabled !== 'boolean') throw new Error('dsh desktop: invalid plugin activation request')
+    return mutate(event, { type: 'plugin-toggle', name, enabled })
+  })
+  ipcMain.handle(DESKTOP_IPC.pluginsDisableAll, event => mutate(event, { type: 'plugins-disable-all' }))
+  ipcMain.handle(DESKTOP_IPC.backendStatus, (event) => {
+    assertDesktopSender(event, ['shell'])
+    return { ready: host !== undefined, ...(startupError === undefined ? {} : { error: startupError }) }
+  })
+  ipcMain.handle(DESKTOP_IPC.backendRetry, async (event) => {
+    assertDesktopSender(event, ['shell'])
+    if (host === undefined) await reconcileBackend()
+    focusPrimaryWindow()
+  })
   ipcMain.handle(DESKTOP_IPC.updatesCheck, async (event) => {
     assertDesktopSender(event, ['shell'])
     return updates.check()
@@ -348,6 +374,7 @@ async function main(): Promise<void> {
     return window
   }
   focusPrimaryWindow = () => {
+    if (host === undefined) { openPluginWindow(); return }
     const window = mainWindow
     if (window === undefined || window.isDestroyed()) {
       const replacement = createMainWindow()
@@ -359,9 +386,13 @@ async function main(): Promise<void> {
     window.focus()
   }
 
-  mainWindow = createMainWindow()
-  await mainWindow.loadURL(`${SCHEME}://app/index.html`)
-  if (development !== undefined && process.env.DSH_DESKTOP_OPEN_DEVTOOLS !== '0') {
+  await reconcileBackend().catch(() => undefined)
+  if (host === undefined) openPluginWindow()
+  else {
+    mainWindow = createMainWindow()
+    await mainWindow.loadURL(`${SCHEME}://app/index.html`)
+  }
+  if (mainWindow !== undefined && development !== undefined && process.env.DSH_DESKTOP_OPEN_DEVTOOLS !== '0') {
     mainWindow.webContents.openDevTools({ mode: 'detach' })
   }
   publishUpdate(updateState)

+ 6 - 0
apps/desktop/src/preload.ts

@@ -10,8 +10,14 @@ const api: DshDesktopApi = {
     list: () => ipcRenderer.invoke(DESKTOP_IPC.pluginsList) as Promise<ReturnType<DshDesktopApi['plugins']['list']> extends Promise<infer T> ? T : never>,
     add: spec => ipcRenderer.invoke(DESKTOP_IPC.pluginsAdd, spec) as Promise<void>,
     remove: name => ipcRenderer.invoke(DESKTOP_IPC.pluginsRemove, name) as Promise<void>,
+    toggle: (name, enabled) => ipcRenderer.invoke(DESKTOP_IPC.pluginsToggle, name, enabled) as Promise<void>,
+    disableAll: () => ipcRenderer.invoke(DESKTOP_IPC.pluginsDisableAll) as Promise<void>,
     update: (name, version) => ipcRenderer.invoke(DESKTOP_IPC.pluginsUpdate, name, version) as Promise<void>,
   },
+  backend: {
+    status: () => ipcRenderer.invoke(DESKTOP_IPC.backendStatus) as ReturnType<DshDesktopApi['backend']['status']>,
+    retry: () => ipcRenderer.invoke(DESKTOP_IPC.backendRetry) as Promise<void>,
+  },
   updates: {
     check: () => ipcRenderer.invoke(DESKTOP_IPC.updatesCheck) as Promise<DesktopUpdateState>,
     install: () => ipcRenderer.invoke(DESKTOP_IPC.updatesInstall) as Promise<void>,

+ 254 - 0
apps/desktop/src/profile-packages.ts

@@ -0,0 +1,254 @@
+/** Desktop-owned host links and validation of the external plugin dependency graph. */
+
+import { createHash } from 'node:crypto'
+import { cpSync, existsSync, lstatSync, mkdirSync, readFileSync, readlinkSync, realpathSync, readdirSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs'
+import { createRequire } from 'node:module'
+import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
+import { satisfies } from 'semver'
+import { desktopRuntimeId, runtimePath, type DesktopRuntimeDescriptor } from './runtime-tree.ts'
+
+/** Applied runtime identity and the only links Desktop may replace. */
+export const DESKTOP_PROFILE_STATE = 'desktop-runtime-state.json'
+
+/** Durable ownership of a package-directory link. */
+export interface DesktopPackageLink {
+  readonly name: string
+  readonly target: string
+}
+
+/** Facts from the last successfully validated profile. */
+export interface DesktopProfileState {
+  readonly schemaVersion: 1
+  readonly runtimeId: string
+  readonly version: string
+  readonly nodeVersion: string
+  readonly platform: string
+  readonly arch: string
+  readonly lockHash: string
+  readonly links: readonly DesktopPackageLink[]
+}
+
+const PACKAGE_NAME = /^(?:@[a-z0-9][a-z0-9._~-]*\/[a-z0-9][a-z0-9._~-]*|[a-z0-9][a-z0-9._~-]*)$/u
+
+function record(value: unknown): value is Record<string, unknown> {
+  return typeof value === 'object' && value !== null && !Array.isArray(value)
+}
+
+function stat(path: string): ReturnType<typeof lstatSync> | undefined {
+  try { return lstatSync(path) } catch (error) {
+    if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
+    return undefined
+  }
+}
+
+function inside(root: string, path: string): boolean {
+  const child = relative(root, path)
+  return child === '' || (!isAbsolute(child) && child !== '..' && !child.startsWith(`..${sep}`))
+}
+
+/**
+ * Read profile state without interpreting an unpublished predecessor format.
+ * @param profile - Desktop profile directory.
+ * @returns Validated state, or undefined for an uninitialized profile.
+ */
+export function readDesktopProfileState(profile: string): DesktopProfileState | undefined {
+  const path = join(profile, DESKTOP_PROFILE_STATE)
+  if (!existsSync(path)) return undefined
+  const value: unknown = JSON.parse(readFileSync(path, 'utf8'))
+  if (!record(value) || value.schemaVersion !== 1 || typeof value.runtimeId !== 'string'
+    || !/^[a-f0-9]{64}$/u.test(value.runtimeId) || typeof value.version !== 'string'
+    || typeof value.nodeVersion !== 'string' || typeof value.platform !== 'string' || typeof value.arch !== 'string'
+    || typeof value.lockHash !== 'string' || !Array.isArray(value.links)) {
+    throw new Error('desktop profile: invalid runtime state')
+  }
+  const links = value.links.map((link: unknown): DesktopPackageLink => {
+    if (!record(link) || typeof link.name !== 'string' || !PACKAGE_NAME.test(link.name)
+      || typeof link.target !== 'string' || !isAbsolute(link.target)) {
+      throw new Error('desktop profile: invalid managed link')
+    }
+    return { name: link.name, target: link.target }
+  })
+  if (new Set(links.map(link => link.name)).size !== links.length) throw new Error('desktop profile: duplicate managed link')
+  return { schemaVersion: 1, runtimeId: value.runtimeId, version: value.version, nodeVersion: value.nodeVersion,
+    platform: value.platform, arch: value.arch, lockHash: value.lockHash, links }
+}
+
+/**
+ * Hash the plugin lockfile, including the empty-profile case.
+ * @param profile - Desktop profile directory.
+ * @returns Lockfile content identity.
+ */
+export function desktopPluginLockHash(profile: string): string {
+  const lock = join(profile, 'pnpm-lock.yaml')
+  return createHash('sha256').update(existsSync(lock) ? readFileSync(lock) : '').digest('hex')
+}
+
+/**
+ * Remove only recorded host links, without following even broken targets.
+ * @param profile - Active or copied profile.
+ */
+export function unlinkDesktopHostPackages(profile: string): void {
+  for (const link of readDesktopProfileState(profile)?.links ?? []) {
+    const path = join(profile, 'node_modules', link.name)
+    const entry = stat(path)
+    if (entry === undefined) continue
+    if (!entry.isSymbolicLink() || resolve(dirname(path), readlinkSync(path)) !== resolve(link.target)) {
+      throw new Error(`desktop profile: refusing to replace unowned package ${link.name}`)
+    }
+    unlinkSync(path)
+  }
+}
+
+/**
+ * Copy plugin files without copying host packages or sharing writable hardlinks.
+ * @param source - Active Desktop profile.
+ * @param target - Empty transaction profile directory.
+ */
+export function copyDesktopProfile(source: string, target: string): void {
+  const owned = readDesktopProfileState(source)?.links ?? []
+  for (const link of owned) {
+    const path = join(source, 'node_modules', link.name)
+    const entry = stat(path)
+    if (entry !== undefined && (!entry.isSymbolicLink() || resolve(dirname(path), readlinkSync(path)) !== resolve(link.target))) {
+      throw new Error(`desktop profile: refusing to copy unowned package ${link.name}`)
+    }
+  }
+  const links = new Set(owned.map(link => join(source, 'node_modules', link.name)))
+  cpSync(source, target, { recursive: true, verbatimSymlinks: true, force: false, errorOnExist: true,
+    filter: path => !links.has(path) })
+}
+
+/**
+ * Bind an external profile to this application's real package directories.
+ * @param profile - Candidate profile.
+ * @param root - Current immutable runtime directory.
+ * @param runtime - Verified release descriptor.
+ */
+export function linkDesktopHostPackages(profile: string, root: string, runtime: DesktopRuntimeDescriptor): void {
+  unlinkDesktopHostPackages(profile)
+  const links = runtime.sharedPackages.map(entry => ({ name: entry.name, target: runtimePath(root, entry.path) }))
+  for (const link of links) {
+    const path = join(profile, 'node_modules', link.name)
+    if (stat(path) !== undefined) throw new Error(`desktop profile: plugin installed reserved host package ${link.name}`)
+    mkdirSync(dirname(path), { recursive: true })
+    symlinkSync(link.target, path, process.platform === 'win32' ? 'junction' : 'dir')
+  }
+  const state: DesktopProfileState = { schemaVersion: 1, runtimeId: desktopRuntimeId(runtime), version: runtime.release.version,
+    nodeVersion: runtime.release.nodeVersion, platform: runtime.platform, arch: runtime.arch,
+    lockHash: desktopPluginLockHash(profile), links }
+  writeFileSync(join(profile, DESKTOP_PROFILE_STATE), `${JSON.stringify(state, undefined, 2)}\n`, { mode: 0o600 })
+}
+
+interface PackageManifest {
+  readonly name: string
+  readonly version: string
+  readonly dependencies: Readonly<Record<string, string>>
+  readonly optionalDependencies: Readonly<Record<string, string>>
+  readonly peerDependencies: Readonly<Record<string, string>>
+  readonly optionalPeers: ReadonlySet<string>
+}
+
+function manifest(path: string): PackageManifest {
+  const value: unknown = JSON.parse(readFileSync(join(path, 'package.json'), 'utf8'))
+  if (!record(value) || typeof value.name !== 'string' || typeof value.version !== 'string') {
+    throw new Error(`desktop profile: invalid package manifest ${path}`)
+  }
+  const dependencies = (key: string): Record<string, string> => {
+    const field = value[key]
+    if (field === undefined) return {}
+    if (!record(field) || Object.entries(field).some(([name, spec]) => !PACKAGE_NAME.test(name) || typeof spec !== 'string')) {
+      throw new Error(`desktop profile: invalid ${key} in ${path}`)
+    }
+    return field as Record<string, string>
+  }
+  const optionalPeers = new Set<string>()
+  if (record(value.peerDependenciesMeta)) {
+    for (const [name, meta] of Object.entries(value.peerDependenciesMeta)) {
+      if (record(meta) && meta.optional === true) optionalPeers.add(name)
+    }
+  }
+  return { name: value.name, version: value.version, dependencies: dependencies('dependencies'),
+    optionalDependencies: dependencies('optionalDependencies'), peerDependencies: dependencies('peerDependencies'), optionalPeers }
+}
+
+function packageFrom(anchor: string, name: string): string | undefined {
+  if (!PACKAGE_NAME.test(name)) throw new Error(`desktop profile: invalid package name ${name}`)
+  for (const modules of createRequire(join(anchor, 'package.json')).resolve.paths(name) ?? []) {
+    const path = join(modules, name)
+    if (existsSync(join(path, 'package.json'))) return realpathSync(path)
+  }
+  return undefined
+}
+
+/**
+ * Prove active plugin dependencies stay local and share the host's exact package instances.
+ * @param profile - Profile with its generated host links present.
+ * @param root - Immutable runtime directory.
+ * @param runtime - Verified shared package inventory.
+ * @param activePlugins - Explicit enabled plugin roots whose peer compatibility is required.
+ */
+export function validateDesktopPluginGraph(
+  profile: string, root: string, runtime: DesktopRuntimeDescriptor, activePlugins: readonly string[],
+): void {
+  const profileRoot = realpathSync(profile)
+  const shared = new Map(runtime.sharedPackages.map(entry => [entry.name, realpathSync(runtimePath(root, entry.path))]))
+  for (const [name, path] of shared) {
+    if (packageFrom(profile, name) !== path) throw new Error(`desktop profile: missing or incorrect host link ${name}`)
+  }
+  const scanned = new Set<string>()
+  const scan = (modules: string): void => {
+    if (!existsSync(modules)) return
+    if (lstatSync(modules).isSymbolicLink()) throw new Error(`desktop profile: linked package container ${modules}`)
+    const directory = realpathSync(modules)
+    if (scanned.has(directory)) return
+    scanned.add(directory)
+    for (const entry of readdirSync(modules, { withFileTypes: true })) {
+      if (entry.name.startsWith('.')) continue
+      const path = join(modules, entry.name)
+      if (entry.name.startsWith('@')) { scan(path); continue }
+      if (!existsSync(join(path, 'package.json'))) throw new Error(`desktop profile: invalid installed package ${path}`)
+      const canonical = realpathSync(path)
+      const info = manifest(canonical)
+      const host = shared.get(info.name)
+      if (host !== undefined) {
+        if (canonical !== host || path !== join(profile, 'node_modules', info.name)) {
+          throw new Error(`desktop profile: duplicate or aliased host package ${info.name} at ${path}`)
+        }
+        continue
+      }
+      if (entry.isSymbolicLink()) throw new Error(`desktop profile: linked private package ${path}`)
+      if (!inside(profileRoot, canonical)) throw new Error(`desktop profile: package resolves outside profile: ${path}`)
+      scan(join(path, 'node_modules'))
+    }
+  }
+  scan(join(profile, 'node_modules'))
+  const visited = new Set<string>()
+  const visit = (path: string, chain: string): void => {
+    if (visited.has(path)) return
+    visited.add(path)
+    const info = manifest(path)
+    const deps = { ...info.dependencies, ...info.optionalDependencies }
+    for (const [name, range] of Object.entries({ ...deps, ...info.peerDependencies })) {
+      const peer = name in info.peerDependencies
+      const optional = peer ? info.optionalPeers.has(name) : name in info.optionalDependencies
+      const target = packageFrom(path, name)
+      if (target === undefined && optional) continue
+      if (target === undefined) throw new Error(`desktop profile: ${chain} requires missing ${name}@${range}`)
+      const host = shared.get(name)
+      if (host !== undefined && name in deps) throw new Error(`desktop profile: ${chain} must declare ${name} as a peer dependency`)
+      if (host !== undefined ? target !== host : !inside(profileRoot, target)) {
+        throw new Error(`desktop profile: ${chain} resolves ${name} outside its owned packages`)
+      }
+      const dependency = manifest(target)
+      if (peer && !satisfies(dependency.version, range)) {
+        throw new Error(`desktop profile: ${chain} requires ${name}@${range}, found ${dependency.version}`)
+      }
+      if (host === undefined) visit(target, `${chain} -> ${name}`)
+    }
+  }
+  for (const name of activePlugins) {
+    const path = packageFrom(profile, name)
+    if (path === undefined || !inside(profileRoot, path)) throw new Error(`desktop profile: missing local plugin ${name}`)
+    visit(path, name)
+  }
+}

+ 155 - 189
apps/desktop/src/project-manager.ts

@@ -1,11 +1,9 @@
 /** Transactional owner of the reserved desktop profile and its private pnpm state. */
 
+import { valid } from 'semver'
 import { spawn } from 'node:child_process'
-import { createHash, randomUUID } from 'node:crypto'
+import { randomUUID } from 'node:crypto'
 import {
-  constants,
-  copyFileSync,
-  cpSync,
   existsSync,
   fsyncSync,
   ftruncateSync,
@@ -13,7 +11,6 @@ import {
   mkdirSync,
   openSync,
   closeSync,
-  readdirSync,
   readFileSync,
   renameSync,
   rmSync,
@@ -23,31 +20,23 @@ import {
 } from 'node:fs'
 import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
 import {
-  DESKTOP_PACKAGES_DIR,
-  DESKTOP_PACKAGE_SET_FILE,
   DESKTOP_HOST_PACKAGE,
   desktopCorePackageOverrides,
-  desktopDshPackageSpec,
-  readDesktopCorePackageSet,
   verifyDesktopCorePackageSet,
 } from './core-package-set.ts'
 import type { DesktopPaths } from './paths.ts'
-import { parseDesktopRelease, type DesktopRelease } from './release.ts'
-import { extractPnpmStoreArchives, mergePnpmStore } from './seed-store.ts'
-
-/** Files the package transaction copies between active and staging projects. */
-const DESKTOP_PROJECT_FILES = [
-  'package.json',
-  'pnpm-lock.yaml',
-  'pnpm-workspace.yaml',
-  'desktop-release.json',
-  DESKTOP_PACKAGE_SET_FILE,
-] as const
+import type { DesktopRelease } from './release.ts'
+import { desktopRuntimeId, verifyDesktopRuntime, type DesktopRuntimeDescriptor } from './runtime-tree.ts'
+import {
+  copyDesktopProfile, desktopPluginLockHash, linkDesktopHostPackages, readDesktopProfileState,
+  unlinkDesktopHostPackages, validateDesktopPluginGraph, type DesktopProfileState,
+} from './profile-packages.ts'
 
 /** Desktop plugin record derived from the installed profile. */
 export interface DesktopPluginRecord {
   readonly name: string
   readonly version: string
+  readonly enabled: boolean
 }
 
 /** Installed desktop project manifest slice. */
@@ -68,6 +57,8 @@ interface DesktopPendingTransaction {
   readonly schemaVersion: 1
   readonly id: string
   readonly stagingProfile: string
+  readonly fromRuntimeId: string | null
+  readonly toRuntimeId: string
   readonly step: 'prepared' | 'active-moved' | 'staging-activated'
 }
 
@@ -75,6 +66,7 @@ interface DesktopPendingTransaction {
 export interface DesktopRuntimeExecutables {
   readonly node: string
   readonly pnpm: string
+  readonly dsh: string
 }
 
 /** Hooks that bind project replacement to backend lifecycle and health. */
@@ -92,12 +84,8 @@ export type DesktopProjectMutation =
   | { readonly type: 'plugin-add'; readonly spec: string }
   | { readonly type: 'plugin-remove'; readonly name: string }
   | { readonly type: 'plugin-update'; readonly name: string; readonly version: string }
-
-interface DesktopSeedIntegrityRecord {
-  readonly path: string
-  readonly bytes: number
-  readonly sha256: string
-}
+  | { readonly type: 'plugin-toggle'; readonly name: string; readonly enabled: boolean }
+  | { readonly type: 'plugins-disable-all' }
 
 const PROJECT_NAME = '@deepseek-ai/dsh-desktop-runtime'
 const DSH_PACKAGE = '@deepseek-ai/dsh'
@@ -133,10 +121,6 @@ function workspaceFile(overrides: Readonly<Record<string, string>> = {}): string
   return `packages:\n  - .\n\n${overrideSection}${WORKSPACE_SETTINGS}allowBuilds:\n  node-pty: true\n  koffi: true\n  fs-ext: true\n  ${JSON.stringify(coreBuildKey)}: true\n  '@google/genai': false\n  protobufjs: false\n  node-addon-require-builtin: false\n`
 }
 
-function releaseFile(projectDir: string): DesktopRelease {
-  return parseDesktopRelease(readJson(join(projectDir, 'desktop-release.json')))
-}
-
 function isRecord(value: unknown): value is Record<string, unknown> {
   return typeof value === 'object' && value !== null
 }
@@ -190,83 +174,20 @@ function removeOwnedDirectory(path: string): void {
   rmSync(path, { recursive: true })
 }
 
-function copyMetadata(source: string, target: string): void {
-  mkdirSync(target, { recursive: true, mode: 0o700 })
-  for (const filename of DESKTOP_PROJECT_FILES) {
-    const from = join(source, filename)
-    if (existsSync(from)) copyFileSync(from, join(target, filename), constants.COPYFILE_EXCL)
-  }
-  cpSync(join(source, DESKTOP_PACKAGES_DIR), join(target, DESKTOP_PACKAGES_DIR), {
-    recursive: true,
-    force: false,
-    errorOnExist: true,
-  })
-}
-
-function seedFiles(root: string): readonly DesktopSeedIntegrityRecord[] {
-  const files: DesktopSeedIntegrityRecord[] = []
-  const visit = (directory: string): void => {
-    for (const entry of readdirSync(directory, { withFileTypes: true })) {
-      const path = join(directory, entry.name)
-      const relativePath = path.slice(root.length + 1).split(sep).join('/')
-      if (relativePath === 'integrity.json') continue
-      if (entry.isSymbolicLink()) throw new Error(`desktop seed: symbolic link is not allowed: ${relativePath}`)
-      if (entry.isDirectory()) {
-        visit(path)
-        continue
-      }
-      if (!entry.isFile()) throw new Error(`desktop seed: unsupported file type: ${relativePath}`)
-      const body = readFileSync(path)
-      files.push({
-        path: relativePath,
-        bytes: body.byteLength,
-        sha256: createHash('sha256').update(body).digest('hex'),
-      })
-    }
-  }
-  visit(root)
-  return files.sort((left, right) => left.path.localeCompare(right.path))
-}
-
-/** Verify the packaged offline seed before any content enters writable desktop state. */
-export function verifySeedIntegrity(seedDir: string): void {
-  const integrityPath = join(seedDir, 'integrity.json')
-  const integrity = readJson(integrityPath)
-  if (!isRecord(integrity) || integrity.schemaVersion !== 2 || !Array.isArray(integrity.files)) {
-    throw new Error(`desktop seed: invalid integrity inventory ${integrityPath}`)
-  }
-  const expected: DesktopSeedIntegrityRecord[] = integrity.files.map((record) => {
-    if (!isRecord(record) || typeof record.path !== 'string' || record.path === '' || record.path.startsWith('/')
-      || record.path.split('/').includes('..') || typeof record.bytes !== 'number'
-      || !Number.isSafeInteger(record.bytes) || record.bytes < 0
-      || typeof record.sha256 !== 'string' || !/^[a-f0-9]{64}$/u.test(record.sha256)) {
-      throw new Error(`desktop seed: invalid integrity record in ${integrityPath}`)
-    }
-    return { path: record.path, bytes: record.bytes, sha256: record.sha256 }
-  }).sort((left, right) => left.path.localeCompare(right.path))
-  const actual = seedFiles(seedDir)
-  if (JSON.stringify(actual) !== JSON.stringify(expected)) {
-    throw new Error('desktop seed: integrity verification failed')
-  }
-}
-
 function projectManifest(projectDir: string): DesktopProjectManifest {
   const path = join(projectDir, 'package.json')
   const value = readJson(path)
   const dsh = isRecord(value) && isRecord(value.dsh) ? value.dsh : undefined
   const profile = isRecord(dsh?.profile) ? dsh.profile : undefined
   if (!isRecord(value) || value.name !== PROJECT_NAME || value.private !== true
-    || typeof value.version !== 'string' || !isRecord(value.dependencies)
+    || typeof value.version !== 'string' || (value.dependencies !== undefined && !isRecord(value.dependencies))
     || !Array.isArray(profile?.bundles) || !profile.bundles.every(bundle => typeof bundle === 'string')) {
     throw new Error(`desktop project: invalid desktop profile manifest ${path}`)
   }
-  const manifest = value as unknown as DesktopProjectManifest
-  const packageSet = readDesktopCorePackageSet(projectDir, releaseFile(projectDir).version)
-  const expectedOverrides = desktopCorePackageOverrides(packageSet)
-  if (manifest.dependencies[DSH_PACKAGE] !== desktopDshPackageSpec(packageSet)
-    || Object.entries(expectedOverrides).some(([name, spec]) => manifest.dependencies[name] !== spec)
-    || readFileSync(join(projectDir, 'pnpm-workspace.yaml'), 'utf8') !== workspaceFile(expectedOverrides)) {
-    throw new Error(`desktop project: core package mapping does not match ${DESKTOP_PACKAGE_SET_FILE}`)
+  const manifest = { ...value, dependencies: value.dependencies ?? {} } as unknown as DesktopProjectManifest
+  if (Object.entries(manifest.dependencies).some(([name, version]) => !PACKAGE_NAME_PATTERN.test(name)
+    || typeof version !== 'string' || valid(version) !== version)) {
+    throw new Error('desktop project: plugin dependencies must use exact registry versions')
   }
   return manifest
 }
@@ -285,7 +206,7 @@ function profilePluginNames(projectDir: string): readonly string[] {
 }
 
 function pluginRecords(projectDir: string): readonly DesktopPluginRecord[] {
-  return profilePluginNames(projectDir).map(name => inspectPlugin(projectDir, name))
+  return Object.keys(projectManifest(projectDir).dependencies).sort().map(name => inspectPlugin(projectDir, name))
 }
 
 function writeProfilePlugins(projectDir: string, plugins: readonly DesktopPluginRecord[]): void {
@@ -296,7 +217,7 @@ function writeProfilePlugins(projectDir: string, plugins: readonly DesktopPlugin
       ...manifest.dsh,
       profile: {
         ...manifest.dsh.profile,
-        bundles: [...DESKTOP_PROFILE_BUNDLES, ...plugins.map(plugin => plugin.name)],
+        bundles: [...DESKTOP_PROFILE_BUNDLES, ...plugins.filter(plugin => plugin.enabled).map(plugin => plugin.name)],
       },
     },
   } satisfies DesktopProjectManifest)
@@ -322,12 +243,13 @@ function inspectPlugin(projectDir: string, requestedName: string): DesktopPlugin
   if ((patchPath !== packageDir && !patchPath.startsWith(packageDir + sep)) || !existsSync(patchPath)) {
     throw new Error(`desktop project: ${requestedName}@${manifest.version} declares an invalid bundle patch`)
   }
-  return { name: requestedName, version: manifest.version }
+  return { name: requestedName, version: manifest.version, enabled: profilePluginNames(projectDir).includes(requestedName) }
 }
 
 /** Transactional desktop npm project manager. */
 export class DesktopProjectManager {
   private lockDescriptor: number | undefined
+  private descriptor: DesktopRuntimeDescriptor | undefined
 
   /**
    * @param paths - Electron-owned package state and reserved desktop profile paths.
@@ -345,6 +267,9 @@ export class DesktopProjectManager {
     if (!isRecord(value) || value.schemaVersion !== 1
       || typeof value.id !== 'string' || typeof value.stagingProfile !== 'string'
       || !isDescendant(this.paths.staging, value.stagingProfile)
+      || value.stagingProfile !== join(this.paths.staging, value.id, 'profile')
+      || (value.fromRuntimeId !== null && (typeof value.fromRuntimeId !== 'string' || !/^[a-f0-9]{64}$/u.test(value.fromRuntimeId)))
+      || typeof value.toRuntimeId !== 'string' || !/^[a-f0-9]{64}$/u.test(value.toRuntimeId)
       || (value.step !== 'prepared' && value.step !== 'active-moved' && value.step !== 'staging-activated')) {
       throw new Error(`desktop project: invalid activation journal ${this.paths.pending}`)
     }
@@ -352,9 +277,20 @@ export class DesktopProjectManager {
       schemaVersion: 1,
       id: value.id,
       stagingProfile: value.stagingProfile,
+      fromRuntimeId: value.fromRuntimeId,
+      toRuntimeId: value.toRuntimeId,
       step: value.step,
     }
-    if (!existsSync(this.paths.profile) && existsSync(this.paths.rollback)) {
+    if (pending.step === 'staging-activated' && !existsSync(pending.stagingProfile) && existsSync(this.paths.profile)) {
+      if (readDesktopProfileState(this.paths.profile)?.runtimeId !== pending.toRuntimeId) {
+        throw new Error('desktop project: activated profile does not match its journal')
+      }
+      removeOwnedDirectory(this.paths.profile)
+    }
+    if (!existsSync(this.paths.profile) && pending.fromRuntimeId !== null && existsSync(this.paths.rollback)) {
+      if (readDesktopProfileState(this.paths.rollback)?.runtimeId !== pending.fromRuntimeId) {
+        throw new Error('desktop project: rollback profile does not match its journal')
+      }
       mkdirSync(dirname(this.paths.profile), { recursive: true })
       renameSync(this.paths.rollback, this.paths.profile)
     }
@@ -368,64 +304,59 @@ export class DesktopProjectManager {
     return pluginRecords(this.paths.profile)
   }
 
-  /** Read the exact dsh version installed in the active desktop project. */
+  /** Read the dsh version supplied by this application's verified resources. */
   dshVersion(): string {
-    if (!existsSync(this.paths.profile)) throw new Error('desktop project: active profile is not installed')
-    return this.installedPackageVersion(DSH_PACKAGE)
+    return this.currentRuntime().release.version
   }
 
-  private installedPackageVersion(packageName: string): string {
-    const manifestPath = join(this.paths.profile, 'node_modules', ...packageName.split('/'), 'package.json')
-    const manifest = readJson(manifestPath)
-    if (!isRecord(manifest) || typeof manifest.version !== 'string') {
-      throw new Error(`desktop project: installed ${packageName} package has no version`)
+  /** Read the release most recently applied to the active profile. */
+  releaseVersion(): string {
+    const state = readDesktopProfileState(this.paths.profile)
+    if (state === undefined) throw new Error('desktop project: active profile has no runtime state')
+    return state.version
+  }
+
+  /** Reject a profile whose dependency links were prepared for another runtime. */
+  assertProfileRuntime(projectDir: string): void {
+    if (readDesktopProfileState(projectDir)?.runtimeId !== desktopRuntimeId(this.currentRuntime())) {
+      throw new Error('desktop project: profile does not match this application runtime')
     }
-    assertVersion(manifest.version)
-    return manifest.version
   }
 
-  /** Read the release version applied to the active desktop project. */
-  releaseVersion(): string {
-    if (!existsSync(this.paths.profile)) throw new Error('desktop project: active profile is not installed')
-    return releaseFile(this.paths.profile).version
+  private currentRuntime(): DesktopRuntimeDescriptor {
+    if (this.descriptor === undefined) throw new Error('desktop project: runtime has not been verified')
+    return this.descriptor
   }
 
-  /** Install or reconcile the active project to the Electron package's exact release. */
-  async applyRelease(seedDir: string, electronVersion: string, hooks: DesktopProjectHooks): Promise<boolean> {
+  private prepareProfile(projectDir: string): void {
+    const runtime = this.currentRuntime()
+    linkDesktopHostPackages(projectDir, this.runtime.dsh, runtime)
+    validateDesktopPluginGraph(projectDir, this.runtime.dsh, runtime, profilePluginNames(projectDir))
+  }
+
+  /** Verify this release and reconcile its external profile without installing core packages. */
+  async applyRelease(electronVersion: string, hooks: DesktopProjectHooks): Promise<boolean> {
     return this.withLock(async () => {
       this.recover()
-      verifySeedIntegrity(seedDir)
-      const target = releaseFile(seedDir)
-      verifyDesktopCorePackageSet(seedDir, target.version)
-      if (target.version !== electronVersion) {
-        throw new Error(`desktop project: seed ${target.version} does not match Electron ${electronVersion}`)
+      const target = verifyDesktopRuntime(this.runtime.dsh, electronVersion)
+      this.descriptor = target
+      const previous = readDesktopProfileState(this.paths.profile)
+      if (existsSync(this.paths.profile) && previous === undefined) {
+        throw new Error('desktop project: existing profile is not a Desktop plugin profile')
       }
-      if (existsSync(this.paths.profile) && this.releaseVersion() === target.version
-        && this.dshVersion() === target.version
-        && this.installedPackageVersion(DESKTOP_HOST_PACKAGE) === target.version) {
-        verifyDesktopCorePackageSet(this.paths.profile, target.version)
+      if (previous?.runtimeId === desktopRuntimeId(target)
+        && previous.lockHash === desktopPluginLockHash(this.paths.profile)
+        && previous.links.length === target.sharedPackages.length
+        && previous.links.every(link => link.target === join(this.runtime.dsh, 'node_modules', link.name)
+          && existsSync(join(this.paths.profile, 'node_modules', link.name)))) {
+        validateDesktopPluginGraph(this.paths.profile, this.runtime.dsh, target, profilePluginNames(this.paths.profile))
         return false
       }
-      this.mergeSeedPnpmState(seedDir)
       const stagingProfile = this.newStagingProfile()
       try {
-        if (existsSync(this.paths.profile)) {
-          const plugins = pluginRecords(this.paths.profile)
-          copyMetadata(seedDir, stagingProfile)
-          await this.runPnpm(stagingProfile, ['install', '--offline', '--frozen-lockfile', '--trust-lockfile'])
-          if (plugins.length > 0) {
-            await this.runPnpm(stagingProfile, [
-              'add',
-              ...plugins.map(plugin => `${plugin.name}@${plugin.version}`),
-              '--save-exact',
-              '--offline',
-            ])
-            writeProfilePlugins(stagingProfile, plugins)
-          }
-        } else {
-          copyMetadata(seedDir, stagingProfile)
-          await this.runPnpm(stagingProfile, ['install', '--offline', '--frozen-lockfile', '--trust-lockfile'])
-        }
+        if (previous === undefined) createPluginProfile(stagingProfile)
+        else copyDesktopProfile(this.paths.profile, stagingProfile)
+        await this.reconcileProfile(stagingProfile, previous)
         await hooks.healthCheck(stagingProfile)
         await this.activate(stagingProfile, hooks)
         return true
@@ -436,16 +367,18 @@ export class DesktopProjectManager {
     })
   }
 
-  /** Apply one exact dependency mutation through a staging project. */
+  /** Apply an exact plugin dependency or activation change through a staging project. */
   async mutate(mutation: DesktopProjectMutation, hooks: DesktopProjectHooks): Promise<void> {
     await this.withLock(async () => {
       this.recover()
+      this.currentRuntime()
       if (!existsSync(this.paths.profile)) throw new Error('desktop project: active profile is not installed')
-      verifyDesktopCorePackageSet(this.paths.profile, this.releaseVersion())
       const stagingProfile = this.newStagingProfile()
       try {
-        copyMetadata(this.paths.profile, stagingProfile)
+        copyDesktopProfile(this.paths.profile, stagingProfile)
         await this.applyMutation(stagingProfile, mutation)
+        await this.reconcileProfile(stagingProfile, readDesktopProfileState(stagingProfile),
+          mutation.type !== 'plugin-toggle' && mutation.type !== 'plugins-disable-all')
         await hooks.healthCheck(stagingProfile)
         await this.activate(stagingProfile, hooks)
       } catch (error) {
@@ -455,6 +388,25 @@ export class DesktopProjectManager {
     })
   }
 
+  private async reconcileProfile(projectDir: string, previous: DesktopProfileState | undefined, packagesChanged = false): Promise<void> {
+    const target = this.currentRuntime()
+    this.prepareProfile(projectDir)
+    const rebuild = previous !== undefined && pluginRecords(projectDir).length > 0
+      && (previous.nodeVersion !== target.release.nodeVersion || previous.platform !== target.platform || previous.arch !== target.arch)
+    if (rebuild) {
+      unlinkDesktopHostPackages(projectDir)
+      removeOwnedDirectory(join(projectDir, 'node_modules'))
+      await this.runPnpm(projectDir, ['install', '--frozen-lockfile', '--ignore-scripts'])
+    }
+    if (rebuild || packagesChanged) await this.finishPackageOperation(projectDir)
+  }
+
+  private async finishPackageOperation(projectDir: string): Promise<void> {
+    this.prepareProfile(projectDir)
+    await this.runPnpm(projectDir, ['rebuild', '--pending'])
+    this.prepareProfile(projectDir)
+  }
+
   private newStagingProfile(): string {
     const path = join(this.paths.staging, randomUUID(), 'profile')
     mkdirSync(path, { recursive: true, mode: 0o700 })
@@ -466,8 +418,11 @@ export class DesktopProjectManager {
       case 'plugin-add': {
         const requestedName = packageNameFromSpec(mutation.spec)
         if (requestedName === undefined) throw new Error('desktop project: plugin package name is required')
-        await this.runPnpm(projectDir, ['add', mutation.spec, '--save-exact'])
-        const installed = inspectPlugin(projectDir, requestedName)
+        if (this.currentRuntime().sharedPackages.some(entry => entry.name === requestedName)) {
+          throw new Error(`desktop project: cannot install host-owned package ${requestedName}`)
+        }
+        await this.runPnpm(projectDir, ['add', mutation.spec, '--save-exact', '--ignore-scripts'])
+        const installed = { ...inspectPlugin(projectDir, requestedName), enabled: true }
         const current = pluginRecords(projectDir).filter(plugin => plugin.name !== installed.name)
         writeProfilePlugins(
           projectDir,
@@ -477,21 +432,21 @@ export class DesktopProjectManager {
       }
       case 'plugin-remove': {
         assertPackageName(mutation.name)
-        if (!profilePluginNames(projectDir).includes(mutation.name)) {
+        if (!Object.hasOwn(projectManifest(projectDir).dependencies, mutation.name)) {
           throw new Error(`desktop project: plugin ${JSON.stringify(mutation.name)} is not installed`)
         }
         const remaining = pluginRecords(projectDir).filter(plugin => plugin.name !== mutation.name)
-        await this.runPnpm(projectDir, ['remove', mutation.name])
+        await this.runPnpm(projectDir, ['remove', mutation.name, '--config.ignore-scripts=true'])
         writeProfilePlugins(projectDir, remaining)
         return
       }
       case 'plugin-update':
         assertPackageName(mutation.name)
         assertVersion(mutation.version)
-        if (!profilePluginNames(projectDir).includes(mutation.name)) {
+        if (!Object.hasOwn(projectManifest(projectDir).dependencies, mutation.name)) {
           throw new Error(`desktop project: plugin ${JSON.stringify(mutation.name)} is not installed`)
         }
-        await this.runPnpm(projectDir, ['add', `${mutation.name}@${mutation.version}`, '--save-exact'])
+        await this.runPnpm(projectDir, ['add', `${mutation.name}@${mutation.version}`, '--save-exact', '--ignore-scripts'])
         {
           const installed = inspectPlugin(projectDir, mutation.name)
           writeProfilePlugins(
@@ -500,33 +455,37 @@ export class DesktopProjectManager {
           )
         }
         return
+      case 'plugins-disable-all':
+        writeProfilePlugins(projectDir, pluginRecords(projectDir).map(plugin => ({ ...plugin, enabled: false })))
+        return
+      case 'plugin-toggle': {
+        assertPackageName(mutation.name)
+        const plugins = pluginRecords(projectDir)
+        if (!plugins.some(plugin => plugin.name === mutation.name)) throw new Error(`desktop project: plugin ${mutation.name} is not installed`)
+        writeProfilePlugins(projectDir, plugins.map(plugin => (
+          plugin.name === mutation.name ? { ...plugin, enabled: mutation.enabled } : plugin
+        )))
+        return
+      }
       default:
         mutation satisfies never
     }
   }
 
-  private mergeSeedPnpmState(seedDir: string): void {
-    const transactionRoot = join(this.paths.staging, randomUUID())
-    const extractedStore = join(transactionRoot, 'store')
-    try {
-      extractPnpmStoreArchives(seedDir, extractedStore)
-      mergePnpmStore(extractedStore, this.paths.pnpm.store)
-    } finally {
-      removeOwnedDirectory(transactionRoot)
-    }
-  }
-
   private async activate(stagingProfile: string, hooks: DesktopProjectHooks): Promise<void> {
     const pending: DesktopPendingTransaction = {
       schemaVersion: 1,
       id: basename(dirname(stagingProfile)),
       stagingProfile,
+      fromRuntimeId: readDesktopProfileState(this.paths.profile)?.runtimeId ?? null,
+      toRuntimeId: desktopRuntimeId(this.currentRuntime()),
       step: 'prepared',
     }
     writeJson(this.paths.pending, pending)
-    await hooks.beforeActivate()
     let activeMoved = false
+    let stagingActivated = false
     try {
+      await hooks.beforeActivate()
       removeOwnedDirectory(this.paths.rollback)
       mkdirSync(dirname(this.paths.rollback), { recursive: true, mode: 0o700 })
       writeJson(this.paths.pending, { ...pending, step: 'active-moved' } satisfies DesktopPendingTransaction)
@@ -537,10 +496,11 @@ export class DesktopProjectManager {
       mkdirSync(dirname(this.paths.profile), { recursive: true, mode: 0o700 })
       writeJson(this.paths.pending, { ...pending, step: 'staging-activated' } satisfies DesktopPendingTransaction)
       renameSync(stagingProfile, this.paths.profile)
+      stagingActivated = true
       await hooks.afterActivate()
       unlinkSync(this.paths.pending)
     } catch (error) {
-      if (existsSync(this.paths.profile)) removeOwnedDirectory(this.paths.profile)
+      if (stagingActivated) removeOwnedDirectory(this.paths.profile)
       if (activeMoved && existsSync(this.paths.rollback)) renameSync(this.paths.rollback, this.paths.profile)
       if (existsSync(this.paths.pending)) unlinkSync(this.paths.pending)
       await hooks.afterActivate().catch(() => undefined)
@@ -558,7 +518,7 @@ export class DesktopProjectManager {
     const npmrc = join(this.paths.pnpm.config, 'npmrc')
     if (!existsSync(npmrc)) writeFileSync(npmrc, '', { mode: 0o600 })
     const inherited = Object.fromEntries(Object.entries(process.env).filter(([name]) => (
-      !/^DSH_DESKTOP_/u.test(name) && !/^(?:npm|pnpm|corepack)_/iu.test(name)
+      name !== 'NODE_OPTIONS' && name !== 'NODE_PATH' && !/^DSH_DESKTOP_/u.test(name) && !/^(?:npm|pnpm|corepack)_/iu.test(name)
     )))
     await new Promise<void>((settle, reject) => {
       const child = spawn(this.runtime.node, [
@@ -585,19 +545,7 @@ export class DesktopProjectManager {
         },
         stdio: ['ignore', 'pipe', 'pipe'],
       })
-      const childPid = child.pid
-      if (childPid === undefined) {
-        child.kill('SIGKILL')
-        reject(new Error('desktop project: pnpm did not report a process id'))
-        return
-      }
-      try {
-        this.writeLockOwner(childPid)
-      } catch (error) {
-        child.kill('SIGKILL')
-        reject(errorOf(error, 'desktop project: failed to assign the package transaction lock to pnpm'))
-        return
-      }
+      let failure: Error | undefined
       let diagnostics = ''
       let completed = false
       const appendDiagnostics = (chunk: string): void => {
@@ -618,9 +566,10 @@ export class DesktopProjectManager {
         }
         settleChild()
       }
-      child.once('error', (error) => { complete(() => { reject(error) }) })
+      child.once('error', (error) => { failure = error })
       child.once('close', (code, signal) => {
         complete(() => {
+          if (failure !== undefined) { reject(failure); return }
           if (code === 0) {
             settle()
             return
@@ -630,6 +579,13 @@ export class DesktopProjectManager {
           ))
         })
       })
+      try {
+        if (child.pid === undefined) throw new Error('desktop project: pnpm did not report a process id')
+        this.writeLockOwner(child.pid)
+      } catch (error) {
+        failure = errorOf(error, 'desktop project: failed to assign the package transaction lock to pnpm')
+        child.kill('SIGKILL')
+      }
     })
   }
 
@@ -682,10 +638,10 @@ export class DesktopProjectManager {
   }
 }
 
-/** Create seed metadata for one exact Electron and dsh release. */
-export function createSeedMetadata(seedDir: string, release: DesktopRelease): void {
-  mkdirSync(seedDir, { recursive: true, mode: 0o700 })
-  const packageSet = verifyDesktopCorePackageSet(seedDir, release.version)
+/** Create build-only project metadata for materializing the signed runtime. */
+export function createRuntimeProjectMetadata(projectDir: string, release: DesktopRelease): void {
+  mkdirSync(projectDir, { recursive: true, mode: 0o700 })
+  const packageSet = verifyDesktopCorePackageSet(projectDir, release.version)
   const manifest: DesktopProjectManifest = {
     name: PROJECT_NAME,
     private: true,
@@ -693,13 +649,13 @@ export function createSeedMetadata(seedDir: string, release: DesktopRelease): vo
     dependencies: desktopCorePackageOverrides(packageSet),
     dsh: { profile: { bundles: [...DESKTOP_PROFILE_BUNDLES] } },
   }
-  writeJson(join(seedDir, 'package.json'), manifest)
+  writeJson(join(projectDir, 'package.json'), manifest)
   writeFileSync(
-    join(seedDir, 'pnpm-workspace.yaml'),
+    join(projectDir, 'pnpm-workspace.yaml'),
     workspaceFile(desktopCorePackageOverrides(packageSet)),
     { mode: 0o600 },
   )
-  writeJson(join(seedDir, 'desktop-release.json'), release)
+  writeJson(join(projectDir, 'desktop-release.json'), release)
 }
 
 /**
@@ -723,3 +679,13 @@ export function createDevelopmentProjectMetadata(projectDir: string, release: De
   writeFileSync(join(projectDir, 'pnpm-workspace.yaml'), workspaceFile(), { mode: 0o600 })
   writeJson(join(projectDir, 'desktop-release.json'), release)
 }
+
+/** Create the first external plugin profile without running a package manager. */
+export function createPluginProfile(projectDir: string): void {
+  mkdirSync(projectDir, { recursive: true, mode: 0o700 })
+  writeJson(join(projectDir, 'package.json'), {
+    name: PROJECT_NAME, private: true, version: '0.0.0', dependencies: {},
+    dsh: { profile: { bundles: [...DESKTOP_PROFILE_BUNDLES] } },
+  } satisfies DesktopProjectManifest)
+  writeFileSync(join(projectDir, 'pnpm-workspace.yaml'), workspaceFile(), { mode: 0o600 })
+}

+ 2 - 2
apps/desktop/src/release.ts

@@ -1,9 +1,9 @@
-/** Immutable version identity shared by one Electron shell and its dsh seed. */
+/** Immutable version identity shared by one Electron shell and its bundled dsh runtime. */
 
 import { valid } from 'semver'
 import { DESKTOP_HOST_PROTOCOL_VERSION } from './host-protocol.ts'
 
-/** Release facts embedded in the seed and copied into the active desktop project. */
+/** Release facts embedded in the bundled runtime descriptor. */
 export interface DesktopRelease {
   readonly schemaVersion: 1
   /** Exact version used by both Electron and `@deepseek-ai/dsh`. */

+ 180 - 0
apps/desktop/src/runtime-tree.ts

@@ -0,0 +1,180 @@
+/** Relocatable, integrity-recorded production packages carried by one Desktop release. */
+
+import { createHash } from 'node:crypto'
+import { lstatSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
+import { isAbsolute, join, relative, sep } from 'node:path'
+import { valid } from 'semver'
+import { DESKTOP_HOST_PACKAGE, DESKTOP_HOST_RUNTIME_FILES } from './core-package-set.ts'
+import { parseDesktopRelease, type DesktopRelease } from './release.ts'
+
+/** Descriptor at the root of the immutable Desktop resource tree. */
+export const DESKTOP_RUNTIME_FILE = 'desktop-runtime.json'
+
+/** Host-owned package available to external plugins through a directory link. */
+export interface DesktopSharedPackage {
+  readonly name: string
+  readonly version: string
+  readonly path: string
+}
+
+/** Final bytes and executable permissions of a runtime file. */
+export interface DesktopRuntimeFile {
+  readonly path: string
+  readonly bytes: number
+  readonly sha256: string
+  readonly executable: boolean
+}
+
+/** One signed application's production dependency tree. */
+export interface DesktopRuntimeDescriptor {
+  readonly schemaVersion: 1
+  readonly release: DesktopRelease
+  readonly platform: NodeJS.Platform
+  readonly arch: string
+  readonly sharedPackages: readonly DesktopSharedPackage[]
+  readonly files: readonly DesktopRuntimeFile[]
+}
+
+const PACKAGE_NAME = /^(?:@[a-z0-9][a-z0-9._~-]*\/[a-z0-9][a-z0-9._~-]*|[a-z0-9][a-z0-9._~-]*)$/u
+
+function record(value: unknown): value is Record<string, unknown> {
+  return typeof value === 'object' && value !== null && !Array.isArray(value)
+}
+
+/**
+ * Resolve one portable resource path without permitting traversal or absolute paths.
+ * @param root - Runtime root.
+ * @param path - Slash-separated relative path from durable metadata.
+ * @returns Absolute resource path.
+ */
+export function runtimePath(root: string, path: string): string {
+  if (path === '' || isAbsolute(path) || path.includes('\\') || path.includes(':')
+    || path.split('/').some(part => part === '' || part === '.' || part === '..')) {
+    throw new Error(`desktop runtime: invalid relative path ${JSON.stringify(path)}`)
+  }
+  return join(root, ...path.split('/'))
+}
+
+/**
+ * Inventory a materialized runtime without following links or including its descriptor.
+ * @param root - Self-contained runtime directory.
+ * @returns Sorted final-file inventory.
+ */
+export function inventoryDesktopRuntime(root: string): DesktopRuntimeFile[] {
+  const files: DesktopRuntimeFile[] = []
+  const visit = (directory: string): void => {
+    for (const entry of readdirSync(directory, { withFileTypes: true })) {
+      const path = join(directory, entry.name)
+      const name = relative(root, path).split(sep).join('/')
+      if (name === DESKTOP_RUNTIME_FILE) continue
+      if (entry.isDirectory()) visit(path)
+      else if (entry.isFile()) {
+        const body = readFileSync(path)
+        files.push({ path: name, bytes: body.byteLength, sha256: createHash('sha256').update(body).digest('hex'),
+          executable: (lstatSync(path).mode & 0o111) !== 0 })
+      } else throw new Error(`desktop runtime: unsupported filesystem entry ${name}`)
+    }
+  }
+  visit(root)
+  return files.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0)
+}
+
+/**
+ * Seal the final runtime tree after materialization and native signing.
+ * @param root - Runtime output directory.
+ * @param release - Matching shell, dsh, Host, and executable versions.
+ * @param sharedNames - Release-owned packages supplied to plugins.
+ * @param target - Platform and architecture selected by runtime preparation.
+ * @returns Descriptor written beside the production packages.
+ */
+export function writeDesktopRuntime(
+  root: string, release: DesktopRelease, sharedNames: readonly string[],
+  target: { platform: NodeJS.Platform; arch: string } = process,
+): DesktopRuntimeDescriptor {
+  const sharedPackages = [...new Set(sharedNames)].sort().map((name) => {
+    if (!PACKAGE_NAME.test(name)) throw new Error(`desktop runtime: invalid shared package ${name}`)
+    const path = `node_modules/${name}`
+    const manifest = JSON.parse(readFileSync(join(runtimePath(root, path), 'package.json'), 'utf8')) as unknown
+    if (!record(manifest) || manifest.name !== name || typeof manifest.version !== 'string' || valid(manifest.version) === null) {
+      throw new Error(`desktop runtime: invalid shared package manifest ${name}`)
+    }
+    return { name, version: manifest.version, path }
+  })
+  const descriptor: DesktopRuntimeDescriptor = {
+    schemaVersion: 1, release, platform: target.platform, arch: target.arch,
+    sharedPackages, files: inventoryDesktopRuntime(root),
+  }
+  writeFileSync(join(root, DESKTOP_RUNTIME_FILE), `${JSON.stringify(descriptor, undefined, 2)}\n`)
+  return descriptor
+}
+
+/**
+ * Verify the runtime before linking any of its packages into writable state.
+ * @param root - Current application's runtime resources.
+ * @param electronVersion - Expected shell version.
+ * @param target - Required execution target; defaults to the current process.
+ * @returns Validated runtime descriptor.
+ */
+export function verifyDesktopRuntime(
+  root: string, electronVersion: string, target: { platform: NodeJS.Platform; arch: string } = process,
+): DesktopRuntimeDescriptor {
+  const value: unknown = JSON.parse(readFileSync(join(root, DESKTOP_RUNTIME_FILE), 'utf8'))
+  if (!record(value) || value.schemaVersion !== 1 || value.platform !== target.platform || value.arch !== target.arch
+    || !Array.isArray(value.sharedPackages) || !Array.isArray(value.files)) {
+    throw new Error('desktop runtime: invalid descriptor or incompatible platform/architecture')
+  }
+  const release = parseDesktopRelease(value.release)
+  if (release.version !== electronVersion) throw new Error(`desktop runtime: ${release.version} does not match Electron ${electronVersion}`)
+  const sharedPackages = value.sharedPackages.map((entry: unknown): DesktopSharedPackage => {
+    if (!record(entry) || typeof entry.name !== 'string' || !PACKAGE_NAME.test(entry.name)
+      || typeof entry.version !== 'string' || valid(entry.version) === null || entry.path !== `node_modules/${entry.name}`) {
+      throw new Error('desktop runtime: invalid shared package record')
+    }
+    return { name: entry.name, version: entry.version, path: entry.path }
+  })
+  if (new Set(sharedPackages.map(entry => entry.name)).size !== sharedPackages.length) {
+    throw new Error('desktop runtime: duplicate shared package')
+  }
+  const files = value.files.map((entry: unknown): DesktopRuntimeFile => {
+    if (!record(entry) || typeof entry.path !== 'string' || typeof entry.bytes !== 'number'
+      || !Number.isSafeInteger(entry.bytes) || entry.bytes < 0 || typeof entry.executable !== 'boolean'
+      || typeof entry.sha256 !== 'string' || !/^[a-f0-9]{64}$/u.test(entry.sha256)) {
+      throw new Error('desktop runtime: invalid file inventory')
+    }
+    runtimePath(root, entry.path)
+    return { path: entry.path, bytes: entry.bytes, sha256: entry.sha256, executable: entry.executable }
+  }).sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0)
+  const actual = inventoryDesktopRuntime(root)
+  // Windows has no portable Unix executable permission bits.
+  const comparable = (items: readonly DesktopRuntimeFile[]): unknown => process.platform === 'win32'
+    ? items.map(({ executable: _executable, ...item }) => item) : items
+  if (JSON.stringify(comparable(files)) !== JSON.stringify(comparable(actual))) {
+    throw new Error('desktop runtime: integrity verification failed')
+  }
+  for (const entry of sharedPackages) {
+    const manifest: unknown = JSON.parse(readFileSync(join(runtimePath(root, entry.path), 'package.json'), 'utf8'))
+    if (!record(manifest) || manifest.name !== entry.name || manifest.version !== entry.version) {
+      throw new Error(`desktop runtime: shared package metadata mismatch for ${entry.name}`)
+    }
+  }
+  for (const name of ['@deepseek-ai/dsh', DESKTOP_HOST_PACKAGE]) {
+    if (sharedPackages.find(entry => entry.name === name)?.version !== release.version) {
+      throw new Error(`desktop runtime: missing or mismatched ${name}`)
+    }
+  }
+  for (const file of DESKTOP_HOST_RUNTIME_FILES) {
+    if (!files.some(entry => entry.path === `node_modules/${DESKTOP_HOST_PACKAGE}/${file}`)) {
+      throw new Error(`desktop runtime: missing Host file ${file}`)
+    }
+  }
+  return { schemaVersion: 1, release, platform: target.platform, arch: target.arch, sharedPackages, files }
+}
+
+/**
+ * Identify exact runtime content independently of its installation path.
+ * @param descriptor - Validated runtime metadata.
+ * @returns SHA-256 runtime identity.
+ */
+export function desktopRuntimeId(descriptor: DesktopRuntimeDescriptor): string {
+  return createHash('sha256').update(JSON.stringify(descriptor)).digest('hex')
+}

+ 0 - 271
apps/desktop/src/seed-store.ts

@@ -1,271 +0,0 @@
-/** Deterministic archive transport for the desktop seed's pnpm store. */
-
-import { createHash } from 'node:crypto'
-import {
-  chmodSync,
-  copyFileSync,
-  cpSync,
-  existsSync,
-  mkdirSync,
-  readdirSync,
-  readFileSync,
-  rmSync,
-  writeFileSync,
-} from 'node:fs'
-import { join, relative, sep } from 'node:path'
-import { DatabaseSync } from 'node:sqlite'
-import { create, extract, list } from 'tar'
-
-/** Directory containing the seed's uncompressed pnpm store archives. */
-export const SEED_STORE_ARCHIVE_DIR = 'store-archives'
-
-/** Manifest describing the deterministic pnpm store archive set. */
-export const SEED_STORE_ARCHIVE_MANIFEST = 'store-archives.json'
-
-const DEFAULT_SHARD_COUNT = 16
-const ARCHIVE_NAME_PATTERN = /^store-[0-9a-f]{2}\.tar$/u
-const STORE_VERSION_PATTERN = /^v\d+$/u
-
-interface SeedStoreArchiveRecord {
-  readonly file: string
-  readonly entries: number
-}
-
-interface SeedStoreArchiveManifest {
-  readonly schemaVersion: 1
-  readonly shardCount: number
-  readonly archives: readonly SeedStoreArchiveRecord[]
-}
-
-function storeFiles(storeRoot: string): readonly string[] {
-  const files: string[] = []
-  const visit = (directory: string): void => {
-    for (const entry of readdirSync(directory, { withFileTypes: true })) {
-      const path = join(directory, entry.name)
-      if (entry.isSymbolicLink()) {
-        throw new Error(`desktop seed: pnpm store contains a symbolic link: ${relative(storeRoot, path)}`)
-      }
-      if (entry.isDirectory()) {
-        visit(path)
-        continue
-      }
-      if (!entry.isFile()) {
-        throw new Error(`desktop seed: pnpm store contains an unsupported file: ${relative(storeRoot, path)}`)
-      }
-      files.push(relative(storeRoot, path).split(sep).join('/'))
-    }
-  }
-  visit(storeRoot)
-  return files.sort((left, right) => left.localeCompare(right))
-}
-
-function shardFor(path: string, shardCount: number): number {
-  return createHash('sha256').update(path).digest().readUInt32BE(0) % shardCount
-}
-
-function readArchiveManifest(seedRoot: string): SeedStoreArchiveManifest {
-  const path = join(seedRoot, SEED_STORE_ARCHIVE_MANIFEST)
-  const value = JSON.parse(readFileSync(path, 'utf8')) as unknown
-  if (typeof value !== 'object' || value === null) {
-    throw new Error(`desktop seed: invalid pnpm store archive manifest ${path}`)
-  }
-  const candidate = value as Record<string, unknown>
-  if (candidate.schemaVersion !== 1 || !Number.isSafeInteger(candidate.shardCount)
-    || (candidate.shardCount as number) < 1 || (candidate.shardCount as number) > 256
-    || !Array.isArray(candidate.archives) || candidate.archives.length === 0) {
-    throw new Error(`desktop seed: invalid pnpm store archive manifest ${path}`)
-  }
-  const names = new Set<string>()
-  const archives = candidate.archives.map((entry): SeedStoreArchiveRecord => {
-    if (typeof entry !== 'object' || entry === null) {
-      throw new Error(`desktop seed: invalid pnpm store archive record in ${path}`)
-    }
-    const record = entry as Record<string, unknown>
-    if (typeof record.file !== 'string' || !ARCHIVE_NAME_PATTERN.test(record.file)
-      || names.has(record.file) || !Number.isSafeInteger(record.entries) || (record.entries as number) < 1) {
-      throw new Error(`desktop seed: invalid pnpm store archive record in ${path}`)
-    }
-    const shard = Number.parseInt(record.file.slice('store-'.length, -'.tar'.length), 16)
-    if (shard >= (candidate.shardCount as number)) {
-      throw new Error(`desktop seed: pnpm store archive shard is outside the manifest range in ${path}`)
-    }
-    names.add(record.file)
-    return { file: record.file, entries: record.entries as number }
-  })
-  return {
-    schemaVersion: 1,
-    shardCount: candidate.shardCount as number,
-    archives,
-  }
-}
-
-function assertArchivePath(path: string): void {
-  if (path === '' || path.startsWith('/') || path.includes('\\') || path.includes('\0')
-    || path.split('/').some(part => part === '' || part === '.' || part === '..')) {
-    throw new Error(`desktop seed: unsafe pnpm store archive path ${JSON.stringify(path)}`)
-  }
-}
-
-/**
- * Remove pnpm's registrations for projects that populated the seed store.
- * @param storeRoot - pnpm store directory included in the desktop seed.
- */
-export function removePnpmProjectRegistrations(storeRoot: string): void {
-  for (const entry of readdirSync(storeRoot, { withFileTypes: true })) {
-    if (!entry.isDirectory() || !/^v\d+$/u.test(entry.name)) continue
-    rmSync(join(storeRoot, entry.name, 'projects'), { recursive: true, force: true })
-  }
-}
-
-function mergeStoreIndex(source: string, destination: string): void {
-  if (!existsSync(destination)) {
-    copyFileSync(source, destination)
-    return
-  }
-  const database = new DatabaseSync(destination)
-  let attached = false
-  try {
-    database.exec('PRAGMA busy_timeout=5000')
-    database.prepare('ATTACH DATABASE ? AS seed').run(source)
-    attached = true
-    database.exec('BEGIN IMMEDIATE')
-    let committed = false
-    try {
-      database.exec('INSERT OR REPLACE INTO package_index (key, data) SELECT key, data FROM seed.package_index')
-      database.exec('COMMIT')
-      committed = true
-    } finally {
-      if (!committed) database.exec('ROLLBACK')
-    }
-  } finally {
-    if (attached) database.exec('DETACH DATABASE seed')
-    database.close()
-  }
-}
-
-/**
- * Merge a completely extracted seed store into Desktop's persistent pnpm store.
- * @param source - Verified temporary store extraction.
- * @param destination - Desktop-owned persistent pnpm store.
- */
-export function mergePnpmStore(source: string, destination: string): void {
-  mkdirSync(destination, { recursive: true, mode: 0o700 })
-  const indexPaths = readdirSync(source, { withFileTypes: true })
-    .filter(entry => entry.isDirectory() && STORE_VERSION_PATTERN.test(entry.name)
-      && existsSync(join(source, entry.name, 'index.db')))
-    .map(entry => `${entry.name}/index.db`)
-  const indexes = new Set(indexPaths)
-  cpSync(source, destination, {
-    recursive: true,
-    force: true,
-    filter: path => !indexes.has(relative(source, path).split(sep).join('/')),
-  })
-  for (const path of indexPaths) {
-    mergeStoreIndex(join(source, ...path.split('/')), join(destination, ...path.split('/')))
-  }
-}
-
-/**
- * Replace a prepared loose pnpm store with deterministic uncompressed archive shards.
- * @param seedRoot - seed directory that owns the archive output.
- * @param storeRoot - populated pnpm store to archive and remove after success.
- * @param shardCount - stable shard count used to limit update churn.
- */
-export function archivePnpmStore(
-  seedRoot: string,
-  storeRoot: string,
-  shardCount = DEFAULT_SHARD_COUNT,
-): void {
-  if (!Number.isSafeInteger(shardCount) || shardCount < 1 || shardCount > 256) {
-    throw new Error(`desktop seed: invalid pnpm store shard count ${shardCount}`)
-  }
-  const archiveRoot = join(seedRoot, SEED_STORE_ARCHIVE_DIR)
-  const manifestPath = join(seedRoot, SEED_STORE_ARCHIVE_MANIFEST)
-  rmSync(archiveRoot, { recursive: true, force: true })
-  rmSync(manifestPath, { force: true })
-  mkdirSync(archiveRoot, { recursive: true })
-  const shards = Array.from({ length: shardCount }, (): string[] => [])
-  for (const path of storeFiles(storeRoot)) (shards[shardFor(path, shardCount)] as string[]).push(path)
-  const archives: SeedStoreArchiveRecord[] = []
-  for (const [index, paths] of shards.entries()) {
-    if (paths.length === 0) continue
-    const file = `store-${index.toString(16).padStart(2, '0')}.tar`
-    create({
-      cwd: storeRoot,
-      file: join(archiveRoot, file),
-      noDirRecurse: true,
-      noMtime: true,
-      portable: true,
-      sync: true,
-    }, paths)
-    chmodSync(join(archiveRoot, file), 0o644)
-    archives.push({ file, entries: paths.length })
-  }
-  if (archives.length === 0) throw new Error('desktop seed: pnpm store is empty')
-  writeFileSync(manifestPath, `${JSON.stringify({ schemaVersion: 1, shardCount, archives }, undefined, 2)}\n`)
-  rmSync(storeRoot, { recursive: true })
-}
-
-/**
- * Validate and extract a packaged pnpm store archive set into an empty directory.
- * @param seedRoot - verified packaged seed directory.
- * @param destination - empty Desktop-owned temporary extraction directory.
- */
-export function extractPnpmStoreArchives(seedRoot: string, destination: string): void {
-  const manifest = readArchiveManifest(seedRoot)
-  const archiveRoot = join(seedRoot, SEED_STORE_ARCHIVE_DIR)
-  const actualFiles = readdirSync(archiveRoot, { withFileTypes: true }).map((entry) => {
-    if (!entry.isFile() || entry.isSymbolicLink()) {
-      throw new Error(`desktop seed: invalid pnpm store archive entry ${entry.name}`)
-    }
-    return entry.name
-  }).sort()
-  const expectedFiles = manifest.archives.map(archive => archive.file).sort()
-  if (JSON.stringify(actualFiles) !== JSON.stringify(expectedFiles)) {
-    throw new Error('desktop seed: pnpm store archive set does not match its manifest')
-  }
-  if (existsSync(destination) && readdirSync(destination).length !== 0) {
-    throw new Error(`desktop seed: pnpm store extraction directory is not empty: ${destination}`)
-  }
-  mkdirSync(destination, { recursive: true, mode: 0o700 })
-  const paths = new Set<string>()
-  for (const archive of manifest.archives) {
-    const archivePath = join(archiveRoot, archive.file)
-    const archiveShard = Number.parseInt(archive.file.slice('store-'.length, -'.tar'.length), 16)
-    let entries = 0
-    list({
-      file: archivePath,
-      onReadEntry: (entry) => {
-        if (entry.type !== 'File' && entry.type !== 'OldFile') {
-          throw new Error(`desktop seed: unsupported pnpm store archive entry type ${entry.type}`)
-        }
-        assertArchivePath(entry.path)
-        if (shardFor(entry.path, manifest.shardCount) !== archiveShard) {
-          throw new Error(`desktop seed: pnpm store path is assigned to the wrong archive shard: ${entry.path}`)
-        }
-        if (paths.has(entry.path)) {
-          throw new Error(`desktop seed: duplicate pnpm store archive path ${entry.path}`)
-        }
-        paths.add(entry.path)
-        entries += 1
-      },
-      strict: true,
-      sync: true,
-    })
-    if (entries !== archive.entries) {
-      throw new Error(`desktop seed: pnpm store archive ${archive.file} has an unexpected entry count`)
-    }
-  }
-  for (const archive of manifest.archives) {
-    extract({
-      chmod: true,
-      cwd: destination,
-      file: join(archiveRoot, archive.file),
-      noMtime: true,
-      preservePaths: false,
-      processUmask: 0,
-      strict: true,
-      sync: true,
-    })
-  }
-}

+ 1 - 1
apps/desktop/src/update-coordinator.ts

@@ -1,4 +1,4 @@
-/** One Electron release stream for the version-bound shell and dsh seed. */
+/** One Electron release stream for the version-bound shell and bundled dsh runtime. */
 
 import { existsSync } from 'node:fs'
 import { join } from 'node:path'

+ 3 - 3
apps/desktop/tests/desktop-build-paths.spec.ts

@@ -15,8 +15,8 @@ describe('desktop build paths', () => {
       'artifacts',
       'runtime',
       'packageSet',
-      'seed',
-      'seedPnpm',
+      'dsh',
+      'dshPnpm',
       'nodeExtract',
       'packedDsh',
       'packedVendor',
@@ -27,7 +27,7 @@ describe('desktop build paths', () => {
       expect(new Set([arm64[key], x64[key], windows[key]]).size).toBe(3)
     }
     expect(arm64.artifacts).toContain(join('targets', 'mac-arm64', 'artifacts'))
-    expect(x64.seed).toContain(join('targets', 'mac-x64', 'seed'))
+    expect(x64.dsh).toContain(join('targets', 'mac-x64', 'dsh'))
     expect(windows.runtime).toContain(join('targets', 'win-x64', 'runtime'))
   })
 

+ 28 - 7
apps/desktop/tests/host-process.spec.ts

@@ -1,4 +1,4 @@
-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
 import { tmpdir } from 'node:os'
 import { join } from 'node:path'
 import { afterEach, describe, expect, it } from 'vitest'
@@ -75,6 +75,27 @@ afterEach(() => {
 })
 
 describe('desktop host process', () => {
+  it('loads the resource entry with a separate profile and scrubs Node resolution overrides', async () => {
+    const runtime = projectWithHost(`
+process.send({ type: 'ready', protocolVersion: 3, dshVersion: 'split-runtime' })
+function onRequestFrame(frame) {
+  if (frame.type !== 1) return
+  responseStart(frame.streamId)
+  responseData(frame.streamId, JSON.stringify({runtime: process.argv[2], profile: process.argv[3], cwd: process.cwd(), nodePath: process.env.NODE_PATH}))
+  responseEnd(frame.streamId)
+}
+`)
+    const profile = mkdtempSync(join(tmpdir(), 'desktop-external-profile-'))
+    roots.push(profile)
+    const host = new DesktopHostProcess(process.execPath, runtime, profile, undefined, {
+      ...process.env, NODE_OPTIONS: '--invalid-desktop-test-option', NODE_PATH: '/unowned',
+    })
+    try {
+      const response = await host.fetch(new Request('dsh-app://app/environment'))
+      expect(await response.json()).toEqual({ runtime, profile, cwd: realpathSync(profile) })
+    } finally { await host.stop() }
+  })
+
   it('carries raw request and response bytes and shuts the child down cleanly', async () => {
     const project = projectWithHost(`
 const bodies = new Map()
@@ -98,7 +119,7 @@ function answer(streamId) {
 `)
     const previous = process.env.NODE_OPTIONS
     process.env.NODE_OPTIONS = '--require /path/that-must-not-reach-the-child'
-    const host = new DesktopHostProcess(process.execPath, project)
+    const host = new DesktopHostProcess(process.execPath, project, project)
     try {
       await expect(host.start()).resolves.toMatchObject({ dshVersion: 'clean' })
       const response = await host.fetch(new Request('dsh-app://app/example', { method: 'POST', body: 'request' }))
@@ -124,7 +145,7 @@ function onRequestFrame(frame) {
   responseEnd(frame.streamId)
 }
 `)
-    const host = new DesktopHostProcess(process.execPath, project)
+    const host = new DesktopHostProcess(process.execPath, project, project)
     try {
       const response = await host.fetch(new Request('dsh-app://app/large'))
       const body = new Uint8Array(await response.arrayBuffer())
@@ -151,7 +172,7 @@ function onRequestFrame(frame) {
       start(controller) { controller.enqueue(Buffer.from('first')) },
       cancel() { canceled = true },
     })
-    const host = new DesktopHostProcess(process.execPath, project)
+    const host = new DesktopHostProcess(process.execPath, project, project)
     try {
       const request = new Request('dsh-app://app/early', {
         method: 'POST',
@@ -184,7 +205,7 @@ function onRequestFrame(frame) {
   }
 }
 `)
-    const host = new DesktopHostProcess(process.execPath, project)
+    const host = new DesktopHostProcess(process.execPath, project, project)
     try {
       const canceled = await host.fetch(new Request('dsh-app://app/cancel'))
       await canceled.body?.cancel()
@@ -202,7 +223,7 @@ process.send({ type: 'ready', protocolVersion: 3, dshVersion: 'invalid-frame' })
 function onRequestFrame(frame) {
   if (frame.type === 1) responsePipe.write(Buffer.alloc(13))
 }
-`))
+`), projectWithHost(''))
     await invalid.start()
     await expect(invalid.fetch(new Request('dsh-app://app/invalid'))).rejects.toThrow(/invalid Host response frame marker/u)
     await invalid.stop().catch(() => undefined)
@@ -210,7 +231,7 @@ function onRequestFrame(frame) {
     const earlyExit = new DesktopHostProcess(process.execPath, projectWithHost(`
 function onRequestFrame() {}
 process.exit(0)
-`))
+`), projectWithHost(''))
     await expect(earlyExit.start()).rejects.toThrow(/response pipe ended/u)
   })
 })

+ 48 - 0
apps/desktop/tests/macos-runtime.spec.ts

@@ -0,0 +1,48 @@
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, expect, it, vi } from 'vitest'
+import { signMacOSRuntime } from '../scripts/macos-runtime.ts'
+import { signMacOSRuntimeCode, verifyMacOSRuntimeCode } from '../scripts/verify-macos-signature.mjs'
+
+vi.mock('../scripts/verify-macos-signature.mjs', () => ({ signMacOSRuntimeCode: vi.fn(), verifyMacOSRuntimeCode: vi.fn() }))
+const roots: string[] = []
+function root(): string {
+  const path = mkdtempSync(join(tmpdir(), 'desktop-signing-'))
+  roots.push(path)
+  return path
+}
+const identity = { signingIdentity: 'Example (TEAMID1234)', teamId: 'TEAMID1234' }
+afterEach(() => {
+  vi.resetAllMocks()
+  for (const path of roots.splice(0)) rmSync(path, { recursive: true, force: true })
+})
+it('signs Mach-O files in their final locations and verifies each signature', async () => {
+  const path = root()
+  writeFileSync(join(path, 'addon.node'), Buffer.from('cffaedfe00000000', 'hex'))
+  writeFileSync(join(path, 'source.js'), 'export {}')
+  await expect(signMacOSRuntime(path, 'com.example.app', identity)).resolves.toBe(1)
+  expect(signMacOSRuntimeCode).toHaveBeenCalledWith(join(path, 'addon.node'), expect.stringMatching(/^com\.example\.app\.runtime\.[a-f0-9]{64}$/u), identity)
+  expect(verifyMacOSRuntimeCode).toHaveBeenCalledWith(join(path, 'addon.node'), identity)
+})
+it('awaits other signers before rejecting and permitting output cleanup', async () => {
+  const path = root()
+  for (const name of ['a.node', 'b.node']) writeFileSync(join(path, name), Buffer.from('cffaedfe00000000', 'hex'))
+  let release!: () => void
+  const barrier = new Promise<void>((resolve) => { release = resolve })
+  let started!: () => void
+  const ready = new Promise<void>((resolve) => { started = resolve })
+  vi.mocked(signMacOSRuntimeCode).mockImplementation(async (file) => {
+    if (file.endsWith('a.node')) throw new Error('sign failure')
+    started()
+    await barrier
+  })
+  let completed = false
+  const result = signMacOSRuntime(path, 'com.example.app', identity).catch((error: unknown) => { completed = true; return error })
+  try {
+    await ready
+    expect(completed).toBe(false)
+  } finally { release() }
+  expect(await result).toBeInstanceOf(AggregateError)
+  expect(verifyMacOSRuntimeCode).toHaveBeenCalledWith(join(path, 'b.node'), identity)
+})

+ 0 - 245
apps/desktop/tests/macos-seed-store.spec.ts

@@ -1,245 +0,0 @@
-import { createHash } from 'node:crypto'
-import {
-  appendFileSync,
-  existsSync,
-  mkdirSync,
-  mkdtempSync,
-  readFileSync,
-  rmSync,
-  writeFileSync,
-} from 'node:fs'
-import { tmpdir } from 'node:os'
-import { dirname, join } from 'node:path'
-import { DatabaseSync } from 'node:sqlite'
-import { Packr } from 'msgpackr'
-import { afterEach, describe, expect, it } from 'vitest'
-import {
-  signMacOSSeedStore,
-  verifyMacOSSeedStore,
-} from '../scripts/macos-seed-store.ts'
-
-const temporaryRoots: string[] = []
-const packr = new Packr({ moreTypes: true, useRecords: true })
-const SIGNING_ENVIRONMENT = {
-  signingIdentity: 'Example Company (TEAMID1234)',
-  teamId: 'TEAMID1234',
-}
-
-function temporaryRoot(): string {
-  const root = mkdtempSync(join(tmpdir(), 'dsh-desktop-seed-signing-test-'))
-  temporaryRoots.push(root)
-  return root
-}
-
-function casPath(store: string, body: Buffer, executable = false): { digest: string; path: string } {
-  const digest = createHash('sha512').update(body).digest('hex')
-  return {
-    digest,
-    path: join(store, 'v11', 'files', digest.slice(0, 2), `${digest.slice(2)}${executable ? '-exec' : ''}`),
-  }
-}
-
-function createStoreFile(path: string, body: Buffer): void {
-  mkdirSync(dirname(path), { recursive: true })
-  writeFileSync(path, body)
-}
-
-afterEach(() => {
-  for (const root of temporaryRoots.splice(0)) rmSync(root, { recursive: true, force: true })
-})
-
-describe('desktop macOS seed store signing', () => {
-  it('rehashes signed Mach-O content, rewrites every package reference, and prunes native orphans', async () => {
-    const store = temporaryRoot()
-    const native = Buffer.concat([Buffer.from('cffaedfe', 'hex'), Buffer.from('native-code')])
-    const nativeCas = casPath(store, native)
-    createStoreFile(nativeCas.path, native)
-    const orphan = Buffer.concat([Buffer.from('cafebabe', 'hex'), Buffer.from('orphan')])
-    const orphanCas = casPath(store, orphan)
-    createStoreFile(orphanCas.path, orphan)
-    const plain = Buffer.from('plain package content')
-    const plainCas = casPath(store, plain)
-    createStoreFile(plainCas.path, plain)
-
-    const database = new DatabaseSync(join(store, 'v11', 'index.db'))
-    database.exec('CREATE TABLE package_index (key TEXT PRIMARY KEY, data BLOB NOT NULL) WITHOUT ROWID')
-    const insert = database.prepare('INSERT INTO package_index (key, data) VALUES (?, ?)')
-    for (const key of ['package-a', 'package-b']) {
-      insert.run(key, packr.pack({
-        algo: 'sha512',
-        files: new Map([
-          ['native.node', { checkedAt: 1, digest: nativeCas.digest, mode: 0o644, size: native.length }],
-          ['index.js', { checkedAt: 1, digest: plainCas.digest, mode: 0o644, size: plain.length }],
-        ]),
-        sideEffects: key === 'package-b'
-          ? new Map([['build', { added: new Map([
-            ['built/native.node', { checkedAt: 1, digest: nativeCas.digest, mode: 0o644, size: native.length }],
-          ]) }]])
-          : undefined,
-      }))
-    }
-    database.close()
-
-    const result = await signMacOSSeedStore(
-      store,
-      'com.example.desktop',
-      SIGNING_ENVIRONMENT,
-      {
-        signer: async (path, identifier) => {
-          expect(identifier).toBe(`com.example.desktop.seed.${nativeCas.digest.slice(0, 32)}`)
-          appendFileSync(path, 'signed')
-        },
-      },
-    )
-
-    expect(result).toEqual({ signedFiles: 1, prunedOrphans: 1, updatedIndexRows: 2 })
-    expect(existsSync(nativeCas.path)).toBe(false)
-    expect(existsSync(orphanCas.path)).toBe(false)
-    expect(readFileSync(plainCas.path)).toEqual(plain)
-
-    const updated = new DatabaseSync(join(store, 'v11', 'index.db'), { readOnly: true })
-    const digests = [...updated.prepare('SELECT data FROM package_index').iterate() as Iterable<{ data: Uint8Array }>]
-      .flatMap((row) => {
-        const record = packr.unpack(row.data) as {
-          files: Map<string, { digest: string }>
-          sideEffects?: Map<string, { added: Map<string, { digest: string }> }>
-        }
-        return [
-          record.files.get('native.node')?.digest,
-          ...[...(record.sideEffects?.values() ?? [])].map(effect => effect.added.get('built/native.node')?.digest),
-        ].filter((digest): digest is string => digest !== undefined)
-      })
-    updated.close()
-    expect(new Set(digests).size).toBe(1)
-    expect(digests).toHaveLength(3)
-    expect(digests[0]).not.toBe(nativeCas.digest)
-
-    const verified: string[] = []
-    expect(verifyMacOSSeedStore(store, SIGNING_ENVIRONMENT, (path) => { verified.push(path) })).toBe(1)
-    expect(verified).toHaveLength(1)
-  })
-
-  it('bounds concurrent signing while allowing independent Mach-O files to overlap', async () => {
-    const store = temporaryRoot()
-    const files = new Map<string, { checkedAt: number; digest: string; mode: number; size: number }>()
-    for (let index = 0; index < 6; index += 1) {
-      const body = Buffer.concat([Buffer.from('feedfacf', 'hex'), Buffer.from(`native-${index}`)])
-      const nativeCas = casPath(store, body)
-      createStoreFile(nativeCas.path, body)
-      files.set(`native-${index}.node`, {
-        checkedAt: 1,
-        digest: nativeCas.digest,
-        mode: 0o644,
-        size: body.length,
-      })
-    }
-    const database = new DatabaseSync(join(store, 'v11', 'index.db'))
-    database.exec('CREATE TABLE package_index (key TEXT PRIMARY KEY, data BLOB NOT NULL) WITHOUT ROWID')
-    database.prepare('INSERT INTO package_index (key, data) VALUES (?, ?)')
-      .run('package', packr.pack({ algo: 'sha512', files }))
-    database.close()
-
-    let started = 0
-    let active = 0
-    let maximumActive = 0
-    let releaseSigning = (): void => {}
-    const signingReleased = new Promise<void>((resolve) => { releaseSigning = resolve })
-    let markFirstWaveReady = (): void => {}
-    const firstWaveReady = new Promise<void>((resolve) => { markFirstWaveReady = resolve })
-    const signing = signMacOSSeedStore(store, 'com.example.desktop', SIGNING_ENVIRONMENT, {
-      concurrency: 4,
-      signer: async () => {
-        started += 1
-        active += 1
-        maximumActive = Math.max(maximumActive, active)
-        if (started === 4) markFirstWaveReady()
-        try {
-          await signingReleased
-        } finally {
-          active -= 1
-        }
-      },
-    })
-
-    await firstWaveReady
-    expect({ started, active, maximumActive }).toEqual({ started: 4, active: 4, maximumActive: 4 })
-    releaseSigning()
-    await expect(signing).resolves.toMatchObject({ signedFiles: 6, updatedIndexRows: 1 })
-    expect({ started, active, maximumActive }).toEqual({ started: 6, active: 0, maximumActive: 4 })
-  })
-
-  it('awaits active signers and preserves the store when one signer fails', async () => {
-    const store = temporaryRoot()
-    const originals: { digest: string; path: string }[] = []
-    const files = new Map<string, { checkedAt: number; digest: string; mode: number; size: number }>()
-    for (let index = 0; index < 2; index += 1) {
-      const body = Buffer.concat([Buffer.from('feedfacf', 'hex'), Buffer.from(`native-${index}`)])
-      const nativeCas = casPath(store, body)
-      originals.push(nativeCas)
-      createStoreFile(nativeCas.path, body)
-      files.set(`native-${index}.node`, {
-        checkedAt: 1,
-        digest: nativeCas.digest,
-        mode: 0o644,
-        size: body.length,
-      })
-    }
-    const databasePath = join(store, 'v11', 'index.db')
-    const database = new DatabaseSync(databasePath)
-    database.exec('CREATE TABLE package_index (key TEXT PRIMARY KEY, data BLOB NOT NULL) WITHOUT ROWID')
-    database.prepare('INSERT INTO package_index (key, data) VALUES (?, ?)')
-      .run('package', packr.pack({ algo: 'sha512', files }))
-    database.close()
-    const originalIndex = readFileSync(databasePath)
-
-    let started = 0
-    let settled = 0
-    let releaseSigning = (): void => {}
-    const signingReleased = new Promise<void>((resolve) => { releaseSigning = resolve })
-    let markBothReady = (): void => {}
-    const bothReady = new Promise<void>((resolve) => { markBothReady = resolve })
-    const signing = signMacOSSeedStore(store, 'com.example.desktop', SIGNING_ENVIRONMENT, {
-      concurrency: 2,
-      signer: async () => {
-        started += 1
-        const call = started
-        if (started === 2) markBothReady()
-        try {
-          await signingReleased
-          if (call === 1) throw new Error('signing failed')
-        } finally {
-          settled += 1
-        }
-      },
-    })
-
-    await bothReady
-    releaseSigning()
-    await expect(signing).rejects.toThrow(/signing failed/u)
-    expect({ started, settled }).toEqual({ started: 2, settled: 2 })
-    expect(readFileSync(databasePath)).toEqual(originalIndex)
-    for (const original of originals) expect(existsSync(original.path)).toBe(true)
-  })
-
-  it('rejects an invalid signing worker bound before starting a signer', async () => {
-    const store = temporaryRoot()
-    mkdirSync(join(store, 'v11', 'files'), { recursive: true })
-    await expect(signMacOSSeedStore(store, 'com.example.desktop', SIGNING_ENVIRONMENT, {
-      concurrency: 0,
-      signer: async () => {},
-    })).rejects.toThrow(/positive integer/u)
-  })
-
-  it('propagates a signature-verification failure', () => {
-    const store = temporaryRoot()
-    const native = Buffer.concat([Buffer.from('feedfacf', 'hex'), Buffer.from('native-code')])
-    const nativeCas = casPath(store, native)
-    createStoreFile(nativeCas.path, native)
-
-    expect(() => {
-      verifyMacOSSeedStore(store, SIGNING_ENVIRONMENT, () => {
-        throw new Error('invalid signature')
-      })
-    }).toThrow(/invalid signature/u)
-  })
-})

+ 41 - 8
apps/desktop/tests/macos-signature.spec.ts

@@ -1,3 +1,10 @@
+import { mkdtempSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join, relative } from 'node:path'
+import { createRequire } from 'node:module'
+import { FileMatcher } from 'app-builder-lib/out/fileMatcher.js'
+import { runtimeFixture } from './runtime-fixture.ts'
+import { verifyDesktopRuntime } from '../src/runtime-tree.ts'
 import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
 import type { NotarizeOptions } from '@electron/notarize'
 import {
@@ -7,10 +14,15 @@ import {
 } from '../scripts/desktop-release-environment.mjs'
 import { notarizeMacOSDiskImageArtifact } from '../scripts/notarize-macos-disk-images.mjs'
 import {
-  assertMacOSSeedSignatureDetails,
+  assertMacOSRuntimeSignatureDetails,
   assertMacOSSignatureDetails,
 } from '../scripts/verify-macos-signature.mjs'
 
+// app-builder-lib omits this internal copier from its declarations; the regression exercises its actual file filter.
+const { copyFiles } = createRequire(import.meta.url)('app-builder-lib/out/fileMatcher.js') as {
+  copyFiles: (matchers: FileMatcher[]) => Promise<void>
+}
+
 const RELEASE_ENVIRONMENT = {
   DSH_DESKTOP_APP_ID: 'com.example.desktop',
   DSH_DESKTOP_TARGET_PLATFORM: 'darwin',
@@ -40,17 +52,18 @@ describe('desktop macOS release signature', () => {
     const { createElectronBuilderConfig } = await import('../electron-builder.config.mjs')
     const config = createElectronBuilderConfig(RELEASE_ENVIRONMENT, 'darwin', 'arm64')
     expect(portablePath(config.directories.output)).toContain('/.desktop-build/targets/mac-arm64/artifacts')
-    expect(config.extraResources).toHaveLength(2)
+    expect(config.extraResources).toHaveLength(3)
     expect(config.extraResources[0]?.to).toBe('runtime')
-    expect(config.extraResources[1]?.to).toBe('seed')
+    expect(config.extraResources[1]?.to).toBe('dsh')
     expect(portablePath(config.extraResources[0]?.from ?? '')).toContain('/.desktop-build/targets/mac-arm64/runtime')
-    expect(portablePath(config.extraResources[1]?.from ?? '')).toContain('/.desktop-build/targets/mac-arm64/seed')
+    expect(portablePath(config.extraResources[1]?.from ?? '')).toContain('/.desktop-build/targets/mac-arm64/dsh')
     expect(config).toMatchObject({
       appId: RELEASE_ENVIRONMENT.DSH_DESKTOP_APP_ID,
       mac: {
         identity: RELEASE_ENVIRONMENT.DSH_DESKTOP_MACOS_SIGNING_IDENTITY,
         forceCodeSigning: true,
         notarize: true,
+        signIgnore: ['/Contents/Resources/dsh(?:/|$)'],
       },
       dmg: {
         sign: true,
@@ -64,6 +77,26 @@ describe('desktop macOS release signature', () => {
     expect(typeof config.artifactBuildCompleted).toBe('function')
   })
 
+  it('copies the complete runtime despite electron-builder excluding root node_modules', async () => {
+    const { createElectronBuilderConfig } = await import('../electron-builder.config.mjs')
+    const config = createElectronBuilderConfig(RELEASE_ENVIRONMENT, 'darwin', 'arm64')
+    const root = mkdtempSync(join(tmpdir(), 'desktop-resource-copy-'))
+    try {
+      const source = join(root, 'source')
+      const destination = join(root, 'resources')
+      runtimeFixture(source)
+      const sourceRoot = config.extraResources[1].from
+      const matchers = config.extraResources.slice(1).map(entry => new FileMatcher(
+        join(source, relative(sourceRoot, entry.from)), join(destination, entry.to), value => value,
+      ))
+      await copyFiles(matchers.slice(0, 1))
+      expect(() => verifyDesktopRuntime(join(destination, 'dsh'), '1.0.0')).toThrow(/integrity/u)
+      rmSync(destination, { recursive: true })
+      await copyFiles(matchers)
+      expect(() => verifyDesktopRuntime(join(destination, 'dsh'), '1.0.0')).not.toThrow()
+    } finally { rmSync(root, { recursive: true, force: true }) }
+  })
+
   it('validates Windows signing without requiring macOS identifiers for a Windows target', async () => {
     const { createElectronBuilderConfig } = await import('../electron-builder.config.mjs')
     expect(() => createElectronBuilderConfig({
@@ -82,7 +115,7 @@ describe('desktop macOS release signature', () => {
     }).not.toThrow()
   })
 
-  it('requires a secure timestamp and hardened runtime for seed code', () => {
+  it('requires a secure timestamp and hardened runtime for runtime code', () => {
     const expected = resolveMacOSSigningEnvironment(RELEASE_ENVIRONMENT)
     const details = [
       `Authority=Developer ID Application: ${expected.signingIdentity}`,
@@ -90,12 +123,12 @@ describe('desktop macOS release signature', () => {
       'Timestamp=31 Aug 2026 at 20:00:00',
       'CodeDirectory v=20500 size=773 flags=0x10000(runtime) hashes=13+7 location=embedded',
     ].join('\n')
-    expect(() => { assertMacOSSeedSignatureDetails(details, expected) }).not.toThrow()
+    expect(() => { assertMacOSRuntimeSignatureDetails(details, expected) }).not.toThrow()
     expect(() => {
-      assertMacOSSeedSignatureDetails(details.replace(/^Timestamp=.*\n/um, ''), expected)
+      assertMacOSRuntimeSignatureDetails(details.replace(/^Timestamp=.*\n/um, ''), expected)
     }).toThrow(/secure timestamp/u)
     expect(() => {
-      assertMacOSSeedSignatureDetails(details.replace('flags=0x10000(runtime)', 'flags=0x0(none)'), expected)
+      assertMacOSRuntimeSignatureDetails(details.replace('flags=0x10000(runtime)', 'flags=0x0(none)'), expected)
     }).toThrow(/hardened runtime/u)
   })
 

+ 1 - 1
apps/desktop/tests/package-target.spec.ts

@@ -56,7 +56,7 @@ describe('desktop package target', () => {
     expect(desktopElectronBuilderArguments(target, true)).toContain('--dir')
   })
 
-  it('keeps Windows signing fields out of build and seed preparation subprocesses', () => {
+  it('keeps Windows signing fields out of build and runtime preparation subprocesses', () => {
     expect(withoutWindowsSigningEnvironment({
       DSH_DESKTOP_WINDOWS_CER_FILE: 'C:\\release\\server.cer',
       DSH_DESKTOP_WINDOWS_TOKEN_PIN: 'token-secret',

+ 33 - 0
apps/desktop/tests/plugin-manager.spec.ts

@@ -0,0 +1,33 @@
+import { readFileSync } from 'node:fs'
+import { runInContext } from 'node:vm'
+import { JSDOM } from 'jsdom'
+import { expect, it, vi } from 'vitest'
+import { resolveDesktopLocale } from '../src/locale.ts'
+
+it('keeps disabled packages visible and offers recovery without a running backend', async () => {
+  const dom = new JSDOM(readFileSync(new URL('../renderer/plugin-manager.html', import.meta.url), 'utf8'), { runScripts: 'outside-only' })
+  let enabled = true
+  let ready = false
+  const disableAll = vi.fn(async () => { enabled = false; ready = true })
+  const toggle = vi.fn(async (_name: string, active: boolean) => { enabled = active })
+  const api = {
+    locale: async () => resolveDesktopLocale('en'),
+    backend: { status: async () => ({ ready, error: ready ? undefined : 'plugin requires Cordis ^2.0.0' }), retry: vi.fn() },
+    plugins: { list: async () => [{ name: 'example-plugin', version: '1.0.0', enabled }], disableAll, toggle },
+  }
+  Object.defineProperty(dom.window, 'dshDesktop', { value: api })
+  try {
+    runInContext(readFileSync(new URL('../renderer/plugin-manager.js', import.meta.url), 'utf8'), dom.getInternalVMContext())
+    const document = dom.window.document
+    await expect.poll(() => document.querySelector('#plugins li')?.textContent).toContain('example-plugin')
+    expect(document.querySelector<HTMLElement>('#recovery')?.hidden).toBe(false)
+    expect(document.querySelector('#startup-error')?.textContent).toBe('plugin requires Cordis ^2.0.0')
+    document.querySelector<HTMLButtonElement>('#disable-all')?.click()
+    await expect.poll(() => document.querySelector<HTMLElement>('#recovery')?.hidden).toBe(true)
+    expect(disableAll).toHaveBeenCalledOnce()
+    expect(document.querySelector('#plugins li')?.textContent).toMatchInlineSnapshot('"example-plugin1.0.0 · DisabledEnableUpdateRemove"')
+    document.querySelector<HTMLButtonElement>('#plugins li button')?.click()
+    await expect.poll(() => toggle.mock.calls).toEqual([['example-plugin', true]])
+    await expect.poll(() => document.querySelector('#plugins li')?.textContent).toBe('example-plugin1.0.0DisableUpdateRemove')
+  } finally { dom.window.close() }
+})

+ 72 - 0
apps/desktop/tests/plugin-pnpm.spec.ts

@@ -0,0 +1,72 @@
+import { createHash } from 'node:crypto'
+import { execFileSync } from 'node:child_process'
+import { createServer } from 'node:http'
+import { mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { pathToFileURL } from 'node:url'
+import { c } from 'tar'
+import { expect, it } from 'vitest'
+import { DesktopProjectManager, type DesktopProjectHooks } from '../src/project-manager.ts'
+import { resolveDesktopPaths } from '../src/paths.ts'
+import { runtimeFixture, writePackage } from './runtime-fixture.ts'
+
+it('installs a real pnpm graph, then executes approved scripts with the shared host instance', async () => {
+  const root = realpathSync(mkdtempSync(join(tmpdir(), 'desktop-real-pnpm-')))
+  const server = createServer()
+  const archives = new Map<string, Buffer>()
+  try {
+    for (const name of ['fixture-plugin', 'node-pty']) {
+      const path = writePackage(join(root, 'packages'), name, name === 'fixture-plugin'
+        ? { dependencies: { 'node-pty': '1.0.0' }, peerDependencies: { '@deepseek-ai/cordis': '^1.0.0' }, dsh: { bundle: { patch: 'bundle.yml' } } }
+        : { scripts: { install: 'node install.cjs' } }, 'export {identity} from "@deepseek-ai/cordis"')
+      writeFileSync(join(path, 'bundle.yml'), '[]\n')
+      writeFileSync(join(path, 'install.cjs'), 'require("node:fs").writeFileSync("built.json", JSON.stringify({node:process.execPath, host:require.resolve("@deepseek-ai/cordis")}))')
+      const tarball = join(root, `${name}.tgz`)
+      await c({ file: tarball, cwd: join(path, '..'), gzip: true }, [name])
+      archives.set(name, readFileSync(tarball))
+    }
+    await new Promise<void>((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve) })
+    const address = server.address()
+    if (address === null || typeof address === 'string') throw new Error('fixture registry has no TCP address')
+    const origin = `http://127.0.0.1:${address.port}`
+    server.on('request', (request, response) => {
+      const name = request.url?.slice(1).replace(/\.tgz$/u, '') ?? ''
+      const archive = archives.get(name)
+      if (archive === undefined) { response.writeHead(404); response.end(); return }
+      if (request.url?.endsWith('.tgz')) { response.end(archive); return }
+      response.setHeader('content-type', 'application/json')
+      response.end(JSON.stringify({ name, 'dist-tags': { latest: '1.0.0' }, versions: { '1.0.0': {
+        name, version: '1.0.0', dist: { tarball: `${origin}/${name}.tgz`, integrity: `sha512-${createHash('sha512').update(archive).digest('base64')}` },
+        ...(name === 'fixture-plugin' ? { dependencies: { 'node-pty': '1.0.0' }, peerDependencies: { '@deepseek-ai/cordis': '^1.0.0' } } : {}),
+      } }, time: { '1.0.0': '2020-01-01T00:00:00.000Z' } }))
+    })
+    const dsh = join(root, 'dsh')
+    runtimeFixture(dsh)
+    const pnpm = join(root, 'pnpm.mjs')
+    const realPnpm = join(import.meta.dirname, '../node_modules/pnpm/bin/pnpm.mjs')
+    writeFileSync(pnpm, `process.argv = process.argv.map(arg => arg === '--config.registry=https://registry.npmjs.org/' ? ${JSON.stringify(`--config.registry=${origin}`)} : arg); await import(${JSON.stringify(pathToFileURL(realPnpm).href)})`)
+    const manager = new DesktopProjectManager(resolveDesktopPaths(join(root, '.dsh')), { node: process.execPath, pnpm, dsh })
+    const hooks: DesktopProjectHooks = { healthCheck: async () => {}, beforeActivate: async () => {}, afterActivate: async () => {} }
+    await manager.applyRelease('1.0.0', hooks)
+    await manager.mutate({ type: 'plugin-add', spec: 'fixture-plugin@1.0.0' }, hooks)
+    expect(manager.listPlugins()).toEqual([{ name: 'fixture-plugin', version: '1.0.0', enabled: true }])
+    const built = JSON.parse(readFileSync(join(manager.paths.profile, 'node_modules/node-pty/built.json'), 'utf8')) as { node: string; host: string }
+    expect(realpathSync(built.node)).toBe(realpathSync(process.execPath))
+    expect(built.host).toBe(join(dsh, 'node_modules/@deepseek-ai/cordis/index.js'))
+    const entry = join(dsh, 'identity.mjs')
+    writeFileSync(entry, `import {identity} from '@deepseek-ai/cordis'; import {identity as plugin} from ${JSON.stringify(pathToFileURL(join(manager.paths.profile, 'node_modules/fixture-plugin/index.js')).href)}; console.log(identity === plugin)`)
+    expect(execFileSync(process.execPath, [entry], { encoding: 'utf8' }).trim()).toBe('true')
+    await manager.mutate({ type: 'plugin-remove', name: 'fixture-plugin' }, hooks)
+    expect(manager.listPlugins()).toEqual([])
+  } finally {
+    server.closeAllConnections()
+    if (server.listening) await new Promise<void>((resolve, reject) => {
+      server.close((error) => {
+        if (error !== undefined) reject(error)
+        else resolve()
+      })
+    })
+    rmSync(root, { recursive: true, force: true })
+  }
+}, 30_000)

+ 81 - 0
apps/desktop/tests/profile-packages.spec.ts

@@ -0,0 +1,81 @@
+import { execFileSync } from 'node:child_process'
+import { mkdtempSync, readFileSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { pathToFileURL } from 'node:url'
+import { afterEach, expect, it } from 'vitest'
+import { createPluginProfile } from '../src/project-manager.ts'
+import { copyDesktopProfile, linkDesktopHostPackages, unlinkDesktopHostPackages, validateDesktopPluginGraph } from '../src/profile-packages.ts'
+import { runtimeFixture, writePackage } from './runtime-fixture.ts'
+
+const roots: string[] = []
+function fixture() {
+  const root = mkdtempSync(join(tmpdir(), 'desktop-profile-'))
+  roots.push(root)
+  const dsh = join(root, 'dsh')
+  const runtime = runtimeFixture(dsh)
+  const profile = join(root, 'profile')
+  createPluginProfile(profile)
+  linkDesktopHostPackages(profile, dsh, runtime)
+  return { root, dsh, runtime, profile }
+}
+afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) })
+
+it('loads one shared ESM instance from both host and external plugin while keeping ordinary dependencies private', () => {
+  const { dsh, runtime, profile } = fixture()
+  writePackage(join(dsh, 'node_modules'), 'ordinary', {}, 'export default "host"')
+  writePackage(join(profile, 'node_modules'), 'ordinary', {}, 'export default "plugin"')
+  const plugin = writePackage(join(profile, 'node_modules'), 'plugin', {
+    peerDependencies: { '@deepseek-ai/cordis': '^1.0.0' }, dependencies: { ordinary: '1.0.0' },
+  }, 'export { identity } from "@deepseek-ai/cordis"; export { default as ordinary } from "ordinary"')
+  validateDesktopPluginGraph(profile, dsh, runtime, ['plugin'])
+  const entry = join(dsh, 'check.mjs')
+  writeFileSync(entry, `import {identity} from '@deepseek-ai/cordis'; import ordinary from 'ordinary'; import * as plugin from ${JSON.stringify(pathToFileURL(join(plugin, 'index.js')).href)}; console.log(JSON.stringify({same:identity===plugin.identity, host:ordinary, plugin:plugin.ordinary}))`)
+  const output = execFileSync(process.execPath, [entry], { encoding: 'utf8', env: { ...process.env, NODE_OPTIONS: '', NODE_PATH: '' } })
+  expect(JSON.parse(output)).toEqual({ same: true, host: 'host', plugin: 'plugin' })
+})
+it.each(['nested', 'alias'])('rejects a %s second copy of a host package', (placement) => {
+  const { dsh, runtime, profile } = fixture()
+  const plugin = writePackage(join(profile, 'node_modules'), 'plugin')
+  if (placement === 'nested') writePackage(join(plugin, 'node_modules'), '@deepseek-ai/cordis')
+  else writePackage(join(profile, 'node_modules'), 'alias', { name: '@deepseek-ai/cordis' })
+  expect(() =>{  validateDesktopPluginGraph(profile, dsh, runtime, ['plugin']) }).toThrow(/duplicate or aliased/u)
+})
+it('rejects a host package declared as an ordinary dependency', () => {
+  const { dsh, runtime, profile } = fixture()
+  writePackage(join(profile, 'node_modules'), 'plugin', { dependencies: { '@deepseek-ai/cordis': '^1.0.0' } })
+  expect(() =>{  validateDesktopPluginGraph(profile, dsh, runtime, ['plugin']) }).toThrow(/peer dependency/u)
+})
+it('rejects incompatible peers only when the plugin is enabled', () => {
+  const { dsh, runtime, profile } = fixture()
+  writePackage(join(profile, 'node_modules'), 'plugin', { peerDependencies: { '@deepseek-ai/cordis': '^2.0.0' } })
+  expect(() =>{  validateDesktopPluginGraph(profile, dsh, runtime, ['plugin']) }).toThrow(/found 1.0.0/u)
+  expect(() =>{  validateDesktopPluginGraph(profile, dsh, runtime, []) }).not.toThrow()
+})
+it('refuses to satisfy a plugin dependency from an ancestor CLI project', () => {
+  const { root, dsh, runtime, profile } = fixture()
+  writePackage(join(root, 'node_modules'), 'ambient')
+  writePackage(join(profile, 'node_modules'), 'plugin', { dependencies: { ambient: '1.0.0' } })
+  expect(() =>{  validateDesktopPluginGraph(profile, dsh, runtime, ['plugin']) }).toThrow(/outside its owned packages/u)
+})
+it('copies writable plugin bytes independently and removes broken owned links without following them', () => {
+  const { root, profile } = fixture()
+  writePackage(join(profile, 'node_modules'), 'plugin')
+  copyDesktopProfile(profile, join(root, 'copy'))
+  writeFileSync(join(root, 'copy/node_modules/plugin/index.js'), 'changed')
+  expect(readFileSync(join(profile, 'node_modules/plugin/index.js'), 'utf8')).toContain('identity')
+  rmSync(join(root, 'dsh'), { recursive: true })
+  expect(() =>{  unlinkDesktopHostPackages(profile) }).not.toThrow()
+})
+it('refuses to replace an unowned package at a managed name', () => {
+  const { profile } = fixture()
+  unlinkSync(join(profile, 'node_modules/@deepseek-ai/cordis'))
+  writePackage(join(profile, 'node_modules'), '@deepseek-ai/cordis')
+  expect(() =>{  unlinkDesktopHostPackages(profile) }).toThrow(/unowned package/u)
+})
+it('rejects private package links instead of following cycles or old transaction paths', () => {
+  const { dsh, runtime, profile } = fixture()
+  const plugin = writePackage(join(profile, 'node_modules'), 'plugin')
+  symlinkSync(plugin, join(profile, 'node_modules/alias'), process.platform === 'win32' ? 'junction' : 'dir')
+  expect(() =>{  validateDesktopPluginGraph(profile, dsh, runtime, ['plugin']) }).toThrow(/linked private package/u)
+})

+ 171 - 346
apps/desktop/tests/project-manager.spec.ts

@@ -1,392 +1,217 @@
-import { createHash } from 'node:crypto'
-import { existsSync, mkdtempSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
+import { existsSync, mkdtempSync, mkdirSync, readFileSync, renameSync, rmSync, unlinkSync, realpathSync, writeFileSync } from 'node:fs'
 import { tmpdir } from 'node:os'
-import { dirname, join, relative, sep } from 'node:path'
+import { dirname, join } from 'node:path'
 import { pathToFileURL } from 'node:url'
 import { afterEach, describe, expect, it } from 'vitest'
 import { resolveDesktopPaths } from '../src/paths.ts'
-import {
-  createSeedMetadata,
-  DesktopProjectManager,
-  packageNameFromSpec,
-  verifySeedIntegrity,
-  type DesktopProjectHooks,
-} from '../src/project-manager.ts'
-import { DESKTOP_HOST_PROTOCOL_VERSION } from '../src/host-protocol.ts'
-import { DESKTOP_PACKAGES_DIR, DESKTOP_PACKAGE_SET_FILE } from '../src/core-package-set.ts'
-import type { DesktopRelease } from '../src/release.ts'
-import { archivePnpmStore } from '../src/seed-store.ts'
+import { DesktopProjectManager, packageNameFromSpec, type DesktopProjectHooks } from '../src/project-manager.ts'
+import { readDesktopProfileState } from '../src/profile-packages.ts'
+import { runtimeFixture } from './runtime-fixture.ts'
 
 const roots: string[] = []
-
 function temporaryRoot(): string {
   const root = mkdtempSync(join(tmpdir(), 'dsh-desktop-test-'))
   roots.push(root)
   return root
 }
-
-function writeIntegrity(seed: string): void {
-  const paths: string[] = []
-  const visit = (directory: string): void => {
-    for (const entry of readdirSync(directory, { withFileTypes: true })) {
-      const path = join(directory, entry.name)
-      if (entry.isDirectory()) visit(path)
-      else if (entry.name !== 'integrity.json') paths.push(path)
-    }
-  }
-  visit(seed)
-  const files = paths.sort().map((path) => {
-    const body = readFileSync(path)
-    return {
-      path: relative(seed, path).split(sep).join('/'),
-      bytes: statSync(path).size,
-      sha256: createHash('sha256').update(body).digest('hex'),
-    }
-  })
-  writeFileSync(join(seed, 'integrity.json'), `${JSON.stringify({ schemaVersion: 2, files })}\n`)
-}
-
-function archiveStore(seed: string): void {
-  const store = join(seed, 'store')
-  mkdirSync(store, { recursive: true })
-  if (readdirSync(store).length === 0) writeFileSync(join(store, 'test-entry'), 'content')
-  archivePnpmStore(seed, store)
-}
-
-function writeCorePackageSet(seed: string, version: string): void {
-  const packages = [
-    { name: '@deepseek-ai/dsh', file: `deepseek-ai-dsh-${version}.tgz`, body: Buffer.from(`dsh-${version}`) },
-    {
-      name: '@deepseek-ai/dsh-desktop-host',
-      file: `deepseek-ai-dsh-desktop-host-${version}.tgz`,
-      body: Buffer.from(`desktop-host-${version}`),
-    },
-  ]
-  mkdirSync(join(seed, DESKTOP_PACKAGES_DIR), { recursive: true })
-  for (const entry of packages) writeFileSync(join(seed, DESKTOP_PACKAGES_DIR, entry.file), entry.body)
-  writeFileSync(join(seed, DESKTOP_PACKAGE_SET_FILE), `${JSON.stringify({
-    schemaVersion: 1,
-    packages: packages.map(({ name, file, body }) => ({
-      name,
-      version,
-      file,
-      bytes: body.byteLength,
-      integrity: `sha512-${createHash('sha512').update(body).digest('base64')}`,
-    })),
-  })}\n`)
-}
-
-function createTestSeedMetadata(seed: string, desktopRelease: DesktopRelease): void {
-  writeCorePackageSet(seed, desktopRelease.version)
-  createSeedMetadata(seed, desktopRelease)
-}
-
 function writeFakePnpm(root: string): string {
   const path = join(root, 'pnpm.mjs')
-  writeFileSync(path, String.raw`
-import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
-import { dirname, join } from 'node:path'
+  writeFileSync(path, `
+import { appendFileSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
 const args = process.argv.slice(2)
 const project = process.cwd()
-const command = args.find(value => value === 'install' || value === 'add' || value === 'remove')
-const manifestPath = join(project, 'package.json')
-const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'))
-const packageName = spec => spec.startsWith('@')
-  ? spec.slice(0, spec.indexOf('@', spec.indexOf('/') + 1) === -1 ? undefined : spec.indexOf('@', spec.indexOf('/') + 1))
-  : spec.split('@')[0]
-const packageVersion = spec => {
-  const index = spec.startsWith('@') ? spec.indexOf('@', spec.indexOf('/') + 1) : spec.indexOf('@')
-  return index === -1 ? '1.0.0' : spec.slice(index + 1)
-}
-
-if (command === 'add') {
-  const spec = args[args.indexOf('add') + 1]
-  manifest.dependencies[packageName(spec)] = packageVersion(spec)
-}
-if (command === 'remove') delete manifest.dependencies[args[args.indexOf('remove') + 1]]
-writeFileSync(manifestPath, JSON.stringify(manifest))
-rmSync(join(project, 'node_modules'), { recursive: true, force: true })
-for (const [name, version] of Object.entries(manifest.dependencies)) {
-  const packageRoot = join(project, 'node_modules', ...name.split('/'))
-  mkdirSync(packageRoot, { recursive: true })
-  const core = name === '@deepseek-ai/dsh' || name === '@deepseek-ai/dsh-desktop-host'
-  const plugin = !core
-  const installedVersion = plugin
-    ? version
-    : JSON.parse(readFileSync(join(project, 'desktop-release.json'), 'utf8')).version
-  writeFileSync(join(packageRoot, 'package.json'), JSON.stringify({
-    name, version: installedVersion,
-    ...(plugin ? { dsh: { bundle: { patch: './bundle.yml' } } } : {}),
-  }))
-  if (plugin) writeFileSync(join(packageRoot, 'bundle.yml'), '[]\n')
-  else if (name === '@deepseek-ai/dsh-desktop-host') {
-    mkdirSync(join(packageRoot, 'lib'), { recursive: true })
-    writeFileSync(join(packageRoot, 'lib', 'index.js'), '')
+const command = args.find(value => ['install', 'add', 'remove', 'rebuild'].includes(value))
+appendFileSync(${JSON.stringify(join(root, 'pnpm-log.jsonl'))}, JSON.stringify({args, registry: process.env.NPM_CONFIG_REGISTRY}) + '\\n')
+if (command !== 'rebuild') {
+  const manifestPath = join(project, 'package.json')
+  const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'))
+  if (command === 'add') {
+    const spec = args[args.indexOf(command) + 1]
+    const index = spec.lastIndexOf('@')
+    const name = index > 0 ? spec.slice(0, index) : spec
+    manifest.dependencies[name] = index > 0 ? spec.slice(index + 1) : '1.0.0'
   }
+  if (command === 'remove') delete manifest.dependencies[args[args.indexOf(command) + 1]]
+  writeFileSync(manifestPath, JSON.stringify(manifest))
+  rmSync(join(project, 'node_modules'), { recursive: true, force: true })
+  for (const [name, version] of Object.entries(manifest.dependencies)) {
+    const packageRoot = join(project, 'node_modules', name)
+    mkdirSync(packageRoot, { recursive: true })
+    writeFileSync(join(packageRoot, 'package.json'), JSON.stringify({name, version,
+      peerDependencies: {'@deepseek-ai/cordis': '^1.0.0'}, dsh: {bundle: {patch: './bundle.yml'}}}))
+    writeFileSync(join(packageRoot, 'bundle.yml'), '[]\\n')
+  }
+  writeFileSync(join(project, 'pnpm-lock.yaml'), JSON.stringify(manifest.dependencies))
 }
-writeFileSync(join(project, 'pnpm-lock.yaml'), 'lockfileVersion: 9\n')
-if (process.env.TEST_PNPM_LOG) writeFileSync(process.env.TEST_PNPM_LOG, JSON.stringify({ args, env: process.env }))
-`)
-  return path
-}
-
-function writeBlockingFakePnpm(root: string, ready: string, release: string): string {
-  const path = join(root, 'blocking-pnpm.mjs')
-  const delegate = writeFakePnpm(root)
-  writeFileSync(path, `
-import { existsSync, writeFileSync } from 'node:fs'
-import { setTimeout as sleep } from 'node:timers/promises'
-writeFileSync(${JSON.stringify(ready)}, String(process.pid))
-while (!existsSync(${JSON.stringify(release)})) await sleep(10)
-await import(${JSON.stringify(pathToFileURL(delegate).href)})
 `)
   return path
 }
-
 function hooks(overrides: Partial<DesktopProjectHooks> = {}): DesktopProjectHooks {
-  return {
-    healthCheck: async () => {},
-    beforeActivate: async () => {},
-    afterActivate: async () => {},
-    ...overrides,
-  }
+  return { healthCheck: async () => {}, beforeActivate: async () => {}, afterActivate: async () => {}, ...overrides }
 }
-
-function release(version = '1.0.0'): DesktopRelease {
-  return {
-    schemaVersion: 1,
-    version,
-    hostProtocolVersion: DESKTOP_HOST_PROTOCOL_VERSION,
-    nodeVersion: '24.17.0',
-    pnpmVersion: '11.7.0',
-  }
+function setup(): { root: string; manager: DesktopProjectManager } {
+  const root = temporaryRoot()
+  const dsh = join(root, 'resources', 'dsh')
+  runtimeFixture(dsh)
+  return { root, manager: new DesktopProjectManager(resolveDesktopPaths(join(root, '.dsh')), { node: process.execPath, pnpm: writeFakePnpm(root), dsh }) }
 }
+function calls(root: string): { args: string[]; registry: string }[] {
+  const path = join(root, 'pnpm-log.jsonl')
+  return existsSync(path) ? readFileSync(path, 'utf8').trim().split('\n').map(line => JSON.parse(line) as { args: string[]; registry: string }) : []
+}
+afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) })
 
-afterEach(() => {
-  for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })
-})
-
-describe('desktop package policy', () => {
-  it('accepts registry package specs but rejects alternate sources and flags', () => {
+describe('desktop external plugin profile', () => {
+  it('accepts registry names and tags but rejects alternate sources and flags', () => {
     expect(packageNameFromSpec('@scope/plugin@1.2.3')).toBe('@scope/plugin')
     expect(packageNameFromSpec('plugin@next')).toBe('plugin')
-    expect(() => packageNameFromSpec('file:../plugin')).toThrow(/unsupported npm package spec/u)
-    expect(() => packageNameFromSpec('--registry=evil')).toThrow(/unsupported npm package spec/u)
-    expect(() => packageNameFromSpec('https://example.test/plugin.tgz')).toThrow(/unsupported npm package spec/u)
-  })
-
-  it('rejects any seed content changed after release inventory generation', () => {
-    const seed = join(temporaryRoot(), 'seed')
-    createTestSeedMetadata(seed, release())
-    writeFileSync(join(seed, 'pnpm-lock.yaml'), 'lockfileVersion: 9\n')
-    writeIntegrity(seed)
-    expect(() => { verifySeedIntegrity(seed) }).not.toThrow()
-    writeFileSync(join(seed, 'package.json'), '{}\n')
-    expect(() => { verifySeedIntegrity(seed) }).toThrow(/integrity verification failed/u)
-  })
-})
-
-describe('desktop project transactions', () => {
-  it('installs the offline seed and reconciles a mismatched private Host', async () => {
-    const root = temporaryRoot()
-    const seed = join(root, 'seed')
-    const log = join(root, 'pnpm-log.json')
-    createTestSeedMetadata(seed, release())
-    writeFileSync(join(seed, 'pnpm-lock.yaml'), 'lockfileVersion: 9\n')
-    mkdirSync(join(seed, 'store'), { recursive: true })
-    writeFileSync(join(seed, 'store', 'seed-entry'), 'content')
-    archiveStore(seed)
-    writeIntegrity(seed)
-    const paths = resolveDesktopPaths(join(root, '.dsh'))
-    const manager = new DesktopProjectManager(paths, { node: process.execPath, pnpm: writeFakePnpm(root) })
-    const previousLog = process.env.TEST_PNPM_LOG
-    const previousRegistry = process.env.npm_config_registry
-    process.env.TEST_PNPM_LOG = log
-    process.env.npm_config_registry = 'https://user-registry.invalid'
-    try {
-      await expect(manager.applyRelease(seed, '2.0.0', hooks())).rejects.toThrow(/does not match Electron/u)
-      await manager.applyRelease(seed, '1.0.0', hooks())
-      writeFileSync(
-        join(paths.profile, 'node_modules', '@deepseek-ai', 'dsh-desktop-host', 'package.json'),
-        '{"name":"@deepseek-ai/dsh-desktop-host","version":"0.9.0"}\n',
-      )
-      await expect(manager.applyRelease(seed, '1.0.0', hooks())).resolves.toBe(true)
-    } finally {
-      if (previousLog === undefined) delete process.env.TEST_PNPM_LOG
-      else process.env.TEST_PNPM_LOG = previousLog
-      if (previousRegistry === undefined) delete process.env.npm_config_registry
-      else process.env.npm_config_registry = previousRegistry
+    for (const spec of ['file:../plugin', '--registry=evil', 'https://example.test/plugin.tgz']) {
+      expect(() => packageNameFromSpec(spec)).toThrow(/unsupported npm package spec/u)
     }
-    expect(manager.dshVersion()).toBe('1.0.0')
-    expect(manager.releaseVersion()).toBe('1.0.0')
-    expect(paths.profile).toBe(join(root, '.dsh', 'profiles', 'desktop'))
-    expect(existsSync(join(paths.profile, 'node_modules', '@deepseek-ai', 'dsh'))).toBe(true)
-    const installedHost = JSON.parse(readFileSync(
-      join(paths.profile, 'node_modules', '@deepseek-ai', 'dsh-desktop-host', 'package.json'),
-      'utf8',
-    )) as { version: string }
-    expect(installedHost.version).toBe('1.0.0')
-    expect(existsSync(join(paths.profile, 'desktop-plugins.json'))).toBe(false)
-    expect(readFileSync(join(paths.pnpm.store, 'seed-entry'), 'utf8')).toBe('content')
-    const invocation = JSON.parse(readFileSync(log, 'utf8')) as { args: string[]; env: Record<string, string> }
-    expect(invocation.args).toContain('--offline')
-    expect(invocation.args).toContain('--trust-lockfile')
-    expect(invocation.args).toContain(`--config.store-dir=${paths.pnpm.store}`)
-    expect(invocation.args).toContain('--config.enable-global-virtual-store=false')
-    expect(invocation.args).toContain('--config.registry=https://registry.npmjs.org/')
-    expect(invocation.env.NPM_CONFIG_REGISTRY).toBe('https://registry.npmjs.org/')
-    expect(invocation.env.NPM_CONFIG_STORE_DIR).toBe(paths.pnpm.store)
-    expect(invocation.env.NPM_CONFIG_USERCONFIG).toBe(join(paths.pnpm.config, 'npmrc'))
-    expect(invocation.env.npm_config_registry).toBeUndefined()
   })
 
-  it('restores the active project when the replacement backend cannot start', async () => {
-    const root = temporaryRoot()
-    const seed = join(root, 'seed')
-    createTestSeedMetadata(seed, release())
-    writeFileSync(join(seed, 'pnpm-lock.yaml'), 'lockfileVersion: 9\n')
-    archiveStore(seed)
-    writeIntegrity(seed)
-    const paths = resolveDesktopPaths(join(root, '.dsh'))
-    const manager = new DesktopProjectManager(paths, { node: process.execPath, pnpm: writeFakePnpm(root) })
-    await manager.applyRelease(seed, '1.0.0', hooks())
-    let starts = 0
-    await expect(manager.mutate({ type: 'plugin-add', spec: '@scope/plugin@2.0.0' }, hooks({
-      afterActivate: async () => {
-        starts += 1
-        if (starts === 1) throw new Error('backend rejected staged graph')
-      },
-    }))).rejects.toThrow(/backend rejected staged graph/u)
+  it('initializes and restarts offline without executing pnpm', async () => {
+    const { root, manager } = setup()
+    await expect(manager.applyRelease('2.0.0', hooks())).rejects.toThrow(/does not match Electron/u)
+    await expect(manager.applyRelease('1.0.0', hooks())).resolves.toBe(true)
+    await expect(manager.applyRelease('1.0.0', hooks())).resolves.toBe(false)
     expect(manager.listPlugins()).toEqual([])
-    expect(manager.dshVersion()).toBe('1.0.0')
-    expect(starts).toBe(2)
+    expect(calls(root)).toEqual([])
+    expect(existsSync(manager.paths.pnpm.store)).toBe(false)
+    expect(realpathSync(join(manager.paths.profile, 'node_modules/@deepseek-ai/cordis'))).toBe(realpathSync(join(manager.runtime.dsh, 'node_modules/@deepseek-ai/cordis')))
+    expect(JSON.parse(readFileSync(join(manager.paths.profile, 'package.json'), 'utf8'))).toMatchObject({ dependencies: {} })
   })
 
-  it('restores rollback when the active move completed before its journal update', async () => {
-    const root = temporaryRoot()
-    const seed = join(root, 'seed')
-    createTestSeedMetadata(seed, release())
-    writeFileSync(join(seed, 'pnpm-lock.yaml'), 'lockfileVersion: 9\n')
-    archiveStore(seed)
-    writeIntegrity(seed)
-    const paths = resolveDesktopPaths(join(root, '.dsh'))
-    const manager = new DesktopProjectManager(paths, { node: process.execPath, pnpm: writeFakePnpm(root) })
-    await manager.applyRelease(seed, '1.0.0', hooks())
-    await manager.mutate({ type: 'plugin-add', spec: '@scope/plugin@2.0.0' }, hooks())
-    const stagingProfile = join(paths.staging, 'interrupted', 'profile')
-    mkdirSync(stagingProfile, { recursive: true })
-    writeFileSync(join(stagingProfile, 'marker'), 'staging')
-    rmSync(paths.rollback, { recursive: true, force: true })
-    mkdirSync(dirname(paths.rollback), { recursive: true })
-    renameSync(paths.profile, paths.rollback)
-    writeFileSync(paths.pending, `${JSON.stringify({
-      schemaVersion: 1,
-      id: 'interrupted',
-      stagingProfile,
-      step: 'prepared',
-    })}\n`)
+  it('repairs a removed managed link without running pnpm', async () => {
+    const { root, manager } = setup()
+    await manager.applyRelease('1.0.0', hooks())
+    unlinkSync(join(manager.paths.profile, 'node_modules/@deepseek-ai/cordis'))
+    await expect(manager.applyRelease('1.0.0', hooks())).resolves.toBe(true)
+    expect(calls(root)).toEqual([])
+  })
 
-    manager.recover()
+  it('installs only plugins and checks the graph before running lifecycle scripts', async () => {
+    const { root, manager } = setup()
+    await manager.applyRelease('1.0.0', hooks())
+    await manager.mutate({ type: 'plugin-add', spec: '@scope/plugin@2.0.0' }, hooks())
+    expect(manager.listPlugins()).toEqual([{ name: '@scope/plugin', version: '2.0.0', enabled: true }])
+    expect(calls(root).map(call => call.args.filter(arg => !arg.startsWith('--config.')))).toEqual([
+      ['add', '@scope/plugin@2.0.0', '--save-exact', '--ignore-scripts'], ['rebuild', '--pending'],
+    ])
+    expect(calls(root).every(call => call.registry === 'https://registry.npmjs.org/')).toBe(true)
+    expect(JSON.parse(readFileSync(join(manager.paths.profile, 'package.json'), 'utf8'))).toMatchObject({ dependencies: { '@scope/plugin': '2.0.0' } })
+    await expect(manager.mutate({ type: 'plugin-add', spec: '@deepseek-ai/cordis' }, hooks())).rejects.toThrow(/host-owned/u)
+  })
 
-    expect(manager.listPlugins()).toEqual([{ name: '@scope/plugin', version: '2.0.0' }])
-    expect(existsSync(stagingProfile)).toBe(false)
-    expect(existsSync(paths.pending)).toBe(false)
+  it('retains disabled plugin versions through updates and enables them explicitly', async () => {
+    const { root, manager } = setup()
+    await manager.applyRelease('1.0.0', hooks())
+    await manager.mutate({ type: 'plugin-add', spec: 'plugin@1.0.0' }, hooks())
+    await manager.mutate({ type: 'plugins-disable-all' }, hooks())
+    expect(calls(root)).toHaveLength(2)
+    expect(manager.listPlugins()).toEqual([{ name: 'plugin', version: '1.0.0', enabled: false }])
+    await manager.mutate({ type: 'plugin-update', name: 'plugin', version: '1.1.0' }, hooks())
+    expect(manager.listPlugins()).toEqual([{ name: 'plugin', version: '1.1.0', enabled: false }])
+    await manager.mutate({ type: 'plugin-toggle', name: 'plugin', enabled: true }, hooks())
+    expect(manager.listPlugins()[0]?.enabled).toBe(true)
+    await manager.mutate({ type: 'plugin-remove', name: 'plugin' }, hooks())
+    expect(manager.listPlugins()).toEqual([])
   })
 
-  it('records the live pnpm worker as transaction owner until it exits', async () => {
-    const root = temporaryRoot()
-    const seed = join(root, 'seed')
-    const ready = join(root, 'pnpm-ready')
-    const releaseWorker = join(root, 'pnpm-release')
-    createTestSeedMetadata(seed, release())
-    writeFileSync(join(seed, 'pnpm-lock.yaml'), 'lockfileVersion: 9\n')
-    archiveStore(seed)
-    writeIntegrity(seed)
-    const paths = resolveDesktopPaths(join(root, '.dsh'))
-    const runtime = { node: process.execPath, pnpm: writeBlockingFakePnpm(root, ready, releaseWorker) }
-    const manager = new DesktopProjectManager(paths, runtime)
-    const installing = manager.applyRelease(seed, '1.0.0', hooks())
-    await expect.poll(() => existsSync(ready)).toBe(true)
-    const workerPid = Number.parseInt(readFileSync(ready, 'utf8'), 10)
-    expect(readFileSync(paths.lock, 'utf8')).toBe(`${String(workerPid)}\n`)
-    const competing = new DesktopProjectManager(paths, runtime)
-    await expect(competing.applyRelease(seed, '1.0.0', hooks())).rejects.toThrow(/another package transaction is active/u)
-    writeFileSync(releaseWorker, 'continue')
-    await expect(installing).resolves.toBe(true)
-    expect(existsSync(paths.lock)).toBe(false)
+  it('keeps plugin files and patches through a compatible release and application relocation', async () => {
+    const { root, manager } = setup()
+    await manager.applyRelease('1.0.0', hooks())
+    await manager.mutate({ type: 'plugin-add', spec: 'plugin@1.0.0' }, hooks())
+    writeFileSync(join(manager.paths.profile, 'cordis.patch.yml'), '[]\n')
+    const nextRoot = join(root, 'relocated', 'dsh')
+    runtimeFixture(nextRoot, '1.1.0')
+    const next = new DesktopProjectManager(manager.paths, { ...manager.runtime, dsh: nextRoot })
+    await expect(next.applyRelease('1.1.0', hooks())).resolves.toBe(true)
+    expect(next.listPlugins()).toEqual(manager.listPlugins())
+    expect(next.releaseVersion()).toBe('1.1.0')
+    expect(readFileSync(join(manager.paths.profile, 'cordis.patch.yml'), 'utf8')).toBe('[]\n')
+    expect(calls(root)).toHaveLength(2)
+    expect(realpathSync(join(manager.paths.profile, 'node_modules/@deepseek-ai/cordis'))).toBe(realpathSync(join(nextRoot, 'node_modules/@deepseek-ai/cordis')))
+    writeFileSync(join(manager.paths.rollback, 'node_modules/plugin/bundle.yml'), 'rollback only')
+    expect(readFileSync(join(manager.paths.profile, 'node_modules/plugin/bundle.yml'), 'utf8')).toBe('[]\n')
   })
 
-  it('keeps core packages local while installing plugins from the desktop registry', async () => {
-    const root = temporaryRoot()
-    const seed = join(root, 'seed')
-    const log = join(root, 'pnpm-log.json')
-    createTestSeedMetadata(seed, release())
-    writeFileSync(join(seed, 'pnpm-lock.yaml'), 'lockfileVersion: 9\n')
-    archiveStore(seed)
-    writeIntegrity(seed)
-    const paths = resolveDesktopPaths(join(root, '.dsh'))
-    const manager = new DesktopProjectManager(paths, { node: process.execPath, pnpm: writeFakePnpm(root) })
-    await manager.applyRelease(seed, '1.0.0', hooks())
-    const previousLog = process.env.TEST_PNPM_LOG
-    process.env.TEST_PNPM_LOG = log
-    try {
-      await manager.mutate({ type: 'plugin-add', spec: '@scope/plugin@2.0.0' }, hooks())
-    } finally {
-      if (previousLog === undefined) delete process.env.TEST_PNPM_LOG
-      else process.env.TEST_PNPM_LOG = previousLog
-    }
+  it('reinstalls the locked plugin graph when bundled Node changes', async () => {
+    const { root, manager } = setup()
+    await manager.applyRelease('1.0.0', hooks())
+    await manager.mutate({ type: 'plugin-add', spec: 'plugin@1.0.0' }, hooks())
+    const dsh = join(root, 'new-node')
+    runtimeFixture(dsh, '1.1.0', '24.18.0')
+    const next = new DesktopProjectManager(manager.paths, { ...manager.runtime, dsh })
+    await next.applyRelease('1.1.0', hooks())
+    expect(calls(root).slice(2).map(call => call.args.filter(arg => !arg.startsWith('--config.')))).toEqual([
+      ['install', '--frozen-lockfile', '--ignore-scripts'], ['rebuild', '--pending'],
+    ])
+    expect(next.listPlugins()).toEqual([{ name: 'plugin', version: '1.0.0', enabled: true }])
+  })
 
-    const manifest = JSON.parse(readFileSync(join(paths.profile, 'package.json'), 'utf8')) as {
-      dependencies: Record<string, string>
-    }
-    const coreSpec = manifest.dependencies['@deepseek-ai/dsh']
-    expect(coreSpec).toMatch(/^file:\.\/desktop-packages\//u)
-    expect(readFileSync(join(paths.profile, 'pnpm-workspace.yaml'), 'utf8'))
-      .toContain(`${JSON.stringify('@deepseek-ai/dsh')}: ${JSON.stringify(coreSpec)}`)
-    expect(manifest.dependencies['@scope/plugin']).toBe('2.0.0')
-    const invocation = JSON.parse(readFileSync(log, 'utf8')) as { args: string[]; env: Record<string, string> }
-    expect(invocation.args).toContain('add')
-    expect(invocation.args).toContain('@scope/plugin@2.0.0')
-    expect(invocation.args).toContain('--config.registry=https://registry.npmjs.org/')
-    expect(invocation.env.NPM_CONFIG_REGISTRY).toBe('https://registry.npmjs.org/')
+  it('allows incompatible plugins to be disabled in recovery without deleting them', async () => {
+    const { root, manager } = setup()
+    await manager.applyRelease('1.0.0', hooks())
+    await manager.mutate({ type: 'plugin-add', spec: 'plugin@1.0.0' }, hooks())
+    const dsh = join(root, 'next-major')
+    runtimeFixture(dsh, '2.0.0')
+    const next = new DesktopProjectManager(manager.paths, { ...manager.runtime, dsh })
+    await expect(next.applyRelease('2.0.0', hooks())).rejects.toThrow(/requires @deepseek-ai\/cordis/u)
+    expect(next.releaseVersion()).toBe('1.0.0')
+    expect(() =>{  next.assertProfileRuntime(manager.paths.profile) }).toThrow(/does not match/u)
+    await next.mutate({ type: 'plugins-disable-all' }, hooks())
+    expect(next.releaseVersion()).toBe('2.0.0')
+    expect(next.listPlugins()).toEqual([{ name: 'plugin', version: '1.0.0', enabled: false }])
   })
 
-  it('reconciles dsh to the packaged release without removing desktop plugins', async () => {
-    const root = temporaryRoot()
-    const paths = resolveDesktopPaths(join(root, '.dsh'))
-    const manager = new DesktopProjectManager(paths, { node: process.execPath, pnpm: writeFakePnpm(root) })
-    const firstSeed = join(root, 'seed-1')
-    createTestSeedMetadata(firstSeed, release('1.0.0'))
-    writeFileSync(join(firstSeed, 'pnpm-lock.yaml'), 'lockfileVersion: 9\n')
-    mkdirSync(join(firstSeed, 'store'), { recursive: true })
-    writeFileSync(join(firstSeed, 'store', 'release-1'), 'one')
-    archiveStore(firstSeed)
-    writeIntegrity(firstSeed)
-    await manager.applyRelease(firstSeed, '1.0.0', hooks())
-    await manager.mutate({ type: 'plugin-add', spec: '@scope/plugin@2.0.0' }, hooks())
+  it.each(['health', 'before', 'after'] as const)('keeps the active profile when %s activation fails', async (phase) => {
+    const { manager } = setup()
+    await manager.applyRelease('1.0.0', hooks())
+    let starts = 0
+    await expect(manager.mutate({ type: 'plugin-add', spec: 'plugin@1.0.0' }, hooks({
+      healthCheck: async () => { if (phase === 'health') throw new Error('health failed') },
+      beforeActivate: async () => { if (phase === 'before') throw new Error('before failed') },
+      afterActivate: async () => { if (phase === 'after' && starts++ === 0) throw new Error('after failed') },
+    }))).rejects.toThrow(`${phase} failed`)
+    expect(manager.listPlugins()).toEqual([])
+    expect(existsSync(manager.paths.pending)).toBe(false)
+  })
 
-    const nextSeed = join(root, 'seed-2')
-    createTestSeedMetadata(nextSeed, release('1.1.0'))
-    writeFileSync(join(nextSeed, 'pnpm-lock.yaml'), 'lockfileVersion: 9\n')
-    mkdirSync(join(nextSeed, 'store'), { recursive: true })
-    writeFileSync(join(nextSeed, 'store', 'release-2'), 'two')
-    archiveStore(nextSeed)
-    writeIntegrity(nextSeed)
+  it('recovers a directory move using recorded runtime identities', async () => {
+    const { manager } = setup()
+    await manager.applyRelease('1.0.0', hooks())
+    const id = readDesktopProfileState(manager.paths.profile)?.runtimeId
+    const stagingProfile = join(manager.paths.staging, 'interrupted', 'profile')
+    mkdirSync(stagingProfile, { recursive: true })
+    mkdirSync(dirname(manager.paths.rollback), { recursive: true })
+    renameSync(manager.paths.profile, manager.paths.rollback)
+    writeFileSync(manager.paths.pending, JSON.stringify({ schemaVersion: 1, id: 'interrupted', stagingProfile, fromRuntimeId: id, toRuntimeId: id, step: 'active-moved' }))
+    manager.recover()
+    expect(manager.releaseVersion()).toBe('1.0.0')
+    expect(existsSync(stagingProfile)).toBe(false)
+    expect(existsSync(manager.paths.pending)).toBe(false)
+  })
 
-    await expect(manager.applyRelease(nextSeed, '1.1.0', hooks())).resolves.toBe(true)
-    expect(manager.releaseVersion()).toBe('1.1.0')
-    expect(manager.dshVersion()).toBe('1.1.0')
-    expect(manager.listPlugins()).toEqual([{ name: '@scope/plugin', version: '2.0.0' }])
-    const profile = JSON.parse(readFileSync(join(paths.profile, 'package.json'), 'utf8')) as {
-      dsh: { profile: { bundles: string[] } }
+  it('holds the transaction lock until the pnpm worker exits', async () => {
+    const { root, manager } = setup()
+    await manager.applyRelease('1.0.0', hooks())
+    const ready = join(root, 'ready')
+    const release = join(root, 'release')
+    const blocker = join(root, 'blocking.mjs')
+    writeFileSync(blocker, `import {existsSync, writeFileSync} from 'node:fs'; import {setTimeout as sleep} from 'node:timers/promises'; writeFileSync(${JSON.stringify(ready)}, String(process.pid)); while (!existsSync(${JSON.stringify(release)})) await sleep(10); await import(${JSON.stringify(pathToFileURL(manager.runtime.pnpm).href)})`)
+    const worker = new DesktopProjectManager(manager.paths, { ...manager.runtime, pnpm: blocker })
+    await worker.applyRelease('1.0.0', hooks())
+    const pending = worker.mutate({ type: 'plugin-add', spec: 'plugin@1.0.0' }, hooks())
+    try {
+      await expect.poll(() => existsSync(ready)).toBe(true)
+      expect(readFileSync(manager.paths.lock, 'utf8').trim()).toBe(readFileSync(ready, 'utf8'))
+      await expect(manager.applyRelease('1.0.0', hooks())).rejects.toThrow(/another package transaction/u)
+    } finally {
+      writeFileSync(release, 'continue')
+      await pending
     }
-    expect(profile.dsh.profile.bundles).toEqual([
-      '@deepseek-ai/dsh-base',
-      '@deepseek-ai/dsh-web-app',
-      '@scope/plugin',
-    ])
-    expect(readFileSync(join(paths.pnpm.store, 'release-1'), 'utf8')).toBe('one')
-    expect(readFileSync(join(paths.pnpm.store, 'release-2'), 'utf8')).toBe('two')
-    await expect(manager.applyRelease(nextSeed, '1.1.0', hooks())).resolves.toBe(false)
+    expect(existsSync(manager.paths.lock)).toBe(false)
   })
 })

+ 42 - 0
apps/desktop/tests/runtime-fixture.ts

@@ -0,0 +1,42 @@
+/** Temporary materialized packages for Desktop resource and profile behavior tests. */
+
+import { mkdirSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { DESKTOP_HOST_RUNTIME_FILES } from '../src/core-package-set.ts'
+import { DESKTOP_HOST_PROTOCOL_VERSION } from '../src/host-protocol.ts'
+import { writeDesktopRuntime, type DesktopRuntimeDescriptor } from '../src/runtime-tree.ts'
+
+/**
+ * Write a package fixture with explicit runtime exports.
+ * @param modules - Owning node_modules directory.
+ * @param name - Package name.
+ * @param fields - Manifest fields.
+ * @param source - ESM entry contents.
+ * @returns Installed package directory.
+ */
+export function writePackage(modules: string, name: string, fields: Record<string, unknown> = {}, source = 'export const identity = {}\n'): string {
+  const path = join(modules, name)
+  mkdirSync(path, { recursive: true })
+  writeFileSync(join(path, 'package.json'), JSON.stringify({ name, version: '1.0.0', type: 'module', exports: './index.js', ...fields }))
+  writeFileSync(join(path, 'index.js'), source)
+  return path
+}
+
+/**
+ * Seal a minimal release containing Host entry files and a shared Cordis package.
+ * @param root - New runtime directory.
+ * @param version - Shell and dsh version.
+ * @param nodeVersion - Bundled Node version used for native rebuild selection.
+ * @returns Sealed runtime metadata.
+ */
+export function runtimeFixture(root: string, version = '1.0.0', nodeVersion = '24.17.0'): DesktopRuntimeDescriptor {
+  const names = ['@deepseek-ai/dsh', '@deepseek-ai/dsh-desktop-host', '@deepseek-ai/dsh-base', '@deepseek-ai/dsh-web-app', '@deepseek-ai/cordis']
+  for (const name of names) writePackage(join(root, 'node_modules'), name, { version })
+  for (const file of DESKTOP_HOST_RUNTIME_FILES) {
+    const path = join(root, 'node_modules', '@deepseek-ai/dsh-desktop-host', file)
+    mkdirSync(join(path, '..'), { recursive: true })
+    writeFileSync(path, '')
+  }
+  writeFileSync(join(root, 'package.json'), '{"type":"module"}\n')
+  return writeDesktopRuntime(root, { schemaVersion: 1, version, nodeVersion, pnpmVersion: '11.7.0', hostProtocolVersion: DESKTOP_HOST_PROTOCOL_VERSION }, names)
+}

+ 46 - 0
apps/desktop/tests/runtime-tree.spec.ts

@@ -0,0 +1,46 @@
+import { cpSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, expect, it } from 'vitest'
+import { DESKTOP_RUNTIME_FILE, desktopRuntimeId, runtimePath, verifyDesktopRuntime } from '../src/runtime-tree.ts'
+import { runtimeFixture } from './runtime-fixture.ts'
+
+const roots: string[] = []
+function fixture(): string {
+  const root = mkdtempSync(join(tmpdir(), 'desktop-runtime-'))
+  roots.push(root)
+  runtimeFixture(join(root, 'dsh'))
+  return root
+}
+afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) })
+
+it('verifies a runtime after relocation without depending on build paths', () => {
+  const root = fixture()
+  const before = verifyDesktopRuntime(join(root, 'dsh'), '1.0.0')
+  cpSync(join(root, 'dsh'), join(root, 'moved'), { recursive: true })
+  expect(desktopRuntimeId(verifyDesktopRuntime(join(root, 'moved'), '1.0.0'))).toBe(desktopRuntimeId(before))
+})
+it.each(['changed', 'extra', 'missing'])('rejects %s runtime bytes', (operation) => {
+  const dsh = join(fixture(), 'dsh')
+  if (operation === 'changed') writeFileSync(join(dsh, 'package.json'), '{}')
+  if (operation === 'extra') writeFileSync(join(dsh, 'extra'), '')
+  if (operation === 'missing') rmSync(join(dsh, 'package.json'))
+  expect(() => verifyDesktopRuntime(dsh, '1.0.0')).toThrow(/integrity/u)
+})
+it('rejects filesystem links and incompatible targets', () => {
+  const dsh = join(fixture(), 'dsh')
+  expect(() => verifyDesktopRuntime(dsh, '1.0.0', { platform: process.platform, arch: 'wrong' })).toThrow(/incompatible/u)
+  symlinkSync(join(dsh, 'node_modules'), join(dsh, 'outside'), process.platform === 'win32' ? 'junction' : 'dir')
+  expect(() => verifyDesktopRuntime(dsh, '1.0.0')).toThrow(/unsupported filesystem/u)
+})
+it('rejects a descriptor that maps a shared package outside node_modules', () => {
+  const dsh = join(fixture(), 'dsh')
+  const path = join(dsh, DESKTOP_RUNTIME_FILE)
+  const descriptor = JSON.parse(readFileSync(path, 'utf8')) as { sharedPackages: { path: string }[] }
+  descriptor.sharedPackages[0]!.path = '../outside'
+  writeFileSync(path, JSON.stringify(descriptor))
+  expect(() => verifyDesktopRuntime(dsh, '1.0.0')).toThrow(/shared package record/u)
+})
+it.each(['../outside', '/absolute', 'C:/absolute', 'a\\b', 'a//b', './a'])('rejects nonportable path %s', (path) => {
+  expect(() => runtimePath('/runtime', path)).toThrow(/invalid relative path/u)
+})

+ 0 - 167
apps/desktop/tests/seed-store.spec.ts

@@ -1,167 +0,0 @@
-import {
-  chmodSync,
-  existsSync,
-  mkdirSync,
-  mkdtempSync,
-  readFileSync,
-  readdirSync,
-  rmSync,
-  statSync,
-  utimesSync,
-  writeFileSync,
-} from 'node:fs'
-import { tmpdir } from 'node:os'
-import { join } from 'node:path'
-import { DatabaseSync } from 'node:sqlite'
-import { afterEach, describe, expect, it } from 'vitest'
-import {
-  archivePnpmStore,
-  extractPnpmStoreArchives,
-  mergePnpmStore,
-  removePnpmProjectRegistrations,
-  SEED_STORE_ARCHIVE_DIR,
-  SEED_STORE_ARCHIVE_MANIFEST,
-} from '../src/seed-store.ts'
-
-const temporaryRoots: string[] = []
-
-function temporaryRoot(): string {
-  const root = mkdtempSync(join(tmpdir(), 'dsh-desktop-store-'))
-  temporaryRoots.push(root)
-  return root
-}
-
-function archiveBytes(seed: string): readonly { path: string; body: Buffer }[] {
-  return [SEED_STORE_ARCHIVE_MANIFEST, ...readdirSync(join(seed, SEED_STORE_ARCHIVE_DIR))]
-    .map(path => ({
-      path,
-      body: readFileSync(path === SEED_STORE_ARCHIVE_MANIFEST
-        ? join(seed, path)
-        : join(seed, SEED_STORE_ARCHIVE_DIR, path)),
-    }))
-}
-
-afterEach(() => {
-  for (const root of temporaryRoots.splice(0)) rmSync(root, { recursive: true, force: true })
-})
-
-describe('desktop seed store cleanup', () => {
-  it('removes project registrations without removing package data', () => {
-    const storeRoot = temporaryRoot()
-    mkdirSync(join(storeRoot, 'v11', 'projects', 'temporary-project'), { recursive: true })
-    mkdirSync(join(storeRoot, 'v12', 'projects'), { recursive: true })
-    mkdirSync(join(storeRoot, 'metadata', 'projects'), { recursive: true })
-    writeFileSync(join(storeRoot, 'v11', 'package-data'), 'package')
-
-    removePnpmProjectRegistrations(storeRoot)
-
-    expect(existsSync(join(storeRoot, 'v11', 'projects'))).toBe(false)
-    expect(existsSync(join(storeRoot, 'v12', 'projects'))).toBe(false)
-    expect(existsSync(join(storeRoot, 'v11', 'package-data'))).toBe(true)
-    expect(existsSync(join(storeRoot, 'metadata', 'projects'))).toBe(true)
-  })
-})
-
-describe('desktop seed store merge', () => {
-  it('preserves installed package records while the verified seed replaces matching records and files', () => {
-    const root = temporaryRoot()
-    const source = join(root, 'source')
-    const destination = join(root, 'destination')
-    for (const store of [source, destination]) {
-      mkdirSync(join(store, 'v11', 'files'), { recursive: true })
-      const database = new DatabaseSync(join(store, 'v11', 'index.db'))
-      database.exec('CREATE TABLE package_index (key TEXT PRIMARY KEY, data BLOB NOT NULL) WITHOUT ROWID')
-      const insert = database.prepare('INSERT INTO package_index (key, data) VALUES (?, ?)')
-      if (store === source) {
-        insert.run('seed-only', Buffer.from('seed'))
-        insert.run('shared', Buffer.from('new'))
-      } else {
-        insert.run('plugin-only', Buffer.from('plugin'))
-        insert.run('shared', Buffer.from('old'))
-      }
-      database.close()
-    }
-    writeFileSync(join(source, 'v11', 'files', 'shared'), 'new')
-    writeFileSync(join(destination, 'v11', 'files', 'shared'), 'old')
-    writeFileSync(join(destination, 'v11', 'files', 'plugin'), 'plugin')
-
-    mergePnpmStore(source, destination)
-
-    const database = new DatabaseSync(join(destination, 'v11', 'index.db'), { readOnly: true })
-    const records = database.prepare('SELECT key, data FROM package_index ORDER BY key').all() as {
-      key: string
-      data: Uint8Array
-    }[]
-    database.close()
-    expect(records.map(record => [record.key, Buffer.from(record.data).toString()])).toEqual([
-      ['plugin-only', 'plugin'],
-      ['seed-only', 'seed'],
-      ['shared', 'new'],
-    ])
-    expect(readFileSync(join(destination, 'v11', 'files', 'shared'), 'utf8')).toBe('new')
-    expect(readFileSync(join(destination, 'v11', 'files', 'plugin'), 'utf8')).toBe('plugin')
-  })
-})
-
-describe('desktop seed store archives', () => {
-  it('extracts package bytes and executable modes without retaining loose seed files', () => {
-    const root = temporaryRoot()
-    const seed = join(root, 'seed')
-    const store = join(seed, 'store')
-    const executable = join(store, 'v10', 'files', 'native-addon')
-    mkdirSync(join(store, 'v10', 'files'), { recursive: true })
-    writeFileSync(executable, 'native')
-    chmodSync(executable, 0o755)
-    writeFileSync(join(store, 'v10', 'files', 'package-data'), 'package')
-
-    archivePnpmStore(seed, store)
-    const destination = join(root, 'extracted')
-    extractPnpmStoreArchives(seed, destination)
-
-    expect(existsSync(store)).toBe(false)
-    expect(readFileSync(join(destination, 'v10', 'files', 'package-data'), 'utf8')).toBe('package')
-    if (process.platform !== 'win32') {
-      expect(statSync(join(destination, 'v10', 'files', 'native-addon')).mode & 0o111).toBe(0o111)
-    }
-  })
-
-  it('produces identical shards for identical paths, bytes, and modes', () => {
-    const root = temporaryRoot()
-    const seeds = [join(root, 'first'), join(root, 'second')]
-    for (const [index, seed] of seeds.entries()) {
-      const store = join(seed, 'store')
-      mkdirSync(join(store, 'nested'), { recursive: true })
-      const paths = index === 0 ? ['alpha', 'nested/beta'] : ['nested/beta', 'alpha']
-      for (const path of paths) {
-        const target = join(store, path)
-        writeFileSync(target, path)
-        utimesSync(target, new Date(index * 10_000), new Date(index * 20_000))
-      }
-      archivePnpmStore(seed, store)
-    }
-
-    const first = archiveBytes(seeds[0] as string)
-    const second = archiveBytes(seeds[1] as string)
-    expect(second.map(entry => entry.path)).toEqual(first.map(entry => entry.path))
-    expect(second.map(entry => entry.body)).toEqual(first.map(entry => entry.body))
-  })
-
-  it('rejects an archive whose entry count differs from the manifest', () => {
-    const root = temporaryRoot()
-    const seed = join(root, 'seed')
-    const store = join(seed, 'store')
-    mkdirSync(store, { recursive: true })
-    writeFileSync(join(store, 'package-data'), 'package')
-    archivePnpmStore(seed, store)
-    const manifestPath = join(seed, SEED_STORE_ARCHIVE_MANIFEST)
-    const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as {
-      archives: { entries: number }[]
-    }
-    const archive = manifest.archives[0]
-    if (archive === undefined) throw new Error('test seed has no archive')
-    archive.entries += 1
-    writeFileSync(manifestPath, JSON.stringify(manifest))
-
-    expect(() => { extractPnpmStoreArchives(seed, join(root, 'extracted')) }).toThrow(/unexpected entry count/u)
-  })
-})

+ 2 - 2
docs/architecture.i18n.yaml

@@ -2,5 +2,5 @@
 # side as of the last confirmed-consistent state. Both languages carry equal authority;
 # after editing either side, bring the other along and re-record with:
 #   pnpm run verify-translation-pairing --write docs/architecture.md
-architecture.md: a77dfd06c61cbb12d7008133a7e8d515a3449a02
-architecture.zh.md: 83fa958609500cc85af9c0d1f7e339104f6c18c7
+architecture.md: cdd9686261221ffcba7e4991ec4f93bc4e4559f1
+architecture.zh.md: 2cd1b0781e1a56f05d53ba9035542102b15971a9

+ 2 - 2
docs/architecture.md

@@ -48,9 +48,9 @@ The Python SDK follows the same application architecture. Its runtime wheel pack
 
 ## Desktop application
 
-The [Electron desktop application](../apps/desktop/README.md) owns the reserved `$DSH_HOME/profiles/desktop` npm project. Each signed Electron release binds one exact dsh version and carries a first-party offline seed; startup installs that version into the writable profile with the bundled pnpm, while retaining exact desktop-plugin versions from the previous profile. CLI profiles share supported product data under `$DSH_HOME`, but never executable packages, plugin activation, lockfiles, or `node_modules` with Desktop.
+The [Electron desktop application](../apps/desktop/README.md) carries its exact dsh production runtime in signed application resources. The reserved `$DSH_HOME/profiles/desktop` contains external plugins and links to host-owned packages; compatible upgrades retain plugin files and refresh these links without installing core dependencies. CLI profiles share supported product data under `$DSH_HOME`, while executable packages, plugin activation, lockfiles, and package-manager state remain separate.
 
-Electron starts the private Desktop Host package under its bundled upstream Node.js process; that package loads the installed dsh backend and matching client graph from the reserved profile. Unary RPC, Remote streams, and version-matched client assets cross versioned framed byte pipes with Node IPC reserved for lifecycle control, then reach the renderer through the secure `dsh-app://` protocol; the desktop composition opens no Web server or loopback port. Only shell-owned UI can run plugin transactions through the bundled pnpm and its private `$DSH_HOME/desktop/pnpm/store`.
+Electron starts the private Desktop Host package under its bundled upstream Node.js process; that package loads the bundled dsh backend and matching client graph together with enabled profile plugins. Unary RPC, Remote streams, and version-matched client assets cross versioned framed byte pipes with Node IPC reserved for lifecycle control, then reach the renderer through the secure `dsh-app://` protocol; the desktop composition opens no Web server or loopback port. Only shell-owned UI can run plugin transactions through the bundled pnpm and its private `$DSH_HOME/desktop/pnpm/store`.
 
 ## Core packages
 

+ 2 - 2
docs/architecture.zh.md

@@ -48,9 +48,9 @@ Python SDK 遵循相同的应用架构。其运行时 wheel 把普通 `dsh` CLI
 
 ## 桌面应用
 
-[Electron 桌面应用](../apps/desktop/README.zh.md)持有保留的 `$DSH_HOME/profiles/desktop` npm 项目。每个签名 Electron 发行版绑定一个确切 dsh 版本并携带第一方离线 seed;启动时通过内置 pnpm 把该版本安装进可写 profile,同时保留旧 profile 中桌面插件的确切版本。CLI profile 与 Desktop 共享 `$DSH_HOME` 下受支持的产品数据,但绝不共享可执行包、插件激活、lockfile 或 `node_modules`。
+[Electron 桌面应用](../apps/desktop/README.zh.md)在签名应用资源中携带精确版本的 dsh 生产运行时。保留的 `$DSH_HOME/profiles/desktop` 保存外部插件和指向宿主拥有包的链接;兼容升级保留插件文件并刷新这些链接,无需安装核心依赖。CLI profile 共享 `$DSH_HOME` 下受支持的产品数据,而可执行包、插件激活、锁文件和包管理器状态保持独立。
 
-Electron 通过内置的上游 Node.js 进程启动私有 Desktop Host 包;该包从保留 profile 加载已安装的 dsh 后端与匹配的客户端图。一元 RPC、Remote stream 与版本匹配的客户端资源经带版本的分帧字节管道传输,Node IPC 只保留生命周期控制,再通过安全的 `dsh-app://` 协议到达渲染进程;因此桌面组合不会开放 Web server 或 loopback 端口。只有壳自有 UI 能通过内置 pnpm 及其私有 `$DSH_HOME/desktop/pnpm/store` 执行插件事务。
+Electron 通过内置的上游 Node.js 进程启动私有 Desktop Host 包;该包加载内置 dsh 后端、匹配的客户端图和已启用的 profile 插件。一元 RPC、Remote stream 与版本匹配的客户端资源经带版本的分帧字节管道传输,Node IPC 只保留生命周期控制,再通过安全的 `dsh-app://` 协议到达渲染进程;因此桌面组合不会开放 Web server 或 loopback 端口。只有壳自有 UI 能通过内置 pnpm 及其私有 `$DSH_HOME/desktop/pnpm/store` 执行插件事务。
 
 ## 核心包
 

+ 3 - 86
pnpm-lock.yaml

@@ -525,9 +525,6 @@ importers:
       js-yaml:
         specifier: ^4.2.0
         version: 4.3.1
-      msgpackr:
-        specifier: 2.0.4
-        version: 2.0.4
       pnpm:
         specifier: 11.7.0
         version: 11.7.0
@@ -12688,36 +12685,6 @@ packages:
     resolution: {integrity: sha512-Mmjg4anFBD5OzbPnGJOA0jPPN8645ERhQk38HQLpSenx1ox9bfdPkmAzUnNjeQtqQGFLtKe13J20RtLBmUKMZA==}
     hasBin: true
 
-  '@msgpackr-extract/msgpackr-extract-darwin-arm64@3.0.4':
-    resolution: {integrity: sha512-LCkGo6JDfaBhgST7UpPWgNgLINpcpabaHfyz5OBx75nUYxBsaEPxjnyNjWpeb/xBup/682QnBfRBy2/LvPutZQ==}
-    cpu: [arm64]
-    os: [darwin]
-
-  '@msgpackr-extract/msgpackr-extract-darwin-x64@3.0.4':
-    resolution: {integrity: sha512-zExlW9zUJKZH/tOtVMttwjKa4Xm/3KcNjnE3dPN92uCktwavMxpgCA3MoJK/DOnTWsQgo224OaST27/mPNAf+w==}
-    cpu: [x64]
-    os: [darwin]
-
-  '@msgpackr-extract/msgpackr-extract-linux-arm64@3.0.4':
-    resolution: {integrity: sha512-dgX0P/9wGPJeHFBG+ZmhgE6bmtMt7NP5CRBGyyktpopdk/mW4POnrpQsSLtKI1dwpc+pPLuXHDh6vvskyQE/sw==}
-    cpu: [arm64]
-    os: [linux]
-
-  '@msgpackr-extract/msgpackr-extract-linux-arm@3.0.4':
-    resolution: {integrity: sha512-Tg3yX65f5GbtXLkrYEHE5oibZG9epyYWas7FogTTEJeDEF9JlXJzKgXaNhT3UXlTOeA+AfZpYZYZ0uPj7Cfquw==}
-    cpu: [arm]
-    os: [linux]
-
-  '@msgpackr-extract/msgpackr-extract-linux-x64@3.0.4':
-    resolution: {integrity: sha512-8TNXMEjJc3QEy7R/x1INhgiU+XakDAFUzBhaz7+Rbrs8NH5UQeHQxxmzsSBJGyV6I1jW79undiQm8tOI+D+8FQ==}
-    cpu: [x64]
-    os: [linux]
-
-  '@msgpackr-extract/msgpackr-extract-win32-x64@3.0.4':
-    resolution: {integrity: sha512-CmCXPQrkbwExx3j946/PtHWHbYJiCRBRDl4BlkRQcJB/YOwQxJRTpoo7aTsortjgoJ1x7opzTSxn7C+ASSLVjQ==}
-    cpu: [x64]
-    os: [win32]
-
   '@napi-rs/wasm-runtime@1.1.5':
     resolution: {integrity: sha512-AWPoBRJ9tsnVhor4sjO7rkni+7p+2IAEFj6cx06UgP10jkQHqay/36uRV/bFkgrh18D9vb4cr8Q0Pthskgzy+Q==}
     peerDependencies:
@@ -16331,13 +16298,6 @@ packages:
   ms@2.1.3:
     resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
 
-  msgpackr-extract@3.0.4:
-    resolution: {integrity: sha512-4kmO/MdyUIkLIvTPr8VHLil4AtoKIoniWPIEk5+CDy0xnWC84azhSFmuJ7PxZdsYtiP5kEeQsORAVIeMgxT+Hw==}
-    hasBin: true
-
-  msgpackr@2.0.4:
-    resolution: {integrity: sha512-o1C5KRmuRt+apqMr1HuGSqWStZoRBUpEsCsl15uM9VdAF1qHLtvMOU2En747EnTyEl6c4pzPewRMFF31s1CNbA==}
-
   multistream@4.1.0:
     resolution: {integrity: sha512-J1XDiAmmNpRCBfIWJv+n0ymC4ABcf/Pl+5YvC5B/D2f/2+8PtHvCNxMPKiQcZyi922Hq69J2YOpb1pTywfifyw==}
 
@@ -16438,10 +16398,6 @@ packages:
     resolution: {integrity: sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==}
     engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
 
-  node-gyp-build-optional-packages@5.2.2:
-    resolution: {integrity: sha512-s+w+rBWnpTMwSFbaE0UXsRlg7hU4FjekKU4eyAih5T8nJuNZT1nNsskXpxmeqSK9UzkBl6UgRlnKc8hz8IEqOw==}
-    hasBin: true
-
   node-gyp@12.4.0:
     resolution: {integrity: sha512-OMcPNvqTCFUnNaBlmdgq+lfNqY7gTiSmNRDjY3uAXRyudeKZEZxu3CLtjMQrx4zZxCX2b/mpNqTtwuCJgXhHkw==}
     engines: {node: ^20.17.0 || >=22.9.0}
@@ -17149,13 +17105,13 @@ packages:
   stackback@0.0.2:
     resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==}
 
+  standardwebhooks@1.1.1:
+    resolution: {integrity: sha512-bCbX9ZEyFkWPsRz7Bl3NuQUJohmwGSev/yhr7vhaGPlc4AfIrspIRa6cPTBuI1ItmrTDJ4d/S2hCsfe4+vQGnQ==}
+
   stat-mode@1.0.0:
     resolution: {integrity: sha512-jH9EhtKIjuXZ2cWxmXS8ZP80XyC3iasQxMDV8jzhNJpfDb7VbQLVW4Wvsxz9QZvzV+G4YoSfBUVKDOyxLzi/sg==}
     engines: {node: '>= 6'}
 
-  standardwebhooks@1.1.1:
-    resolution: {integrity: sha512-bCbX9ZEyFkWPsRz7Bl3NuQUJohmwGSev/yhr7vhaGPlc4AfIrspIRa6cPTBuI1ItmrTDJ4d/S2hCsfe4+vQGnQ==}
-
   statuses@2.0.2:
     resolution: {integrity: sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==}
     engines: {node: '>= 0.8'}
@@ -19433,24 +19389,6 @@ snapshots:
       - supports-color
       - zod
 
-  '@msgpackr-extract/msgpackr-extract-darwin-arm64@3.0.4':
-    optional: true
-
-  '@msgpackr-extract/msgpackr-extract-darwin-x64@3.0.4':
-    optional: true
-
-  '@msgpackr-extract/msgpackr-extract-linux-arm64@3.0.4':
-    optional: true
-
-  '@msgpackr-extract/msgpackr-extract-linux-arm@3.0.4':
-    optional: true
-
-  '@msgpackr-extract/msgpackr-extract-linux-x64@3.0.4':
-    optional: true
-
-  '@msgpackr-extract/msgpackr-extract-win32-x64@3.0.4':
-    optional: true
-
   '@napi-rs/wasm-runtime@1.1.5(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0)':
     dependencies:
       '@emnapi/core': 1.10.0
@@ -23321,22 +23259,6 @@ snapshots:
 
   ms@2.1.3: {}
 
-  msgpackr-extract@3.0.4:
-    dependencies:
-      node-gyp-build-optional-packages: 5.2.2
-    optionalDependencies:
-      '@msgpackr-extract/msgpackr-extract-darwin-arm64': 3.0.4
-      '@msgpackr-extract/msgpackr-extract-darwin-x64': 3.0.4
-      '@msgpackr-extract/msgpackr-extract-linux-arm': 3.0.4
-      '@msgpackr-extract/msgpackr-extract-linux-arm64': 3.0.4
-      '@msgpackr-extract/msgpackr-extract-linux-x64': 3.0.4
-      '@msgpackr-extract/msgpackr-extract-win32-x64': 3.0.4
-    optional: true
-
-  msgpackr@2.0.4:
-    optionalDependencies:
-      msgpackr-extract: 3.0.4
-
   multistream@4.1.0:
     dependencies:
       once: 1.4.0
@@ -23425,11 +23347,6 @@ snapshots:
       fetch-blob: 3.2.0
       formdata-polyfill: 4.0.10
 
-  node-gyp-build-optional-packages@5.2.2:
-    dependencies:
-      detect-libc: 2.1.2
-    optional: true
-
   node-gyp@12.4.0:
     dependencies:
       env-paths: 2.2.1

Algúns arquivos non se mostraron porque demasiados arquivos cambiaron neste cambio