Преглед изворни кода

Merge remote-tracking branch 'origin/master' into HEAD

lsdsjy пре 1 недеља
родитељ
комит
40dc25fe1d
100 измењених фајлова са 4649 додато и 2086 уклоњено
  1. 2 2
      .agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.i18n.yaml
  2. 0 0
      .agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md
  3. 0 0
      .agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.zh.md
  4. 2 2
      .agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.i18n.yaml
  5. 12 14
      .agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md
  6. 12 14
      .agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md
  7. 6 0
      .agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.i18n.yaml
  8. 61 0
      .agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.md
  9. 61 0
      .agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md
  10. 6 0
      .agents/notes/implemented/architecture/2026-09-09-desktop-build-release-validation.i18n.yaml
  11. 23 0
      .agents/notes/implemented/architecture/2026-09-09-desktop-build-release-validation.md
  12. 23 0
      .agents/notes/implemented/architecture/2026-09-09-desktop-build-release-validation.zh.md
  13. 6 0
      .agents/notes/implemented/architecture/2026-09-09-desktop-immediate-window-and-direct-start.i18n.yaml
  14. 33 0
      .agents/notes/implemented/architecture/2026-09-09-desktop-immediate-window-and-direct-start.md
  15. 33 0
      .agents/notes/implemented/architecture/2026-09-09-desktop-immediate-window-and-direct-start.zh.md
  16. 6 0
      .agents/notes/implemented/architecture/2026-09-09-desktop-in-place-profile.i18n.yaml
  17. 27 0
      .agents/notes/implemented/architecture/2026-09-09-desktop-in-place-profile.md
  18. 27 0
      .agents/notes/implemented/architecture/2026-09-09-desktop-in-place-profile.zh.md
  19. 6 0
      .agents/notes/implemented/testing/2026-09-06-client-assembly-test-line.i18n.yaml
  20. 90 0
      .agents/notes/implemented/testing/2026-09-06-client-assembly-test-line.md
  21. 90 0
      .agents/notes/implemented/testing/2026-09-06-client-assembly-test-line.zh.md
  22. 2 2
      .agents/notes/implemented/testing/2026-09-06-frontend-performance-budgets.i18n.yaml
  23. 1 1
      .agents/notes/implemented/testing/2026-09-06-frontend-performance-budgets.md
  24. 1 1
      .agents/notes/implemented/testing/2026-09-06-frontend-performance-budgets.zh.md
  25. 6 0
      .agents/notes/proposed/feature/2026-09-08-desktop-uninstall-preserve-dsh-home.i18n.yaml
  26. 95 0
      .agents/notes/proposed/feature/2026-09-08-desktop-uninstall-preserve-dsh-home.md
  27. 95 0
      .agents/notes/proposed/feature/2026-09-08-desktop-uninstall-preserve-dsh-home.zh.md
  28. 1 0
      .agents/skills/dsh-pre-push-checks/SKILL.md
  29. 2 1
      THIRD_PARTY_NOTICES.md
  30. 19 15
      apps/desktop-host/src/index.ts
  31. 2 2
      apps/desktop/README.i18n.yaml
  32. 52 32
      apps/desktop/README.md
  33. 52 32
      apps/desktop/README.zh.md
  34. 7 2
      apps/desktop/electron-builder.config.d.mts
  35. 29 9
      apps/desktop/electron-builder.config.mjs
  36. 3 3
      apps/desktop/package.json
  37. 6 0
      apps/desktop/renderer/plugin-manager.html
  38. 17 2
      apps/desktop/renderer/plugin-manager.js
  39. 16 0
      apps/desktop/renderer/startup.css
  40. 26 0
      apps/desktop/renderer/startup.html
  41. 45 0
      apps/desktop/renderer/startup.js
  42. 2 2
      apps/desktop/scripts/desktop-build-paths.d.mts
  43. 3 3
      apps/desktop/scripts/desktop-build-paths.mjs
  44. 3 4
      apps/desktop/scripts/dev.ts
  45. 17 0
      apps/desktop/scripts/installer.nsh
  46. 43 0
      apps/desktop/scripts/macos-runtime.ts
  47. 0 413
      apps/desktop/scripts/macos-seed-store.ts
  48. 30 6
      apps/desktop/scripts/package-target.ts
  49. 159 0
      apps/desktop/scripts/prepare-dsh.ts
  50. 0 200
      apps/desktop/scripts/prepare-seed.ts
  51. 40 0
      apps/desktop/scripts/runtime-file-policy.ts
  52. 58 0
      apps/desktop/scripts/smoke-runtime.ts
  53. 67 0
      apps/desktop/scripts/smoke-windows.ps1
  54. 6 6
      apps/desktop/scripts/verify-macos-signature.d.mts
  55. 11 11
      apps/desktop/scripts/verify-macos-signature.mjs
  56. 148 0
      apps/desktop/src/backend-controller.ts
  57. 1 1
      apps/desktop/src/core-package-set.ts
  58. 20 6
      apps/desktop/src/host-process.ts
  59. 23 0
      apps/desktop/src/ipc.ts
  60. 30 0
      apps/desktop/src/locale.ts
  61. 217 93
      apps/desktop/src/main.ts
  62. 26 0
      apps/desktop/src/owned-directory.ts
  63. 1 7
      apps/desktop/src/paths.ts
  64. 22 3
      apps/desktop/src/preload-app.ts
  65. 12 0
      apps/desktop/src/preload.ts
  66. 238 0
      apps/desktop/src/profile-packages.ts
  67. 194 308
      apps/desktop/src/project-manager.ts
  68. 2 2
      apps/desktop/src/release.ts
  69. 222 0
      apps/desktop/src/runtime-tree.ts
  70. 0 271
      apps/desktop/src/seed-store.ts
  71. 26 0
      apps/desktop/src/startup-document.ts
  72. 13 0
      apps/desktop/src/startup-error.ts
  73. 1 1
      apps/desktop/src/update-coordinator.ts
  74. 170 0
      apps/desktop/tests/backend-controller.spec.ts
  75. 3 3
      apps/desktop/tests/desktop-build-paths.spec.ts
  76. 8 0
      apps/desktop/tests/expected/startup-en-profile.txt
  77. 5 0
      apps/desktop/tests/expected/startup-en-restart.txt
  78. 8 0
      apps/desktop/tests/expected/startup-zh-CN-profile.txt
  79. 5 0
      apps/desktop/tests/expected/startup-zh-CN-restart.txt
  80. 70 0
      apps/desktop/tests/fixtures/installer-cleanup-smoke.nsi
  81. 55 0
      apps/desktop/tests/fixtures/installer-write-failure-smoke.nsi
  82. 29 0
      apps/desktop/tests/fixtures/owned-directory-smoke.mjs
  83. 138 0
      apps/desktop/tests/fixtures/runtime-payload-smoke.mjs
  84. 53 8
      apps/desktop/tests/host-process.spec.ts
  85. 48 0
      apps/desktop/tests/macos-runtime.spec.ts
  86. 0 245
      apps/desktop/tests/macos-seed-store.spec.ts
  87. 79 8
      apps/desktop/tests/macos-signature.spec.ts
  88. 36 0
      apps/desktop/tests/macos-signing-walk.spec.ts
  89. 368 0
      apps/desktop/tests/main-startup.spec.ts
  90. 53 0
      apps/desktop/tests/owned-directory.spec.ts
  91. 41 1
      apps/desktop/tests/package-target.spec.ts
  92. 33 0
      apps/desktop/tests/plugin-manager.spec.ts
  93. 72 0
      apps/desktop/tests/plugin-pnpm.spec.ts
  94. 39 0
      apps/desktop/tests/preload-app.spec.ts
  95. 78 0
      apps/desktop/tests/profile-packages.spec.ts
  96. 341 350
      apps/desktop/tests/project-manager.spec.ts
  97. 81 0
      apps/desktop/tests/runtime-file-policy.spec.ts
  98. 42 0
      apps/desktop/tests/runtime-fixture.ts
  99. 49 0
      apps/desktop/tests/runtime-tree-read-failure.spec.ts
  100. 107 0
      apps/desktop/tests/runtime-tree.spec.ts

+ 2 - 2
.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.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-07-10-single-file-executable-sdk-runtime-distribution.md
-2026-07-10-single-file-executable-sdk-runtime-distribution.md: 7792e24a5869be6b7bae7787a6a481f3075ba740
-2026-07-10-single-file-executable-sdk-runtime-distribution.zh.md: 857bfaec80da962fac0403f2239e0a5e71954194
+2026-07-10-single-file-executable-sdk-runtime-distribution.md: 8c55c142137f0ab24869bd57ffed3835b7b0516a
+2026-07-10-single-file-executable-sdk-runtime-distribution.zh.md: 52ca2e13901d9469e2f9663936acb766a934e8f7

Разлика између датотеке није приказан због своје велике величине
+ 0 - 0
.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md


Разлика између датотеке није приказан због своје велике величине
+ 0 - 0
.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.zh.md


+ 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: f92f15542b1903cdfe5c7b2794ce872becab3517
+2026-08-25-electron-desktop-packaging-and-updates.zh.md: e67d00417fb4e80cff742862537572653ad8d22c

Разлика између датотеке није приказан због своје велике величине
+ 12 - 14
.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md


Разлика између датотеке није приказан због своје велике величине
+ 12 - 14
.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: 581a4ad31121bfda651cb99e550487a0a712e943
+2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md: fbbb25a4a3446d52ac56dc35bb176c0b706d7cb4

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

@@ -0,0 +1,61 @@
+# Agent Note: Bundle the Desktop runtime and retain external plugins
+
+Status: implemented
+
+English | [中文](2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md)
+
+Profile mutation and recovery follow the [in-place profile decision](2026-09-09-desktop-in-place-profile.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.
+
+The [Desktop file policy](../../../../apps/desktop/scripts/runtime-file-policy.ts) applies after production npm installation and before native signing or descriptor generation. npm publication lists serve library consumers and can include declarations, maps, tests, and native build inputs; they do not identify the files needed by the Desktop process. The Desktop copy omits declarations and recognized source maps because Host execution uses JavaScript and generated Typert artifacts, clears inherited `NODE_OPTIONS`, and does not enable source mapping. Reviewed plugin lifecycle builds cover native dependencies, not arbitrary TypeScript compilation. Published npm packages and external plugin directories retain their own files. Source debugger navigation is a development-package capability.
+
+Package-specific exclusions remove Domino tests, fs-ext compilation outputs, Koffi's Windows import library, and non-target node-pty prebuilds and debug symbols. The policy retains native executable dependencies, node-pty's ConPTY source distribution, licenses, and unrecognized assets; broad `src`, `test`, `.ts`, or `.map` exclusions could remove executable code or runtime data. Copy tests preserve sentinel assets and seal the filtered inventory; the bundled-Node [payload smoke](../../../../apps/desktop/tests/fixtures/runtime-payload-smoke.mjs) verifies PTY output, native file seeking, FFI, image conversion, and HTML parsing. Runtime preparation still verifies every retained byte and boots the complete Host with an external plugin.
+
+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, preserving unrelated files. Compatible release changes or application relocation refresh links and validate enabled peers in place. Node version, platform, or architecture changes reinstall the locked plugin graph and run approved native builds.
+
+Native canonical paths identify shared package directories. Windows launchers can vary path casing without moving the application; string equality would trigger unnecessary profile preparation. Profile cleanup explicitly unlinks every nested directory link before removing real directories. A Windows fixture under Electron 44 reproduces recursive `fs.rmSync` deleting files through a nested junction, while bundled upstream Node 24.17 preserves them. Cleanup qualification therefore includes the real Electron runtime; Node-only tests do not establish target preservation.
+
+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.
+
+Desktop stops the Host before package mutations and waits for pnpm exit before restarting it. The [in-place decision](2026-09-09-desktop-in-place-profile.md) owns partial failures and persistent retry state. Recorded host links identify owned directories independently of package-operation completion.
+
+The [immediate-window decision](2026-09-09-desktop-immediate-window-and-direct-start.md) owns direct Host startup and recovery in the main window. Users can update, remove, disable, or re-enable plugins and retry startup. Incompatible plugins are not silently deleted or automatically downgraded. Each backend launch requires the current runtime identity.
+
+## Alternatives considered
+
+Full runtime verification belongs to packaging. Startup reads the descriptor, checks shared package records and required Host entries, and uses the recorded runtime identity for profile reuse. The [release-validation decision](2026-09-09-desktop-build-release-validation.md) assigns release and target compatibility checks to packaging. It neither enumerates nor hashes installed runtime files, including on first launch or after an upgrade. Reading every file before backend loading adds startup I/O proportional to the distribution size. Installed content changes therefore are not detected by a startup checksum comparison; unusable modules fail when loaded. Build-time verification still rejects changed, missing, extra, or linked files against the recorded inventory.
+
+- **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. Metadata checks and backend loading 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.

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

@@ -0,0 +1,61 @@
+# Agent Note: 内置 Desktop 运行时并保留外部插件
+
+Status: implemented
+
+[English](2026-09-08-desktop-bundled-runtime-and-external-plugins.md) | 中文
+
+profile 修改与恢复遵循[直接修改 profile 决策](2026-09-09-desktop-in-place-profile.zh.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` 的排除,并在任何签名或公证前验证复制后的依赖树。
+
+[桌面文件规则](../../../../apps/desktop/scripts/runtime-file-policy.ts)在生产 npm 依赖安装之后、原生签名或描述文件生成之前执行。npm 发布列表服务于库的使用者,可以包含声明、map、测试和原生构建输入,不能直接表示桌面进程需要哪些文件。桌面副本排除声明和已识别的 source map,因为 Host 执行 JavaScript 和生成的 Typert 产物,清除继承的 `NODE_OPTIONS`,且不开启源码映射。经过审核的插件生命周期构建面向原生依赖,不执行任意 TypeScript 编译。已发布的 npm 包和外部插件目录保留各自的文件。源码调试导航由开发包提供。
+
+包专用排除项包括 Domino 测试、fs-ext 编译产物、Koffi 的 Windows 导入库,以及非目标平台的 node-pty 预构建文件和调试符号。规则保留原生可执行依赖、node-pty 的 ConPTY 源分发内容、许可证和未知资源;宽泛排除 `src`、`test`、`.ts` 或 `.map` 可能移除可执行代码或运行时数据。复制测试保留哨兵资源并封存过滤后的清单;内置 Node 的[产物 smoke](../../../../apps/desktop/tests/fixtures/runtime-payload-smoke.mjs)验证 PTY 输出、原生文件定位、FFI、图像转换和 HTML 解析。运行时准备仍会验证每个保留字节,并携带外部插件启动完整 Host。
+
+dsh 与私有 Host 生产闭包中的每个第一方包都共享。profile 包含指向这些资源包的目录软链接,在 Windows 上使用 junction。正常 Node 解析会把链接解析到实际宿主包目录。因此,宿主与插件对每个已解析导出的导入共享同一模块实例。不同的 ESM 与 CommonJS 条件导出仍是不同入口;链接不能合并包的两套实现。
+
+外部插件把共享宿主包声明为 peer。普通依赖由插件拥有,可以不同于 dsh 使用的版本。验证拒绝已启用插件的不兼容 peer、共享包的嵌套或别名副本、私有包链接,以及通过 CLI 或其他祖先目录解析依赖。如果第三方包需要宿主范围的实例身份,必须明确加入运行时共享清单;版本号相同并不足够。
+
+profile manifest 分别记录精确的已安装插件依赖和已启用 bundle 列表。停用插件会保留其包、锁文件条目和用户配置。共享链接是 Desktop 拥有的派生状态,独立于 pnpm 记录;包管理器操作不携带这些链接,随后 Desktop 重建并验证它们。
+
+## 事务与升级
+
+首次启动创建 profile 元数据和宿主链接,不运行 pnpm,并保留无关文件。兼容的发布变化或应用移动会直接刷新链接并验证已启用的 peer。Node 版本、平台或架构变化时,会重新安装锁定的插件依赖图并运行获准的原生构建。
+
+共享包目录使用原生规范路径识别。Windows 启动器可能改变路径大小写而不移动应用;字符串相等判断会触发不必要的 profile 准备。profile 清理在移除真实目录前,显式解除每一个嵌套目录链接。Windows 夹具在 Electron 44 下复现了递归 `fs.rmSync` 沿嵌套 junction 删除目标文件,而内置上游 Node 24.17 会保留它们。因此清理验收包含真实 Electron 运行时;仅在 Node 下测试不能证明目标文件会保留。
+
+依赖修改先禁用脚本安装,验证插件依赖图和宿主链接,运行经过审查的待执行生命周期构建,再次验证。这允许已批准的原生依赖解析宿主 peer,同时阻止意外的重复宿主包进入启动过程。`allowBuilds` 策略保持明确;不受支持且需要构建的依赖会使事务失败。
+
+Desktop 在包修改前停止 Host,并等待 pnpm 退出后再重启它。[直接修改决策](2026-09-09-desktop-in-place-profile.zh.md)规定部分失败和持久重试状态的处理方式。记录的宿主链接用于识别自有目录,与包操作是否完成相互独立。
+
+[立即显示窗口决策](2026-09-09-desktop-immediate-window-and-direct-start.zh.md)规定实际 Host 启动和主窗口恢复。用户可以更新、删除、禁用或重新启用插件并重试启动。不兼容插件不会被静默删除或自动降级。每次后端启动都要求当前运行时标识。
+
+## 考虑过的替代方案
+
+完整运行时验证属于打包流程。启动读取描述文件,检查共享包记录和必要的 Host 入口,并使用记录的运行时身份复用 profile。[发布验证决策](2026-09-09-desktop-build-release-validation.zh.md)把发布与目标兼容性检查交给打包流程。首次启动和升级后启动都不枚举已安装运行时文件或计算其哈希。在后端加载前读取每个文件,会增加与分发体积成正比的启动 I/O。因此,启动不会通过校验和比较检测已安装内容的变化;不可用模块在加载时失败。构建时验证仍按记录的清单拒绝内容变化、缺失、多余或链接文件。
+
+- **启动时安装内置离线 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/implemented/architecture/2026-09-09-desktop-build-release-validation.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-09-desktop-build-release-validation.md
+2026-09-09-desktop-build-release-validation.md: 23aeeaa98d2647f8b9f54e94ea2aedaa82b19e55
+2026-09-09-desktop-build-release-validation.zh.md: 266bca5bbd593907c9a8fadd43050113ede94100

+ 23 - 0
.agents/notes/implemented/architecture/2026-09-09-desktop-build-release-validation.md

@@ -0,0 +1,23 @@
+# Agent Note: Verify Desktop release compatibility during packaging
+
+Status: implemented
+
+English | [中文](2026-09-09-desktop-build-release-validation.zh.md)
+
+## Problem
+
+The shell and runtime descriptor ship together. Comparing their release facts on every launch repeats packaging checks without proving that installed executable bytes match the descriptor.
+
+## Decision
+
+The packaging verifier owns descriptor schema, shell version, platform, architecture, declared Host protocol version, and Node/pnpm semver validation. Startup reads the fields needed for profile preparation and retains shared-package record and Host-entry checks. The actual Host ready message still validates its protocol version.
+
+This partially supersedes startup release compatibility checks in the [bundled-runtime decision](2026-09-08-desktop-bundled-runtime-and-external-plugins.md). That note retains package ownership and distribution rationale.
+
+## Alternatives considered
+
+Repeating descriptor comparisons can diagnose a mixed installation earlier, but cannot establish executable integrity. Reintroducing them requires a concrete installation failure that packaging validation and actual Host diagnostics cannot adequately explain.
+
+## Consequences
+
+Startup does not reject a descriptor solely because its declared release schema, target, or Host protocol differs, or its Node/pnpm version strings are not semver. Packaging still rejects these cases and shell-version mismatch. Tests distinguish startup reads from packaging verification.

+ 23 - 0
.agents/notes/implemented/architecture/2026-09-09-desktop-build-release-validation.zh.md

@@ -0,0 +1,23 @@
+# Agent Note: 在打包时验证 Desktop 发布兼容性
+
+Status: implemented
+
+[English](2026-09-09-desktop-build-release-validation.md) | 中文
+
+## 问题
+
+壳与运行时描述文件一起发布。每次启动比较其中的发布信息会重复打包检查,却不能证明已安装的可执行文件字节与描述文件一致。
+
+## 决策
+
+打包验证器负责描述文件 schema、shell 版本、平台、架构、声明的 Host 协议版本,以及 Node/pnpm semver 验证。启动读取准备 profile 所需的字段,并保留共享包记录和 Host 入口检查。实际 Host ready 消息仍然验证其协议版本。
+
+本决策部分取代[内置运行时决策](2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md)中的启动发布兼容性检查。该记录继续负责包归属与分发的理由。
+
+## 考虑过的替代方案
+
+重复比较描述文件能更早诊断混装,但不能证明可执行文件完整性。重新引入这些比较需要具体的安装故障,且打包验证和实际 Host 诊断无法充分解释该故障。
+
+## 后果
+
+启动不会仅因描述文件声明的发布 schema、目标或 Host 协议不同,或 Node/pnpm 版本字符串不是 semver 而拒绝运行。打包仍拒绝这些情况和 shell 版本不匹配。测试区分启动读取与打包验证。

+ 6 - 0
.agents/notes/implemented/architecture/2026-09-09-desktop-immediate-window-and-direct-start.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-09-desktop-immediate-window-and-direct-start.md
+2026-09-09-desktop-immediate-window-and-direct-start.md: 1c2209c044495de1fb9d3410e5ac777759e8fa6b
+2026-09-09-desktop-immediate-window-and-direct-start.zh.md: 49b08e4eeea2703c9bcf868d7b290d56eba79542

+ 33 - 0
.agents/notes/implemented/architecture/2026-09-09-desktop-immediate-window-and-direct-start.md

@@ -0,0 +1,33 @@
+# Agent Note: Show the Desktop window before starting the Host
+
+Status: implemented
+
+English | [中文](2026-09-09-desktop-immediate-window-and-direct-start.zh.md)
+
+Profile mutation and recovery follow the [in-place profile decision](2026-09-09-desktop-in-place-profile.md).
+
+## Problem
+
+Waiting for backend readiness leaves users without a window during profile preparation and module loading. A complete staged health-check process repeats backend startup before the application starts its serving process, while plugin startup can still fail in the serving process.
+
+## Decision
+
+Electron creates the main window with a local loading page before profile reconciliation or Host startup. The page depends only on packaged shell assets and receives starting, ready, or error state through the owned preload. Readiness loads the product UI in that window; startup failures display diagnostics and available recovery actions. Closing during loading cancels further startup work and waits for the pending child to exit.
+
+The main window owns recovery because the failed Host cannot supply its own controls. Error pages retain diagnostics, restart, and reinstallation guidance. Disabling plugins and resetting Desktop are available only in a packaged application with loaded runtime metadata and available resources. Reset removes all profile contents except its held lock, without a backup; shared product data and the Harness-home environment file remain intact. The profile directory remains in place so another transaction cannot acquire a replacement lock during cleanup. Self-contained recovery controls use intercepted form navigation when preload is unavailable. A crashed renderer invalidates the navigation cache so the startup page loads again.
+
+Desktop starts the actual Host after preparing the profile in place, without booting a separate health-check backend. Package mutations retain dependency validation, approved lifecycle builds, runtime identity checks, and locking. Failures retain partial changes for explicit repair; there is no automatic profile rollback.
+
+This partially supersedes staged backend probes and waiting to create the main window in the [packaging decision](2026-08-25-electron-desktop-packaging-and-updates.md) and [bundled-runtime decision](2026-09-08-desktop-bundled-runtime-and-external-plugins.md). Those notes retain release, signing, transport, resource ownership, and dependency-transaction rationale. Full runtime file verification remains a packaging operation.
+
+## Alternatives considered
+
+**Keep a complete staged health check.** It can reject some startup failures before activation, but executes plugin initialization twice and cannot guarantee that the serving process will start. The actual Host result provides the diagnostic needed for explicit recovery.
+
+**Keep the main window hidden until readiness.** This avoids presenting a loading page but gives users no visible progress or interaction while the backend loads. A shell-owned page can remain available when Host startup fails.
+
+## Consequences
+
+Users can see startup progress and recover from failures before the product UI is available. A responsive window does not imply that the backend is ready, and startup latency still requires installed-artifact measurement. Profile changes remain in place after activation fails.
+
+Verification covers a delayed Host with a visible loading page, one serving startup for a fresh profile, failure and retry in the same window, plugin management during recovery, and closing while a child is starting. Installed GUI evidence complements lifecycle and transaction tests.

+ 33 - 0
.agents/notes/implemented/architecture/2026-09-09-desktop-immediate-window-and-direct-start.zh.md

@@ -0,0 +1,33 @@
+# Agent Note: Show the Desktop window before starting the Host
+
+Status: implemented
+
+[English](2026-09-09-desktop-immediate-window-and-direct-start.md) | 中文
+
+profile 修改与恢复遵循[直接修改 profile 决策](2026-09-09-desktop-in-place-profile.zh.md)。
+
+## 问题
+
+等待后端就绪会让用户在准备 profile 和加载模块期间看不到窗口。完整的 staging 健康检查进程会在应用启动服务进程前重复启动后端,而插件在实际服务进程中仍然可能启动失败。
+
+## 决策
+
+Electron 在 profile 校准或 Host 启动前创建带本地加载页的主窗口。该页面仅依赖已打包的壳资源,并通过自有 preload 接收 starting、ready 或 error 状态。就绪后在同一窗口加载产品 UI;启动失败时显示诊断和可用恢复操作。加载期间关闭窗口会取消后续启动工作,并等待正在启动的子进程退出。
+
+主窗口提供恢复操作,因为失败的 Host 无法提供自身控件。错误页保留诊断、重启和重装指导。只有已打包应用加载了运行时元数据且资源可用时,才提供禁用插件和重置 Desktop。重置会删除 profile 中除所持锁文件外的所有内容,不保留备份;共享产品数据和 Harness-home 环境文件保持完整。profile 目录保持原位,避免清理期间另一事务获取替代锁。preload 不可用时,独立恢复控件使用被拦截的表单导航。渲染进程崩溃会使导航缓存失效,以重新加载启动页。
+
+Desktop 直接准备 profile 后启动实际 Host,不另行启动健康检查后端。包修改保留依赖验证、获准生命周期构建、运行时标识检查和锁。失败后保留部分修改,供显式修复;不自动回滚 profile。
+
+本决策部分取代[打包决策](2026-08-25-electron-desktop-packaging-and-updates.zh.md)和[内置运行时决策](2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md)中的 staging 后端探针与延迟创建主窗口。这两份记录仍保留发布、签名、传输、资源归属与依赖事务的理由。完整运行时文件验证仍属于打包操作。
+
+## 考虑过的替代方案
+
+**保留完整 staging 健康检查。** 它可以在激活前拒绝部分启动失败,但会执行两次插件初始化,也不能保证服务进程能够启动。实际 Host 结果提供显式恢复所需的诊断。
+
+**在就绪前隐藏主窗口。** 这避免显示加载页,但后端加载期间用户看不到进度,也无法交互。壳拥有的页面可以在 Host 启动失败时继续使用。
+
+## 后果
+
+用户可以在产品 UI 可用前看到启动进度并从失败中恢复。窗口能够响应不代表后端已经就绪,启动延迟仍需通过已安装产物测量。激活失败后,profile 修改保留在原位。
+
+验证覆盖 Host 延迟时可见的加载页、新 profile 只启动一次服务进程、同一窗口中的失败与重试、恢复期间的插件管理,以及子进程正在启动时关闭应用。安装后 GUI 证据补充生命周期与事务测试。

+ 6 - 0
.agents/notes/implemented/architecture/2026-09-09-desktop-in-place-profile.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-09-desktop-in-place-profile.md
+2026-09-09-desktop-in-place-profile.md: 9a221bb334983a18366baeec00a179646dc76385
+2026-09-09-desktop-in-place-profile.zh.md: 53a744ae9ea284c32c3807f67ad365d270217287

+ 27 - 0
.agents/notes/implemented/architecture/2026-09-09-desktop-in-place-profile.md

@@ -0,0 +1,27 @@
+# Agent Note: Modify the Desktop profile in place
+
+Status: implemented
+
+English | [中文](2026-09-09-desktop-in-place-profile.zh.md)
+
+## Problem
+
+Staging preserves an old plugin installation but adds profile copying, directory moves, a recovery journal, and rollback state. Local plugin changes accept explicit repair after failure instead of this complexity.
+
+## Decision
+
+Desktop stops the Host and modifies the current profile directly. Shared host links are detached for package changes and restored when the operation settles. Package locking, dependency validation, and approved native builds remain. Compatible upgrades refresh links without copying plugin files.
+
+Package or Host failures retain partial changes for repair and retry. There is no staging profile, activation journal, directory-swap recovery, or automatic rollback. Existing scratch directories are not interpreted or deleted.
+
+This supersedes staging and rollback in [2026-08-25-electron-desktop-packaging-and-updates](2026-08-25-electron-desktop-packaging-and-updates.md), [2026-09-08-desktop-bundled-runtime-and-external-plugins](2026-09-08-desktop-bundled-runtime-and-external-plugins.md), [2026-09-09-desktop-immediate-window-and-direct-start](2026-09-09-desktop-immediate-window-and-direct-start.md). Other release, module-identity, and window-lifecycle decisions remain active.
+
+A persistent `desktop-packages-pending` marker precedes package writes or native-runtime rebuilding and is removed only after installation, approved builds, and validation succeed. A later launch with that marker reinstalls the locked graph and retries pending builds even when recorded runtime metadata already matches. Ordinary unchanged startups reuse the profile without scanning the plugin dependency graph; package mutations and runtime reconciliation retain validation.
+
+## Alternatives considered
+
+Staging protects the previous installation at the cost of copying and crash recovery. Versioned directories still need preparation, selection, and cleanup. Direct writes give up automatic recovery; reintroduction requires an unattended-recovery product requirement that justifies these costs.
+
+## Consequences
+
+Tests cover offline initialization, in-place upgrades, failure before writes, retained changes after Host failure, partial pnpm failure, restored host links, and exclusive package ownership. Signed application and GUI acceptance remain release-environment checks.

+ 27 - 0
.agents/notes/implemented/architecture/2026-09-09-desktop-in-place-profile.zh.md

@@ -0,0 +1,27 @@
+# Agent Note: 直接修改 Desktop profile
+
+Status: implemented
+
+[English](2026-09-09-desktop-in-place-profile.md) | 中文
+
+## 问题
+
+staging 能保留旧插件安装,但增加 profile 复制、目录移动、恢复日志和回滚状态。本地插件变更接受失败后显式修复,以避免这些复杂度。
+
+## 决策
+
+Desktop 停止 Host 后直接修改当前 profile。修改包前解除宿主共享链接,操作结束后恢复链接。保留包锁、依赖验证和已批准的原生构建。兼容升级只刷新链接,不复制插件文件。
+
+包操作或 Host 失败会保留部分修改,供修复和重试。不使用 staging profile、激活日志、目录切换恢复或自动回滚。已有临时目录不会被解释或删除。
+
+本决策取代以下记录中的 staging 和回滚:[2026-08-25-electron-desktop-packaging-and-updates](2026-08-25-electron-desktop-packaging-and-updates.zh.md), [2026-09-08-desktop-bundled-runtime-and-external-plugins](2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md), [2026-09-09-desktop-immediate-window-and-direct-start](2026-09-09-desktop-immediate-window-and-direct-start.zh.md)。其他发布、模块实例和窗口生命周期决策继续有效。
+
+持久的 `desktop-packages-pending` 标记先于包写入或原生运行时重建,仅在安装、获准构建和验证成功后删除。后续启动发现该标记时,会重新安装锁定的依赖图并重试待执行构建,即使记录的运行时元数据已经匹配。普通未变化的启动复用 profile,不扫描插件依赖图;包修改和运行时校准保留验证。
+
+## 考虑过的替代方案
+
+staging 以复制和崩溃恢复为代价保护旧安装。版本化目录仍需要准备、选择和清理。直接写入放弃自动恢复;只有无人值守恢复的产品要求能证明这些成本合理时,才重新引入。
+
+## 后果
+
+测试覆盖离线初始化、原地升级、写入前失败、Host 失败后保留修改、pnpm 部分失败、宿主链接恢复及独占包操作。签名应用和 GUI 验收仍由发布环境负责。

+ 6 - 0
.agents/notes/implemented/testing/2026-09-06-client-assembly-test-line.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/testing/2026-09-06-client-assembly-test-line.md
+2026-09-06-client-assembly-test-line.md: 0d7ed86e4f0c8898441737c8d6a4c631586268a2
+2026-09-06-client-assembly-test-line.zh.md: 8b4381dbfa24819e1b1f086b7c318d388b681ef5

+ 90 - 0
.agents/notes/implemented/testing/2026-09-06-client-assembly-test-line.md

@@ -0,0 +1,90 @@
+# Agent Note: Whole-client test tier over an endpoint-named Remote mock
+
+Status: implemented
+
+English | [中文](2026-09-06-client-assembly-test-line.zh.md)
+
+## Problem
+
+Browser feature specs each hand-build their bench: a bare Cordis context, stand-ins for `locale`, `connection`, and `remote`, and slot declarations the real declarer would have made. Their assertions therefore describe the bench, not the product: a plugin that adds a settings section, a declarer that reloads through the Loader, or a Connection that reconnects is invisible to them, and every bench repeats the same forty lines with small drift.
+
+API client specs drive their objects through a programmable fake of the Remote surface. The fake re-implements Gateway semantics it should only exercise: follow-stream opening snapshots derived from a history list, page cuts, stream pumps with delivery promises, and an envelope layer. Each of those is a second implementation of a contract the product already owns, and it lets tests describe behavior the generated client cannot produce, such as a unary call that rejects.
+
+No focused source test boots the client the way production does — `bootClient` creating one Loader entry per manifest row, then `mountClient` — so composition faults between plugins are hidden by hand-built benches.
+
+## Decision
+
+A whole-client tier lives in `@deepseek-ai/dsh-client-test-runtime` under the deep import `src/assembly/`, and a new test-support package `@deepseek-ai/dsh-remote-mock` answers Remote traffic by endpoint name. Both are described by their READMEs ([client-runtime](../../../../packages/test-support/client-runtime/README.md), [remote-mock](../../../../packages/test-support/remote-mock/README.md)); this note records the decisions behind them.
+
+**The roster is read from the bundles, never copied.** `bundleRoster(bundles)` parses each bundle's `dsh.bundle.patch` with the include plugin's own YAML dialect (`entryListSchema`, which carries `!!js`) and composes the layers with its `applyEntryPatches`, then keeps every enabled row whose package declares `dsh.client.platform === 'web'`, carrying that declaration's `inject` and `immediately`. `webApp` is the `web` profile's roster (`dsh-base`, then `dsh-web-app`), computed at import. A spec names what it tests and derives the rest: `webApp.closure([row])` keeps a row plus its transitive `inject` cone; `pick` and `without` exist for deliberate cuts. The test runtime stays a Client-face package: it imports no Host module, uses no dynamic import for this, and its client-face `types` adds `node` beside `client-build-environment` so the reader can use `node:fs`. `closure` treats the shell's static platform modules (`PLATFORM_MODULES`) as satisfied without a row.
+
+**The production boot path runs unchanged.** `TestClient.start(plan, mock)` installs the mock as the Connection carrier (`__DSH_TRANSPORT__ = { rpc: mock.rpc }`), loads each roster row's `/client` module, registers its factory through the production module facade's `pendingQueue`, boots through `bootClient`, optionally mounts through `mountClient`, and waits for `connected`. `reload(name)` rebuilds a Loader entry through client-hmr's exported `tearDownEntryFiber`; `unload(name)` removes it; `dispose()` tears down and then fails the test on any endpoint that had no rule. jsdom lacks `EventSource` and `ResizeObserver`; `start` installs inert stand-ins only where the global is absent. Boots and entry rebuilds run one at a time per worker, since the `connection` plugin reads the transport global at apply, and each installs the acting client's transport first; the transport and shims are held by reference count, the first client installing them and the last dispose restoring them, so overlapping clients in one test each connect to their own mock, also after a `reload` of the `connection` row.
+
+**`remote.<ns>` is a contract-free proxy, not the generated client.** The `@deepseek-ai/dsh-api-remotes` row is dropped because its generated clients exist only in built `lib/`. For every `remote.<ns>` a roster row injects, plus every namespace the mock has a rule for, the tier provides one Proxy: `ctx.remote.<ns>.<method>(...args)` calls the endpoint `<ns>/<method>` over the roster's own Connection with the positional args, as a stream when the mock registered a stream script for it and as a unary call otherwise. Cordis resolves `ctx.remote.<ns>` to the service `remote.<ns>`, so the Gateway client itself is untouched. A unary answer returns unchanged; a unary rejection folds the way the generated client folds a carrier throw, through the Gateway client's exported `carrierFailure` and `cancelledFailure`, so product code that fires a Remote call without awaiting sees no rejection. Stream items and failures pass through as the stream yields them.
+
+**Native mocks own response configuration and call assertions.** Tests use `mock.remote.<namespace>.<method>` with `mockResolvedValue`, `mockResolvedValueOnce`, `mockReturnValueOnce`, or `mockImplementation`; the generated API supplies the signatures. Each mock instance owns its native response queue. Reusable tables register only default values or positional handlers, and each endpoint retains only its latest default. Stateful callbacks and deferred promises belong to individual tests. `ok` builds the success envelope. Streams require explicit declarations and can receive scripts over the opening args and a handle (`push`, `end`, `fail`); a declaration without a script produces a stream miss, while undeclared endpoints default to unary calls. Values are not validated. `mock.streams` controls scripted streams and exposes readiness/drain waits; `mock.log` records carrier calls (`pending`, `answered`, `failed`), scripted-stream state, first-argument `requests(endpoint?)`, and unmatched requests. `RemoteMock.create()` answers `$events` with a ready frame so the client can connect.
+
+**Vitest owns each test's mock and client lifetime.** `createClientTest(plan, options)` adds native `mock`, `remote`, and `start` fixtures. The mock is fresh and carries the default responses; `remote` is its namespace proxy, and explicit `start()` leaves startup responses configurable and shares one startup promise within the test. Teardown waits for startup, disposes the successful client even after an assertion failure, checks missing responses, and rejects later starts. Callers await startup failures. Independently owned clients still use `TestClient.start`. Scenario data configures native mocks directly; returning a mutation response and updating subsequent describe responses remain separate actions.
+
+**`remoteDefaultResponses` holds default responses for the boot-time Remote endpoints.** The table lists exactly the endpoints the `web` roster calls while booting and rendering with no sessions, no workspaces, and default settings, each row commented with its caller. A spec layers its own `RemoteTable` on top; a new boot-time call fails the spec at `dispose()`.
+
+`mock.remote` uses native `@vitest/spy.fn` functions shared by direct callers and Connection dispatch. `MockedRemote` applies Vitest's deep mock type transformation to the entire generated namespace map; an empty map weakens only this proxy to `any`. Production `Context` and Remote declarations remain strict, with no namespace-specific type copies or compiler flags. The [proxy typing guidance](../../../../packages/test-support/remote-mock/README.md#remote-proxy) requires build-backed local type checking even when unbuilt tests pass.
+
+## Product exports added for the tier
+
+- `client/connection`: `ClientTransportHooks.rpc?` publishes the already decoded carrier the `?fixture` path used internally; `fetch` becomes optional.
+- `client/hmr`: `tearDownEntryFiber(entry)` is the registry-first fiber teardown `reload` already performed.
+- `client/modules`: `parseDshClient` and `exactPackageSpecifier` are exported from the client face and shared by the Host and roster reader. Test factories use the existing registration queue. The roster-to-boot-graph synthesis has only test consumers and lives in the tier.
+- `client/web`: `bootClient` and `mountClient` are extracted from `AppWebEntry.run()`, which now calls them.
+- `api/gateway`: `carrierFailure` and `cancelledFailure` are exported so a stand-in for the generated client folds identically.
+
+## Alternatives considered
+
+**Running the generated `/remote` clients from built `lib/`.** Rejected: it makes source-plane specs depend on a build artifact, and the proxies need only the unary-or-stream declaration the mock already holds.
+
+**A generated static roster module with a drift gate.** Rejected after review: it is a copy of bundle data inside the test package, and every subset written against it is a hand-list that misses rows. Reading the bundles at import through the include plugin's own schema and patch application removes the copy, the generator, and the gate.
+
+**A Host compile face for the test runtime, a dynamic import of a Host module, or a vitest `globalSetup` handing rosters through `provide`/`inject`.** Rejected: a Client test runtime must not import Host code, dynamic imports hide the dependency, and a config-level channel hides the roster's source. The composition functions the launcher uses are face-neutral, so none of these is needed.
+
+**A hand-written test-side YAML and patch parser.** Rejected: `entryListSchema` and `applyEntryPatches` are the launcher's own and carry no Host Context merge; the tier writes only file reading, package.json location, and the web-row filter.
+
+**A mock module standing in for the Gateway client.** Rejected: the mock must not interfere with Gateway internals; installing it on the Connection carrier keeps retry, folding, and stream semantics real.
+
+**A second typed Gateway implementation with an `Api` generic, envelope and error classes, and a fixtures directory.** Rejected: it duplicates Gateway declarations and encoding. The mock derives method types from the generated namespace map and declares only unary or stream behavior at runtime.
+
+**Proxies passing unary rejections through unchanged.** Rejected: product code never awaits a Remote rejection because the generated client folds carrier throws, so an unmatched endpoint produced unhandled rejections; folding through the exported helpers restores the client's face.
+
+**Keeping CallContext and wrapping native spies in an adapter.** Rejected: it makes each test unwrap a synthetic call and retains counter/state machinery with no business-spec consumer. Positional handlers use the existing test ecosystem directly.
+
+**A separate `once` / `sequence` DSL and fallback rule stack.** Rejected: native per-instance queues already express the deferred responses and temporary failures used by consumers. Immutable table declarations with a cursor per registration would allow shared one-shot tables, but no current shared table requires them. The tier gives up newest-registration-first fallback and table-level repeat-last declarations; tests use native queue order and a persistent default instead. Response values and stateful handlers remain borrowed, not cloned.
+
+**A separate pre-materialized-module option or `staticModules`.** Rejected: the existing pending registration queue accepts the same factories before Loader startup. `staticModules` bypasses factory materialization and does not share graph prefetch/invalidation behavior; the queue removes the extra option without losing that behavior. Assembly-only helpers remain in their leaf modules rather than the recommended entry's exports.
+
+**A compiler-wide fallback flag or private augmentation package.** Rejected: declaration merging affects every file in a TypeScript Program that reaches the import; `private: true` only prevents publication. Separate test compiler graphs and additional policy checks add configuration maintenance without narrowing the fallback to its actual helper consumers. A local conditional type limits weakened inference to those consumers.
+
+**Per-namespace helpers with selected method lists and separate spy aliases.** Rejected: they repeat operation names and controls already supplied by native mocks. The generic proxy derives every method from the production namespace map, while fixtures own the returned data rather than a second implementation of domain writes or publication.
+
+## Consequences
+
+Specs boot real plugins: the whole `web` roster costs about five seconds cold and well under a second warm, and a three-row cone about twenty milliseconds per test. Assertions read product facts — the real section list, the real declarer, a Loader rebuild, a second `$events` generation on reconnect — and change when the product changes.
+
+The proxies skip the generated client's zod validation, wire-name mapping, and scoped-identity injection; mock rules read positional `args`, and the generated clients stay covered by the built-artifact e2e lanes. `remoteDefaultResponses` must gain a row when a plugin adds a boot-time call, and fails loud until it does. The two bundle names of the `web` profile are repeated once in `WEB_PROFILE_BUNDLES`, mirroring the launcher's `PROFILE_TEMPLATES.web`, and no check links the two: the client test program cannot import `@deepseek-ai/dsh-app-boot`, whose Host `Context` merges collide with the Client ones, and the test runtime takes no Host dependency even for tests. A template change therefore has to be carried to that constant by hand.
+
+The shared functions keep production and test callers on one implementation. `AppWebEntry.run()` mounts the Loader after the immediate-tier prefetch settles; application entry creation remains after prefetch, so serializing Loader setup with prefetch does not advance application activation.
+
+Native stream overrides may return their own iterable. The caller then owns consumption and cancellation; these iterables bypass scripted-stream logs and controls. Registered scripts retain managed queues and cancellation. This distinction preserves native mock behavior without adding another iterator wrapper or changing pull timing.
+
+## Deferred
+
+Product facts the tier surfaced and leaves as they are:
+
+- No `declare module` augmentation declares `Context.connection`; consumers read `ctx.get('connection') as ConnectionHandle`, and `TestClient.connection` is the typed entry the tier offers.
+- `TestClient.start` has no page-URL option, so a spec that needs the `connection` plugin to classify the page as off-loopback reconfigures the jsdom instance vitest exposes on `globalThis.jsdom`, a private detail of the jsdom environment provider.
+- `ISessions` exposes no queue observation point, so queue frames reach a `Session` through `handleControlFrame` directly rather than over the `session/control` stream.
+- A durable event pushed twice with the same seq is dropped at the tail of `RemoteJournalStream` as a replay and never reaches `SessionQueueMirror.acceptDurable`.
+- The vendored Loader rejects `create()` when a module import fails, so the import-failed branch of `assertEntriesActive` is unreachable through `create()`.
+- The session-controller client casts `ctx.remote as unknown as SessionRemotes`; in the client test program the cast is redundant, since the generated `/remote` merges are visible there.
+
+## Testing
+
+`packages/test-support/remote-mock/tests/` covers rules, streams, the log, and the carrier face; the `assembly-` specs under `packages/test-support/client-runtime/tests/` cover the roster reader on the real bundles and on a scratch installation, module loading, the proxies including their fold, and `TestClient` under jsdom and plain Node. Seven converted specs use the tier. In `packages/client/ui-settings-general/tests/`, the shell and apply specs boot the whole `web` roster; the apply spec reads its Chinese copy from the Host settings document the mock answers and reconfigures the jsdom page URL for the off-loopback branch. In `packages/api/session-controller/tests/`, the Session, queue-store, and pending-submission specs drive their objects over the roster's real Connection through the `remote.<ns>` proxies, with the Gateway client's own `$stream` retry loop, over the gateway's dependency cone, and the client-apply spec boots the plugin's dependency cone, delivering Remote events as emit frames on `$events`. In `packages/api/workspace-controller/tests/`, the transport spec boots the plugin's cone for apply cases and the gateway cone for hand-built stream and controller cases, since a rostered plugin would share the follow endpoint. Each package keeps a `tests/remote/` module with its default responses and frame builders. The fixture tests include an expected assertion failure and independently observe completed client cleanup; settings reload tests observe replaced registration identities, and write tests assert every mutation argument. Teardown-failure tests execute the real tree disposer before reporting the injected failure and observe the `$events` stream's cancelled state.

+ 90 - 0
.agents/notes/implemented/testing/2026-09-06-client-assembly-test-line.zh.md

@@ -0,0 +1,90 @@
+# Agent Note: 基于端点具名 Remote mock 的整机客户端测试档
+
+Status: implemented
+
+[English](2026-09-06-client-assembly-test-line.md) | 中文
+
+## 问题
+
+浏览器功能 spec 各自手拼测试台:一个裸 Cordis context、`locale`、`connection`、`remote` 的替身,以及本该由真声明者做出的 slot 声明。它们的断言因此描述的是测试台而不是产品:一个插件新增了设置 section、一个声明者经 Loader 重载、一个 Connection 重连,对它们都不可见,而每个测试台都重复着同样的四十行并各有细小漂移。
+
+API 客户端 spec 用一个可编程的 Remote 面假件驱动对象。这个假件重新实现了它本该只是调用的 Gateway 语义:从历史列表推导 follow 流的开场快照、切页、带投递 promise 的流泵,以及一层信封。每一样都是产品已有契约的第二份实现,它还让测试描述出生成客户端做不出来的行为,比如一次会 reject 的一元调用。
+
+没有聚焦源码测试按生产方式起客户端——`bootClient` 按 manifest 每行建一个 Loader entry,再 `mountClient`——插件之间的组合故障会被手工测试台遮住。
+
+## 决定
+
+整机档放在 `@deepseek-ai/dsh-client-test-runtime` 的深 import `src/assembly/` 下,新的 test-support 包 `@deepseek-ai/dsh-remote-mock` 按端点名应答 Remote 流量。两者的用法由各自 README 描述([client-runtime](../../../../packages/test-support/client-runtime/README.zh.md)、[remote-mock](../../../../packages/test-support/remote-mock/README.zh.md));本文记录它们背后的决定。
+
+**roster 从 bundle 现读,绝不拷贝。** `bundleRoster(bundles)` 用 include 插件自己的 YAML 方言(带 `!!js` 的 `entryListSchema`)解析每个 bundle 的 `dsh.bundle.patch`,用它的 `applyEntryPatches` 合成各层,再保留每个未禁用且其包声明 `dsh.client.platform === 'web'` 的行,带上该声明的 `inject` 与 `immediately`。`webApp` 是 `web` profile 的 roster(先 `dsh-base`、再 `dsh-web-app`),import 时算出。spec 点名它要测的东西,其余推导:`webApp.closure([row])` 保留一行及其传递 `inject` 锥;`pick` 与 `without` 留给刻意裁剪。测试运行时仍是 Client 面的包:它不 import 任何 Host 模块,此处不用动态 import,其 client 面的 `types` 在 `client-build-environment` 之外加了 `node`,好让读取器使用 `node:fs`。`closure` 把 shell 静态种入的平台模块(`PLATFORM_MODULES`)视为无需行即已满足。
+
+**生产启动路径原样运行。** `TestClient.start(plan, mock)` 把 mock 装成 Connection 载体(`__DSH_TRANSPORT__ = { rpc: mock.rpc }`),加载每个 roster 行的 `/client` 模块,经生产模块 facade 的 `pendingQueue` 登记其工厂,经 `bootClient` 启动,可选经 `mountClient` 挂载,然后等 `connected`。`reload(name)` 经 client-hmr 导出的 `tearDownEntryFiber` 重建一个 Loader entry;`unload(name)` 移除它;`dispose()` 拆掉一切,然后对任何没有规则的端点让测试失败。jsdom 没有 `EventSource` 与 `ResizeObserver`;`start` 只在全局缺失处装惰性替身。每个 worker 内启动与 entry 重建逐个进行,因为 `connection` 插件在 apply 时读传输全局,每次都先装上当事客户端的传输;传输与替身按引用计数持有,第一个客户端安装、最后一次 dispose 恢复,因此同一测试里重叠的客户端各连各的 mock,`reload` 了 `connection` 行之后也是。
+
+**`remote.<ns>` 是无契约代理,不是生成客户端。** `@deepseek-ai/dsh-api-remotes` 行被去掉,因为它生成的客户端只存在于构建后的 `lib/`。对 roster 行注入的每个 `remote.<ns>`,加上 mock 有规则的每个命名空间,本档各提供一个 Proxy:`ctx.remote.<ns>.<method>(...args)` 经 roster 自己的 Connection 用位置参数调用端点 `<ns>/<method>`,mock 为它登记了流脚本就走流、否则走一元。Cordis 把 `ctx.remote.<ns>` 解析到服务 `remote.<ns>`,所以 Gateway 客户端本身不动。一元应答原样返回;一元拒绝按生成客户端折叠载体抛错的方式折叠,经 Gateway 客户端导出的 `carrierFailure` 与 `cancelledFailure`,因此不等待就发出 Remote 调用的产品代码看不到任何 reject。流的项与失败按流吐出的样子直传。
+
+**原生 mock 负责响应配置和调用断言。** 测试通过 `mock.remote.<namespace>.<method>` 使用 `mockResolvedValue`、`mockResolvedValueOnce`、`mockReturnValueOnce` 或 `mockImplementation`,签名由生成的 API 提供。每个 mock 实例独立持有原生响应队列。可复用的表只登记默认值或位置参数 handler,每个端点仅保留最新默认响应。有状态回调和 deferred promise 归各测试所有。`ok` 构造成功信封。流需要显式声明,可提供接收打开参数与句柄(`push`、`end`、`fail`)的脚本;无脚本的声明产生流漏配,未声明端点默认走一元。值不校验。`mock.streams` 控制脚本流并提供打开/排空等待;`mock.log` 记录载体调用(`pending`、`answered`、`failed`)、脚本流状态、首参数 `requests(endpoint?)` 和未匹配请求。`RemoteMock.create()` 为 `$events` 应答 ready 帧,让客户端可以连接。
+
+**Vitest 拥有每条测试的 mock 和客户端生命周期。** `createClientTest(plan, options)` 增加原生 `mock`、`remote` 与 `start` fixture。mock 每次新建并携带默认响应;`remote` 是它的命名空间 Proxy,显式 `start()` 留出配置启动期应答的时机,同一测试共用一个启动 Promise。收尾等待启动,即使断言失败也销毁成功创建的客户端、检查漏配,并拒绝后续启动。启动错误由调用方 await 观察。分别拥有多个客户端时仍用 `TestClient.start`。场景数据直接配置原生 mock;返回 mutation 应答与更新后续 describe 应答仍是两个独立操作。
+
+**`remoteDefaultResponses` 是启动期 Remote 端点的默认响应。** 这张表恰好列出 `web` roster 在没有 session、没有 workspace、默认设置下启动并渲染时会打的端点,每行注明调用方。spec 在其上叠加自己的 `RemoteTable`;新的启动期调用会在 `dispose()` 时让 spec 失败。
+
+`mock.remote` 使用直接调用方与 Connection 分发共用的原生 `@vitest/spy.fn` 函数。`MockedRemote` 对完整生成的命名空间映射应用 Vitest 深层 mock 类型转换;映射为空时仅这个 Proxy 弱化为 `any`。生产 `Context` 与 Remote 声明保持严格,不需要命名空间专属类型副本或编译器 Flag。[Proxy 类型指引](../../../../packages/test-support/remote-mock/README.zh.md#remote-proxy)要求即使无构建测试通过,本地也必须执行构建后的类型检查。
+
+## 为本档新增的产品导出
+
+- `client/connection`:`ClientTransportHooks.rpc?` 公开 `?fixture` 路径内部已在用的已解码载体;`fetch` 变为可选。
+- `client/hmr`:`tearDownEntryFiber(entry)` 就是 `reload` 本来执行的 registry 先行的 fiber 拆除。
+- `client/modules`:`parseDshClient` 与 `exactPackageSpecifier` 从 client 面导出,由 Host 和 roster 读取器共用。测试工厂使用已有注册队列。roster 行到 boot graph 的合成只有测试消费者,放在本档里。
+- `client/web`:`bootClient` 与 `mountClient` 从 `AppWebEntry.run()` 抽出,后者现在调用它们。
+- `api/gateway`:导出 `carrierFailure` 与 `cancelledFailure`,让生成客户端的替身折叠得一模一样。
+
+## 考虑过的替代方案
+
+**从构建后的 `lib/` 运行生成的 `/remote` 客户端。** 否决:它让源码面的 spec 依赖构建产物,而代理只需要 mock 已持有的一元或流声明。
+
+**带漂移门禁的生成静态 roster 模块。** 评审后否决:它是测试包内的一份 bundle 数据拷贝,基于它写的每个子集都是会漏行的手列清单。用 include 插件自己的 schema 与补丁应用在 import 时读 bundle,把拷贝、生成器和门禁一起去掉。
+
+**给测试运行时加 Host 编译面、动态 import 一个 Host 模块,或用 vitest `globalSetup` 经 `provide`/`inject` 传 roster。** 否决:Client 测试运行时不得 import Host 代码,动态 import 藏起依赖,配置层通道藏起 roster 的来源。启动器用的合成函数本就面中立,这些都不需要。
+
+**自写一套测试侧的 YAML 与补丁解析器。** 否决:`entryListSchema` 与 `applyEntryPatches` 就是启动器自己的,不带 Host Context 合并;本档只写读文件、定位 package.json 和 web 行过滤。
+
+**用一个 mock 模块替代 Gateway 客户端。** 否决:mock 不得干涉 Gateway 内部;装在 Connection 载体上让重试、折叠与流语义都保持真实。
+
+**第二套带类型的 Gateway 实现,包含 `Api` 泛型、信封与错误类以及 fixtures 目录。** 否决:它重复 Gateway 声明与编解码。mock 从生成的命名空间映射派生方法类型,运行时只声明一元或流行为。
+
+**代理把一元拒绝原样直传。** 否决:产品代码从不等待 Remote 的 reject,因为生成客户端会折叠载体抛错,于是没匹配的端点造成未处理的拒绝;经导出的辅助函数折叠恢复了客户端的面。
+
+**保留 CallContext,再用适配器包装原生 spy。** 否决:每个测试都要解开合成调用对象,还保留没有业务 spec 消费者的计数/状态机制。位置参数 handler 直接使用现有测试生态。
+
+**独立的 `once` / `sequence` DSL 与回退规则栈。** 否决:按实例持有的原生队列已经能表达消费方使用的延迟响应和临时失败。不可变表声明配合每次登记的游标虽能共享一次性响应表,但当前没有共享表需要它。本档放弃最新登记优先的回退和表级末项重复声明,测试改用原生队列顺序与持续默认响应。响应值和有状态 handler 仍按引用借用,不做克隆。
+
+**独立的预加载模块选项或 `staticModules`。** 否决:现有待注册队列能在 Loader 启动前接收同样的工厂。`staticModules` 绕过工厂物化,也不共享图的预取/失效行为;队列在保留这些行为的同时省掉额外选项。仅装配内部使用的 helper 保留在叶模块,不从推荐入口再导出。
+
+**编译器级全局降级 Flag 或私有类型增补包。** 否决:声明合并会影响同一 TypeScript Program 中能够到达该导入的所有文件;`private: true` 只阻止发布。拆分测试编译图或增加策略检查会增加配置维护成本,却不能把降级限制在真正使用它的 Helper 中。局部条件类型只弱化这些消费方的类型推断。
+
+**为每个命名空间编写方法清单和独立 spy 别名的 Helper。** 否决:它们重复操作名称和原生 mock 已经提供的控制功能。通用 Proxy 从生产命名空间映射派生每个方法,fixture 拥有返回数据,而不再实现另一份领域写入或发布机制。
+
+## 后果
+
+spec 起的是真插件:整个 `web` roster 冷启动约五秒、热启动远低于一秒,三行的锥每例约二十毫秒。断言读的是产品事实——真实的 section 清单、真实的声明者、一次 Loader 重建、重连时的第二代 `$events`——并随产品变化而变化。
+
+代理跳过了生成客户端的 zod 校验、wire 字段名映射与 scoped 身份注入;mock 规则读位置 `args`,生成客户端仍由构建产物 e2e 车道覆盖。插件新增启动期调用时 `remoteDefaultResponses` 必须加一行,加之前会响亮失败。`web` profile 的两个 bundle 名在 `WEB_PROFILE_BUNDLES` 里重复了一次,对应启动器的 `PROFILE_TEMPLATES.web`,且两者之间没有机检联系:客户端测试程序不能 import `@deepseek-ai/dsh-app-boot`(其 Host `Context` 合并与 Client 的冲突),而测试运行时连测试也不引入 Host 依赖。模板变更因此要靠人工带到这个常量。
+
+共享函数让生产和测试调用方使用同一份实现。`AppWebEntry.run()` 在立即层预取落定后挂载 Loader;应用 entry 仍在预取之后创建,因此让 Loader 安装与预取串行不会提前应用激活。
+
+原生流覆盖可以返回自有 iterable,此时调用方负责消费与取消,这些 iterable 不参与脚本流日志或控制。已登记的脚本仍使用受控队列与取消机制。这一区分保留原生 mock 行为,无需再添加 iterator 包装器或改变拉取时机。
+
+## 遗留事项
+
+本档暴露出来、原样保留的产品事实:
+
+- 没有任何 `declare module` 增强声明 `Context.connection`;消费方一律 `ctx.get('connection') as ConnectionHandle`,`TestClient.connection` 是本档提供的带类型入口。
+- `TestClient.start` 没有页面 URL 选项,需要 `connection` 插件把页面判为 off-loopback 的 spec 只能重配 vitest 挂在 `globalThis.jsdom` 上的 jsdom 实例,这是 jsdom 环境提供者的私有细节。
+- `ISessions` 没有 queue 观察点,queue 帧只能直接经 `handleControlFrame` 到达 `Session`,而不是走 `session/control` 流。
+- 同 seq 的 durable 事件二次推送在 `RemoteJournalStream` 尾部被当作重放丢弃,到不了 `SessionQueueMirror.acceptDurable`。
+- vendored Loader 在模块 import 失败时让 `create()` reject,因此 `assertEntriesActive` 的 import 失败分支经 `create()` 不可达。
+- session-controller 客户端把 `ctx.remote` cast 成 `SessionRemotes`;在客户端测试程序里这个 cast 是多余的,因为生成的 `/remote` 合并在那里可见。
+
+## 测试
+
+`packages/test-support/remote-mock/tests/` 覆盖规则、流、日志与载体面;`packages/test-support/client-runtime/tests/` 下的 `assembly-` 系列 spec 覆盖在真 bundle 与临时安装上的 roster 读取器、模块加载、含折叠的代理,以及 jsdom 与纯 Node 下的 `TestClient`。七条改造后的 spec 使用本档。`packages/client/ui-settings-general/tests/` 下,shell 与 apply 两条起整个 `web` roster;apply 从 mock 应答的 Host settings 文档读它的中文文案,并为 off-loopback 分支重配 jsdom 页面 URL。`packages/api/session-controller/tests/` 下,Session、queue-store、pending-submission 三条在 gateway 依赖锥上经 `remote.<ns>` 代理走 roster 的真 Connection 驱动对象(`$stream` 的重试循环仍是 Gateway 客户端自己的),client-apply 起插件的依赖锥,把 Remote 事件作为 `$events` 上的 emit 帧投递。`packages/api/workspace-controller/tests/` 下,transport 的 apply 用例起插件锥、手工构造流与 controller 的用例起 gateway 锥,因为进了 roster 的插件会共用 follow 端点。每个包在 `tests/remote/` 保有自己的默认响应与帧构造。fixture 测试包含预期的断言失败,并独立观察客户端清理完成;settings 重载测试观察注册身份被替换,写入测试断言全部 mutation 参数。teardown 失败测试先执行真实树清理,再报告注入的失败,并观察 `$events` 流的取消状态。

+ 2 - 2
.agents/notes/implemented/testing/2026-09-06-frontend-performance-budgets.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/testing/2026-09-06-frontend-performance-budgets.md
-2026-09-06-frontend-performance-budgets.md: 4c1a99e10c9b2d7ba7ecbd38f2249ac84e9d330b
-2026-09-06-frontend-performance-budgets.zh.md: f563c55e6440de85d71110cbfb2533c7f99218ce
+2026-09-06-frontend-performance-budgets.md: 4d69dda8a04d4e9807c18c8f1b978ca7fc87a883
+2026-09-06-frontend-performance-budgets.zh.md: c9a174df55a2c175232eb2f4d8468b054e532b9c

+ 1 - 1
.agents/notes/implemented/testing/2026-09-06-frontend-performance-budgets.md

@@ -16,7 +16,7 @@ The existing serial benchmark inventory includes two frontend owners: [active re
 
 The browser input contains 240 closed turns, 40 tool results, and 20 code fences, plus mixed-language prose and reasoning. Historical Assistant records carry matching compact streams built through the production accumulator with 12-character reasoning/text deltas and 8-character tool-argument deltas; empty streams would omit stored and transferred payload costs. Nine older-page actions exhaust this input from its observed 25-turn initial window; the readiness probe follows mounted turn growth rather than duplicating the pagination algorithm. Each sample uses a fresh scaffold and browser. Setup, seeding, browser launch, initial shell load, and sidebar expansion are excluded from open timing. Open ends at transcript availability and an editable composer; page and navigation timings end at their target DOM state. Two animation frames include a rendering opportunity, not hardware presentation or a guarantee that every offscreen node painted.
 
-The continuation sends 120 text deltas at 16 ms replay pacing. The input witness is installed before Enter submission from the focused composer; typing retains focus without a mouse-refocus action or a separate pre-input animation-frame wait. First/final marker lookups stay inside the latest Assistant step and retain visible-state waits. Diagnostics capture reply markers and focus immediately after the first-visible wait, plus browser-clock timestamps and focus at the first actual input event. Replay never waits for input; starvation can still fail overlap. The synchronous input witness reads that same bounded reply. Whole-history text and accessibility queries add observer CPU and garbage collection to the measured interval, so reducing that observer work is benchmark repair, not product optimization. It records Enter-to-first-visible-reply, trusted draft typing whose first actual input event observes the first reply but no completion marker, complete reply wall time through settled persistence and the new rendered turn-tail, and Chromium main-thread task duration. The complete wall budget adds the fixed 1984 ms scripted pacing to a scaled overhead allowance; input and completion have their own enforced budgets. Post-GC browser heap and DOM counts remain diagnostics because one endpoint does not prove a leak.
+The continuation sends 120 text deltas at 16 ms replay pacing. The input witness is installed before Enter submission from the focused composer; typing retains focus without a mouse-refocus action or a separate pre-input animation-frame wait. First/final marker lookups sample visible text inside the latest Assistant step on animation frames, avoiding selector retry backoff. Hidden text and markers in older steps cannot satisfy the observer. The first observation captures reply markers and focus in the browser; diagnostics are retrieved after typing to avoid an additional pre-input round trip. Diagnostics also capture browser-clock timestamps and focus at the first actual input event. Replay never waits for input; starvation can still fail overlap. The synchronous input witness reads that same bounded reply. Whole-history text and accessibility queries add observer CPU and garbage collection to the measured interval, so reducing that observer work is benchmark repair, not product optimization. It records Enter-to-first-visible-reply, trusted draft typing whose first actual input event observes the first reply but no completion marker, complete reply wall time through settled persistence and the new rendered turn-tail, and Chromium main-thread task duration. The complete wall budget adds the fixed 1984 ms scripted pacing to a scaled overhead allowance; input and completion have their own enforced budgets. Post-GC browser heap and DOM counts remain diagnostics because one endpoint does not prove a leak.
 
 Reconnect uses three fresh compiled plain-Node children. Each creates a 100,000-delta reasoning prefix with distinct timestamps and two compact records before timing `ClientAssistantStream.replace()`. GC precedes the baseline and follows replacement while the result remains reachable; replacement time excludes both collections. The report consumes the result after collection and checks that the next dense live frame remains accepted. This measures reconstruction, not transport, rendering, or an entire reconnect workflow.
 

+ 1 - 1
.agents/notes/implemented/testing/2026-09-06-frontend-performance-budgets.zh.md

@@ -16,7 +16,7 @@ Node 对话折叠很快,并不能证明浏览器能绘制长对话或在流式
 
 浏览器输入包含 240 个已关闭轮次、40 个工具结果和 20 个代码块,以及混合语言正文和推理。历史 Assistant 记录携带匹配的紧凑 stream,通过生产 accumulator 按 12 字符推理/文本 delta 和 8 字符工具参数 delta 构建;空 stream 会遗漏存储与传输负载成本。从观察到的初始 25 轮窗口开始,九次更早分页操作读完该输入;就绪探针跟踪已挂载轮次增长,不复制分页算法。每个样本使用全新 scaffold 和浏览器。环境准备、数据播种、浏览器启动、初始 shell 加载及侧栏展开不计入打开时间。打开测量在对话可用且输入框可编辑时结束;分页与导航测量在目标 DOM 状态出现时结束。两次动画帧包含一次渲染机会,不代表硬件显示或保证每个屏幕外节点都已绘制。
 
-续接以 16 ms 重放间隔发送 120 个文本 delta。输入观察器在从已聚焦输入框按 Enter 提交前安装;键入保留焦点,不执行鼠标重新聚焦,也不单独等待输入前动画帧。首段/最终标记查找限制在最新 Assistant step,并保留可见状态等待。诊断在首段可见等待后立即记录回复标记和焦点,并记录首个实际输入事件的浏览器时钟时间戳与焦点。重放从不等待输入;响应阻塞仍可能导致重叠失败。同步输入证据读取同一个受限回复。全历史文本与无障碍查询会向测量区间加入观察器 CPU 和垃圾回收成本,因此减少此类观察工作属于基准修正,而非产品优化。它记录 Enter 提交到首段可见回复的时间、首个实际输入事件观察到首段回复且完成标记尚未出现时的真实草稿键入、直到持久化结算并渲染新 turn-tail 的完整回复壁钟时间,以及 Chromium 主线程任务时间。完整壁钟预算在缩放后的额外开销额度上加固定的 1984 ms 脚本节奏;输入和完成均有独立执行的预算。强制 GC 后的浏览器 heap 和 DOM 数量仍仅供诊断,因为单个终点不能证明泄漏。
+续接以 16 ms 重放间隔发送 120 个文本 delta。输入观察器在从已聚焦输入框按 Enter 提交前安装;键入保留焦点,不执行鼠标重新聚焦,也不单独等待输入前动画帧。首段/最终标记查找在动画帧上采样最新 Assistant step 内的可见文本,避免选择器重试退避。隐藏文本和较早步骤中的标记均不能满足观察条件。首次观察在浏览器内记录回复标记与焦点;诊断在键入后取回,避免增加输入前的通信往返。诊断还记录首个实际输入事件的浏览器时钟时间戳与焦点。重放从不等待输入;响应阻塞仍可能导致重叠失败。同步输入证据读取同一个受限回复。全历史文本与无障碍查询会向测量区间加入观察器 CPU 和垃圾回收成本,因此减少此类观察工作属于基准修正,而非产品优化。它记录 Enter 提交到首段可见回复的时间、首个实际输入事件观察到首段回复且完成标记尚未出现时的真实草稿键入、直到持久化结算并渲染新 turn-tail 的完整回复壁钟时间,以及 Chromium 主线程任务时间。完整壁钟预算在缩放后的额外开销额度上加固定的 1984 ms 脚本节奏;输入和完成均有独立执行的预算。强制 GC 后的浏览器 heap 和 DOM 数量仍仅供诊断,因为单个终点不能证明泄漏。
 
 重连使用三个全新编译后的纯 Node 子进程。各进程在计时 `ClientAssistantStream.replace()` 前创建包含不同时间戳、两条紧凑记录和 100,000 个 delta 的推理前缀。在基线前执行 GC,并在结果仍可达时于替换后再次 GC;替换时间不含两次回收。报告在回收后消费结果,并检查下一个稠密序号的实时 frame 仍被接受。这测量重建,不测量传输、渲染或完整重连工作流。
 

+ 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)继续分别拥有打包和数据归属规则;本提案不取代这两份记录,也不归档任何活跃记录。

+ 1 - 0
.agents/skills/dsh-pre-push-checks/SKILL.md

@@ -31,6 +31,7 @@ There is no universal local baseline beyond the hooks. Every behavior change nee
 When the outgoing change adds or changes a resource-owning or asynchronous test, fixture, helper, or CI execution path, use [dsh-ci-test-reliability](../dsh-ci-test-reliability/SKILL.md) first to decide whether restoration, negative-control, quiescent-teardown, or concurrent-process evidence applies. This skill still selects the commands and avoids repeating evidence that already passed.
 
 - **Package or script behavior:** run the owning Vitest file or focused test name. Add adjacent package tests when a shared contract changes; leave repository-wide coverage to CI unless the change is genuinely cross-cutting or the user requests it.
+- **Remote mock typing:** unbuilt `any` is an explicit local fallback, not strict evidence. Run `pnpm run typecheck` before handing off Remote/mock changes; rebuild missing, stale, or partial generated declarations before diagnosing remaining errors. Keep the exception in the [test proxy](../../../packages/test-support/remote-mock/README.md#remote-proxy), never in production Remote types, ambient flags, or copied signatures.
 - **Documentation, Agent Notes, catalogs, or doc-linked comments:** run `pnpm run doc-sync`; run full lint when the documentation workflow requires it.
 - **Model-, editor-, CLI-, or terminal-visible output:** run the focused keyless snapshot or real runnable-example scenario that owns the output.
 - **Expected-output placement:** a test whose selected recorded Session generation is replay input and expected persisted output belongs under top-level `snapshots/`, with `snapshot.yml` naming its shipped `dsh` profile and composition/header pin. Canonical parent files are `session[.vN].jsonl`, children are `session.<ordinal>[.vN].jsonl`, and the harness selects the highest generation per role. ARIA, geometry, generator, CLI, and unit expectations without that Session round trip stay beside their owning test under `tests/expected/`; do not place them in `snapshots/` or give them a `*.snapshot.ts` owner. Use the owning `test:expected`, `test:web`, or `test` lane.

+ 2 - 1
THIRD_PARTY_NOTICES.md

@@ -114,6 +114,7 @@ External packages installed for runtime use or distributed inside the prebuilt b
 
 pnpm applies local patches to the following packages at install time, so shipped artifacts carry modified copies; each patch file is the complete record of the modification:
 
+- `@electron/osx-sign@1.3.3` — [`patches/@electron__osx-sign@1.3.3.patch`](patches/@electron__osx-sign@1.3.3.patch)
 - `@yao-pkg/pkg@6.21.0` — [`patches/@yao-pkg__pkg@6.21.0.patch`](patches/@yao-pkg__pkg@6.21.0.patch)
 - `node-pty@1.2.0-beta.15` — [`patches/node-pty@1.2.0-beta.15.patch`](patches/node-pty@1.2.0-beta.15.patch)
 
@@ -169,6 +170,7 @@ External packages **directly declared** for development, tests, types, or toolin
 | [`@types/ws`](https://github.com/DefinitelyTyped/DefinitelyTyped) | MIT |
 | [`@vitejs/plugin-react`](https://github.com/vitejs/vite-plugin-react) | MIT |
 | [`@vitest/coverage-v8`](https://github.com/vitest-dev/vitest) | MIT |
+| [`@vitest/spy`](https://github.com/vitest-dev/vitest) | MIT |
 | [`@yao-pkg/pkg`](https://github.com/yao-pkg/pkg) | MIT |
 | [`@yarnpkg/cli-dist`](https://github.com/yarnpkg/berry) | BSD-2-Clause |
 | [`app-builder-lib`](https://github.com/electron-userland/electron-builder) | MIT |
@@ -191,7 +193,6 @@ External packages **directly declared** for development, tests, types, or toolin
 | [`lightningcss`](https://github.com/parcel-bundler/lightningcss) | MPL-2.0 |
 | [`mermaid`](https://github.com/mermaid-js/mermaid) | MIT |
 | [`micromark-util-types`](https://github.com/micromark/micromark/tree/main/packages/micromark-util-types) | MIT |
-| [`msgpackr`](http://github.com/kriszyp/msgpackr) | MIT |
 | [`oxlint`](https://github.com/oxc-project/oxc) | MIT |
 | [`oxlint-tsgolint`](https://github.com/oxc-project/tsgolint) | MIT |
 | [`playwright`](https://github.com/microsoft/playwright) | Apache-2.0 |

+ 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: aa870c2a74f3b74d3f6de921c4bc5ef04fbfad3f
+README.md: 62d592307161f202f156d66d91f5a4663c3facc1
+README.zh.md: ace1497876d8b60612b8b5adf1d3ee86f1beeaa4

Разлика између датотеке није приказан због своје велике величине
+ 52 - 32
apps/desktop/README.md


Разлика између датотеке није приказан због своје велике величине
+ 52 - 32
apps/desktop/README.zh.md


+ 7 - 2
apps/desktop/electron-builder.config.d.mts

@@ -6,19 +6,24 @@ 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
     readonly writeUpdateInfo: boolean
   }
+  readonly nsis: {
+    readonly include: string
+  }
   readonly artifactBuildCompleted: (artifact: { readonly file: string }) => Promise<void> | undefined
-  readonly publish: readonly [{ readonly provider: 'generic', readonly url: string }]
+  readonly publish: readonly [{ readonly provider: 'generic', readonly url: string }] | null
 }
 
 /**

+ 29 - 9
apps/desktop/electron-builder.config.mjs

@@ -1,3 +1,5 @@
+import { join } from 'node:path'
+import { fileURLToPath } from 'node:url'
 import {
   resolveDesktopAppId,
   resolveMacOSNotarizationEnvironment,
@@ -10,7 +12,7 @@ import {
   installWindowsNsisBootstrapSigner,
 } from './scripts/windows-sign.mjs'
 import { resolveDesktopAutoUpdateConfig } from './scripts/desktop-auto-update-environment.mjs'
-import { desktopTargetBuildPaths } from './scripts/desktop-build-paths.mjs'
+import { desktopTargetBuildPaths, resolveDesktopBuildTarget } from './scripts/desktop-build-paths.mjs'
 
 /**
  * Create electron-builder configuration from one release environment.
@@ -28,11 +30,16 @@ export function createElectronBuilderConfig(
   const targetPlatform = env.DSH_DESKTOP_TARGET_PLATFORM
   const resolvedPlatform = targetPlatform ?? hostPlatform
   const resolvedArch = env.DSH_DESKTOP_TARGET_ARCH ?? hostArch
+  if (env.DSH_DESKTOP_UNSIGNED !== undefined && !['0', '1'].includes(env.DSH_DESKTOP_UNSIGNED)) {
+    throw new Error('desktop package: DSH_DESKTOP_UNSIGNED must be 0 or 1')
+  }
+  const unsigned = env.DSH_DESKTOP_UNSIGNED === '1'
+  if (unsigned && resolvedPlatform !== 'win32') throw new Error('desktop package: unsigned builds require Windows')
   const packagesMacOS = targetPlatform === 'darwin' || (targetPlatform === undefined && hostPlatform === 'darwin')
   const packagesWindows = targetPlatform === 'win32'
   const macOSSigning = packagesMacOS ? resolveMacOSSigningEnvironment(env) : undefined
   if (packagesMacOS) resolveMacOSNotarizationEnvironment(env)
-  const windowsSigner = packagesWindows
+  const windowsSigner = packagesWindows && !unsigned
     ? createWindowsTokenSigner({
         certificateFile: env.DSH_DESKTOP_WINDOWS_CER_FILE,
         signTool: env.DSH_DESKTOP_WINDOWS_SIGNTOOL,
@@ -43,13 +50,13 @@ export function createElectronBuilderConfig(
   if (windowsSigner !== undefined) {
     installWindowsNsisBootstrapSigner({ sign: windowsSigner })
   }
-  const update = resolveDesktopAutoUpdateConfig(env, resolvedPlatform, resolvedArch)
-  const buildPaths = desktopTargetBuildPaths(update.target)
+  const update = unsigned ? undefined : resolveDesktopAutoUpdateConfig(env, resolvedPlatform, resolvedArch)
+  const buildPaths = desktopTargetBuildPaths(resolveDesktopBuildTarget(env, hostPlatform, hostArch))
   return {
     appId,
     productName: 'DeepSeek Harness',
     artifactName: 'deepseek-harness-${version}-${os}-${arch}.${ext}',
-    directories: { output: buildPaths.artifacts },
+    directories: { output: unsigned ? join(buildPaths.root, 'unsigned-artifacts') : buildPaths.artifacts },
     asar: true,
     files: [
       'lib/*.js',
@@ -59,13 +66,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,
+      // Native runtime files are pre-signed; PAK resources are sealed by their enclosing bundle.
+      signIgnore: ['/Contents/Resources/dsh(?:/|$)', '\\.pak$'],
       notarize: true,
       target: ['dmg', 'zip'],
     },
@@ -73,8 +84,16 @@ export function createElectronBuilderConfig(
       sign: true,
       writeUpdateInfo: false,
     },
-    afterSign: context => {
+    afterPack: async context => {
+      const { verifyDesktopRuntime } = await import('./lib/types/runtime-tree.js')
+      await 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')
+      await 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 => {
@@ -86,7 +105,7 @@ export function createElectronBuilderConfig(
       )
     },
     win: {
-      forceCodeSigning: true,
+      forceCodeSigning: !unsigned,
       signtoolOptions: {
         sign: windowsSigner,
         signingHashAlgorithms: ['sha256'],
@@ -98,11 +117,12 @@ export function createElectronBuilderConfig(
       target: ['AppImage'],
     },
     nsis: {
+      include: fileURLToPath(new URL('./scripts/installer.nsh', import.meta.url)),
       oneClick: false,
       allowToChangeInstallationDirectory: true,
       differentialPackage: true,
     },
-    publish: [{ provider: 'generic', url: update.publicUrl }],
+    publish: update === undefined ? null : [{ provider: 'generic', url: update.publicUrl }],
   }
 }
 

+ 3 - 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.5-rc.1",
   "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",
@@ -22,6 +22,7 @@
     "package:mac:x64": "tsx scripts/package-target.ts mac-x64",
     "package:mac:x64:dir": "tsx scripts/package-target.ts mac-x64 --dir",
     "package:win:x64": "tsx scripts/package-target.ts win-x64",
+    "package:win:x64:unsigned": "tsx scripts/package-target.ts win-x64 --unsigned",
     "package:win:x64:dir": "tsx scripts/package-target.ts win-x64 --dir",
     "upload:mac:arm64": "tsx scripts/upload-target.ts mac-arm64",
     "upload:mac:x64": "tsx scripts/upload-target.ts mac-x64",
@@ -43,7 +44,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.phase !== 'error'
+    document.querySelector('#startup-error').textContent = backend.phase === 'error' ? backend.message : ''
     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, '')

+ 16 - 0
apps/desktop/renderer/startup.css

@@ -0,0 +1,16 @@
+:root { color-scheme: light dark; font-family: system-ui, sans-serif; color: #202124; background: #fafafa; }
+body { margin: 0; min-height: 100vh; display: grid; place-items: center; }
+main { width: min(560px, calc(100vw - 64px)); padding: 40px 0; text-align: center; }
+h1 { margin: 24px 0 12px; font-size: 22px; font-weight: 600; }
+p { color: #666; line-height: 1.6; }
+#spinner { width: 32px; height: 32px; margin: auto; border: 3px solid #dedee3; border-top-color: #4d6bfe; border-radius: 50%; animation: spin 0.9s linear infinite; }
+#error { padding: 16px; border: 1px solid #e0e0e5; border-radius: 10px; max-height: 220px; overflow: auto; white-space: pre-wrap; overflow-wrap: anywhere; text-align: left; font: 13px/1.6 ui-monospace, monospace; }
+#actions { margin-top: 24px; }
+button { margin: 4px; padding: 10px 18px; border: 1px solid transparent; border-radius: 8px; color: #fff; background: #4d6bfe; font: inherit; cursor: pointer; }
+button.secondary { color: inherit; background: transparent; border-color: #c8c8d0; }
+button:disabled { opacity: 0.5; cursor: default; }
+button:focus-visible { outline: 2px solid #4d6bfe; outline-offset: 3px; }
+[hidden] { display: none !important; }
+@keyframes spin { to { transform: rotate(360deg); } }
+@media (prefers-color-scheme: dark) { :root { color: #ededf0; background: #171719; } p { color: #aaaab3; } #error { border-color: #38383f; } #spinner { border-color: #38383f; border-top-color: #6a85ff; } }
+@media (prefers-reduced-motion: reduce) { #spinner { animation: none; } }

+ 26 - 0
apps/desktop/renderer/startup.html

@@ -0,0 +1,26 @@
+<!doctype html>
+<html lang="en">
+  <head>
+    <meta charset="UTF-8">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self'; connect-src 'none'; img-src 'self' data:">
+    <title id="page-title"></title>
+    <link rel="stylesheet" href="startup.css">
+  </head>
+  <body>
+    <main aria-busy="true">
+      <div id="spinner" aria-hidden="true"></div>
+      <h1 id="title" role="status" aria-live="polite"></h1>
+      <p id="description"></p>
+      <p id="reset-advice" hidden></p>
+      <p id="reinstall-advice" hidden></p>
+      <pre id="error" role="alert" hidden></pre>
+      <div id="actions" hidden>
+        <button id="restart" type="button"></button>
+        <button id="disable-plugins" type="button"></button>
+        <button id="reset-configuration" type="button"></button>
+      </div>
+    </main>
+    <script src="startup.js"></script>
+  </body>
+</html>

+ 45 - 0
apps/desktop/renderer/startup.js

@@ -0,0 +1,45 @@
+const api = window.dshDesktop
+
+async function main() {
+  const { id, messages } = await api.locale()
+  document.documentElement.lang = id
+  document.querySelector('#page-title').textContent = messages.startupLoading
+  document.querySelector('#restart').textContent = messages.restartApplication
+  document.querySelector('#disable-plugins').textContent = messages.disableThirdPartyPlugins
+  document.querySelector('#reset-configuration').textContent = messages.resetConfiguration
+  document.querySelector('#reset-advice').textContent = messages.startupConfigurationAdvice
+  document.querySelector('#reinstall-advice').textContent = messages.startupReinstallAdvice
+  function render(state) {
+    const failed = state.phase === 'error'
+    document.querySelector('main').setAttribute('aria-busy', String(!failed))
+    document.querySelector('#spinner').hidden = failed
+    document.querySelector('#title').textContent = failed ? messages.startupFailed : messages.startupLoading
+    document.querySelector('#description').textContent = failed ? messages.startupErrorDescription : messages.startupLoadingDescription
+    document.querySelector('#error').hidden = !failed
+    document.querySelector('#error').textContent = failed ? state.message : ''
+    document.querySelector('#actions').hidden = !failed
+    for (const button of document.querySelectorAll('#actions button')) button.disabled = !failed
+    for (const selector of ['#disable-plugins', '#reset-configuration', '#reset-advice']) {
+      document.querySelector(selector).hidden = !failed || !state.profileRecovery
+    }
+    document.querySelector('#reinstall-advice').hidden = !failed
+  }
+  let changed = false
+  const unsubscribe = api.backend.subscribe(state => { changed = true; render(state) })
+  window.addEventListener('pagehide', unsubscribe, { once: true })
+  const initial = await api.backend.status()
+  if (!changed) render(initial)
+  async function recover(operation) {
+    render({ phase: 'starting' })
+    try { await operation() }
+    catch (error) {
+      const current = await api.backend.status().catch(() => undefined)
+      render(current?.phase === 'error' ? current : { phase: 'error', message: error instanceof Error ? error.message : String(error) })
+    }
+  }
+  document.querySelector('#disable-plugins').addEventListener('click', () => { void recover(() => api.disablePlugins()) })
+  document.querySelector('#reset-configuration').addEventListener('click', () => { void recover(() => api.resetConfiguration()) })
+  document.querySelector('#restart').addEventListener('click', () => { void recover(() => api.restart()) })
+}
+
+void main()

+ 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'),

+ 3 - 4
apps/desktop/scripts/dev.ts

@@ -53,7 +53,7 @@ async function runPackageScript(script: string, cwd: string): Promise<void> {
   await run(process.execPath, [packageManager, 'run', script], cwd)
 }
 
-async function launchElectron(projectDir: string): Promise<void> {
+async function launchElectron(): Promise<void> {
   const require = createRequire(import.meta.url)
   const electron: unknown = require('electron')
   if (typeof electron !== 'string') throw new Error('desktop development: electron executable is unavailable')
@@ -65,7 +65,6 @@ async function launchElectron(projectDir: string): Promise<void> {
   const environment: NodeJS.ProcessEnv = {
     ...process.env,
     DSH_HOME: home,
-    DSH_DESKTOP_DEV_PROJECT_DIR: projectDir,
     DSH_DESKTOP_HOST_INSPECT_PORT: String(hostPort),
     DSH_DESKTOP_NODE_BINARY: process.execPath,
     DSH_DESKTOP_OPEN_DEVTOOLS: process.env.DSH_DESKTOP_OPEN_DEVTOOLS ?? '1',
@@ -102,14 +101,14 @@ async function main(): Promise<void> {
     nodeVersion: process.versions.node,
     pnpmVersion,
   }
-  const projectDir = prepareDevelopmentProject({
+  prepareDevelopmentProject({
     projectDir: join(DEVELOPMENT_ROOT, 'project'),
     cliDir: join(REPOSITORY_ROOT, 'apps', 'cli'),
     hostDir: join(REPOSITORY_ROOT, 'apps', 'desktop-host'),
     dependencyDir: join(REPOSITORY_ROOT, 'node_modules', '.pnpm', 'node_modules'),
     release,
   })
-  await launchElectron(projectDir)
+  await launchElectron()
 }
 
 main().catch((error: unknown) => {

+ 17 - 0
apps/desktop/scripts/installer.nsh

@@ -0,0 +1,17 @@
+!include "LogicLib.nsh"
+
+!macro customInstall
+  Push $0
+  StrCpy $0 0
+  ${If} ${Errors}
+    StrCpy $0 1
+  ${EndIf}
+  ; Finish can launch the app while NSIS removes its remaining plugin directory.
+  RMDir /r "$PLUGINSDIR\7z-out"
+  ${If} $0 == 1
+    SetErrors
+  ${Else}
+    ClearErrors
+  ${EndIf}
+  Pop $0
+!macroend

+ 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
-}

+ 30 - 6
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'
@@ -72,6 +72,25 @@ export function withoutWindowsSigningEnvironment(environment: NodeJS.ProcessEnv)
     .filter(([name]) => !name.startsWith(WINDOWS_SIGNING_ENV_PREFIX)))
 }
 
+/**
+ * Select signing and NSIS-compatible archive filters for electron-builder.
+ * @param environment - Target packaging environment.
+ * @param unsigned - Whether to create a local unsigned Windows artifact.
+ * @returns Packaging environment without certificate inputs for unsigned builds.
+ */
+export function desktopElectronBuilderEnvironment(environment: NodeJS.ProcessEnv, unsigned: boolean): NodeJS.ProcessEnv {
+  const selected: NodeJS.ProcessEnv = { ...environment, DSH_DESKTOP_UNSIGNED: unsigned ? '1' : '0' }
+  // The bundled NSIS decoder cannot extract 7-Zip's automatic ARM64-filtered entries.
+  if (environment.DSH_DESKTOP_TARGET_PLATFORM === 'win32') selected.ELECTRON_BUILDER_7Z_FILTER = 'BCJ'
+  if (!unsigned) return selected
+  return {
+    ...Object.fromEntries(Object.entries(withoutWindowsSigningEnvironment(selected))
+      .filter(([name]) => !/^(?:WIN_)?CSC_/iu.test(name))),
+    CSC_IDENTITY_AUTO_DISCOVERY: 'false',
+    DSH_DESKTOP_UNSIGNED: '1',
+  }
+}
+
 /**
  * Remove upload-only COS credentials from every packaging subprocess.
  * @param environment - Packaging command environment.
@@ -152,6 +171,7 @@ interface DesktopPackageInvocation {
   readonly target: DesktopPackageTarget
   readonly directory: boolean
   readonly prepareOnly: boolean
+  readonly unsigned: boolean
 }
 
 function hostTargetName(platform: NodeJS.Platform, arch: string): DesktopPackageTargetName {
@@ -178,14 +198,18 @@ export function parseDesktopPackageInvocation(
     options: {
       dir: { type: 'boolean', default: false },
       'prepare-only': { type: 'boolean', default: false },
+      unsigned: { type: 'boolean', default: false },
     },
   })
   if (positionals.length > 1) throw new Error('desktop package: expected at most one target')
   const name = positionals[0] ?? hostTargetName(hostPlatform, hostArch)
+  if (values.unsigned && name !== 'win-x64') throw new Error('desktop package: --unsigned requires win-x64')
+  if (values.unsigned && values['prepare-only']) throw new Error('desktop package: --unsigned cannot use --prepare-only')
   return {
     target: resolveDesktopPackageTarget(name, hostPlatform, hostArch),
     directory: values.dir,
     prepareOnly: values['prepare-only'],
+    unsigned: values.unsigned,
   }
 }
 
@@ -240,7 +264,7 @@ async function main(): Promise<void> {
   const { target } = invocation
   const buildPaths = desktopTargetBuildPaths(target.name)
   const releaseRecordPath = join(buildPaths.artifacts, desktopBuildRecordFilename(target.name))
-  if (!invocation.prepareOnly) {
+  if (!invocation.prepareOnly && !invocation.unsigned) {
     rmSync(releaseRecordPath, { force: true })
     rmSync(`${releaseRecordPath}.tmp`, { force: true })
   }
@@ -250,9 +274,9 @@ async function main(): Promise<void> {
     DSH_DESKTOP_TARGET_PLATFORM: target.platform,
     DSH_DESKTOP_TARGET_ARCH: target.arch,
   }
-  const electronBuilderEnv = { ...targetEnv }
+  const electronBuilderEnv = desktopElectronBuilderEnvironment(targetEnv, invocation.unsigned)
   for (const name of WINDOWS_SIGNING_ENV_NAMES) {
-    if (process.env[name] !== undefined) electronBuilderEnv[name] = process.env[name]
+    if (!invocation.unsigned && process.env[name] !== undefined) electronBuilderEnv[name] = process.env[name]
   }
   await runPnpm(['run', 'build:official'], buildEnv, REPOSITORY_ROOT)
   await runPnpm(['run', 'release:pack', '--family', 'dsh', '--out', buildPaths.packedDsh], buildEnv, REPOSITORY_ROOT)
@@ -276,10 +300,10 @@ 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)
+  if (!invocation.directory && !invocation.unsigned) writeReleaseRecord(target, electronBuilderEnv, buildPaths.artifacts)
 }
 
 if (process.argv[1] !== undefined && import.meta.filename === resolve(process.argv[1])) await main()

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

@@ -0,0 +1,159 @@
+/** Materialize the complete production runtime before publishing Desktop resources. */
+
+import { spawn, execFile } 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, relative, 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'
+import { desktopRuntimeFileExclusion } from './runtime-file-policy.ts'
+
+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)
+    const targetName = resolveDesktopBuildTarget()
+    const target = { platform: process.platform, arch: targetName.endsWith('arm64') ? 'arm64' : 'x64' }
+    const modules = join(BUILD_ROOT, 'node_modules')
+    mkdirSync(DSH_OUTPUT_ROOT, { recursive: true })
+    cpSync(modules, join(DSH_OUTPUT_ROOT, 'node_modules'), {
+      recursive: true, dereference: true,
+      filter: source => desktopRuntimeFileExclusion(relative(modules, source), target) === undefined,
+    })
+    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))
+    }
+    writeDesktopRuntime(DSH_OUTPUT_ROOT, release, packageSet.packages.map(entry => entry.name), target)
+    const descriptor = await verifyDesktopRuntime(DSH_OUTPUT_ROOT, release.version, target)
+    await new Promise<void>((accept, reject) => {
+      execFile(NODE, [join(APP_ROOT, 'tests/fixtures/runtime-payload-smoke.mjs'), DSH_OUTPUT_ROOT],
+        { timeout: 120_000, env: { ...process.env, NODE_OPTIONS: '' } }, (error, stdout, stderr) => {
+          if (error !== null) reject(new Error(`desktop native payload smoke failed: ${stderr}`, { cause: error }))
+          else { process.stdout.write(stdout); accept() }
+        })
+    })
+    await smokeDesktopRuntime(DSH_OUTPUT_ROOT, NODE, descriptor)
+    await 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()

+ 40 - 0
apps/desktop/scripts/runtime-file-policy.ts

@@ -0,0 +1,40 @@
+/** Desktop-only omissions from already installed production npm packages. */
+
+/**
+ * Identify build and diagnostic files omitted from the immutable Desktop runtime.
+ * Unrecognized assets and target runtime binaries are retained. Paths name the copied
+ * node_modules tree, including nested package containers.
+ * @param path - Path relative to the production node_modules directory.
+ * @param target - Platform and architecture of the bundled Node executable.
+ * @returns Omission reason, or undefined when the entry must be copied.
+ */
+export function desktopRuntimeFileExclusion(
+  path: string, target: { platform: NodeJS.Platform; arch: string },
+): string | undefined {
+  const parts = path.split(/[\\/]/u)
+  if (parts.some(part => ['.bin', '.pnpm', '.modules.yaml', '.pnpm-workspace-state-v1.json'].includes(part))) {
+    return 'package-manager metadata'
+  }
+  const file = parts.at(-1) ?? ''
+  if (/\.(?:[cm]?[jt]s|css)\.map$/u.test(file)) return 'source map'
+  if (/\.d\.[cm]?ts$/u.test(file)) return 'TypeScript declaration'
+  if (/\.tsbuildinfo$/u.test(file)) return 'TypeScript build cache'
+  const packageParts = parts.slice(parts.lastIndexOf('node_modules') + 1)
+  const nameParts = packageParts[0]?.startsWith('@') ? 2 : 1
+  const name = packageParts.slice(0, nameParts).join('/')
+  const entry = packageParts.slice(nameParts).join('/')
+  if (name === 'fs-ext' && /^build\/(?:Release|Debug)\/(?:obj(?:\/|$)|fs_ext\.(?:exp|lib|pdb|iobj|ipdb)$)/u.test(entry)) {
+    return 'fs-ext compiler output'
+  }
+  if (name === 'fs-ext' && /^build\/(?:binding\.sln|config\.gypi|fs_ext\.vcxproj(?:\.filters)?)$/u.test(entry)) {
+    return 'fs-ext build configuration'
+  }
+  if (name === '@mixmark-io/domino' && (entry === 'test' || entry.startsWith('test/'))) return 'Domino test fixtures'
+  if (name === 'node-pty' && entry.startsWith('prebuilds/')) {
+    const platform = packageParts[nameParts + 1]
+    if (platform !== undefined && platform !== `${target.platform}-${target.arch}`) return 'node-pty other platform'
+    if (file.endsWith('.pdb')) return 'node-pty debug symbols'
+  }
+  if (name === '@koromix/koffi-win32-x64' && entry === 'win32_x64/koffi.lib') return 'Koffi import library'
+  return undefined
+}

+ 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 })
+  }
+}

+ 67 - 0
apps/desktop/scripts/smoke-windows.ps1

@@ -0,0 +1,67 @@
+# Run native Electron cleanup and NSIS replacement checks against the prepared Windows target.
+param(
+  [Parameter(Mandatory)][string]$Electron,
+  [Parameter(Mandatory)][string]$Makensis,
+  [Parameter(Mandatory)][string]$SevenZip,
+  [Parameter(Mandatory)][string]$PluginDir
+)
+$ErrorActionPreference = 'Stop'
+$desktopRoot = Split-Path $PSScriptRoot -Parent
+$scratch = [System.IO.Directory]::CreateTempSubdirectory('dsh-desktop-native-').FullName
+$fixtureRoot = Join-Path $desktopRoot 'tests/fixtures'
+
+function Invoke-Checked([string]$Executable, [string[]]$Arguments) {
+  & $Executable @Arguments | Out-Host
+  if ($LASTEXITCODE -ne 0) { throw "$Executable exited with $LASTEXITCODE" }
+}
+
+try {
+  $previousRunAsNode = $env:ELECTRON_RUN_AS_NODE
+  try {
+    $env:ELECTRON_RUN_AS_NODE = '1'
+    Invoke-Checked $electron @((Join-Path $fixtureRoot 'owned-directory-smoke.mjs'))
+  } finally { $env:ELECTRON_RUN_AS_NODE = $previousRunAsNode }
+
+  $cleanupExe = Join-Path $scratch 'cleanup.exe'
+  $cleanupResult = Join-Path $scratch 'cleanup.txt'
+  Invoke-Checked $Makensis @('/V2', "/DOUTPUT_FILE=$cleanupExe", "/DRESULT_FILE=$cleanupResult", (Join-Path $fixtureRoot 'installer-cleanup-smoke.nsi'))
+  Invoke-Checked $cleanupExe @('/S')
+  if ((Get-Content -LiteralPath $cleanupResult -Raw) -ne 'scratch removed; archive, plugin, rollback, registers and error flags preserved') {
+    throw 'NSIS cleanup did not preserve its sentinels'
+  }
+
+  $payload = Join-Path $scratch 'payload'
+  New-Item -ItemType Directory -Path $payload | Out-Null
+  [System.IO.File]::WriteAllText((Join-Path $payload 'locked.txt'), 'new runtime')
+  [System.IO.File]::WriteAllText((Join-Path $payload 'asset.txt'), 'new asset')
+  $archive = Join-Path $scratch 'payload.7z'
+  Invoke-Checked $SevenZip @('a', '-bd', '-t7z', $archive, "$payload/*")
+  foreach ($mode in @('copy', 'direct')) {
+    $target = Join-Path $scratch $mode
+    New-Item -ItemType Directory -Path $target | Out-Null
+    $locked = Join-Path $target 'locked.txt'
+    [System.IO.File]::WriteAllText($locked, 'old runtime')
+    $probeExe = Join-Path $scratch "$mode.exe"
+    $probeResult = Join-Path $scratch "$mode.txt"
+    $compileArgs = @('/V2', "/DOUTPUT_FILE=$probeExe", "/DRESULT_FILE=$probeResult", "/DPAYLOAD_FILE=$archive", "/DTARGET_DIR=$target", "/DPLUGIN_DIR=$PluginDir")
+    if ($mode -eq 'direct') { $compileArgs += '/DDIRECT' }
+    $compileArgs += Join-Path $fixtureRoot 'installer-write-failure-smoke.nsi'
+    Invoke-Checked $Makensis $compileArgs
+    $handle = [System.IO.File]::Open($locked, 'Open', 'Read', 'Read')
+    try { Invoke-Checked $probeExe @('/S') }
+    finally { $handle.Dispose() }
+    $flag = if ($mode -eq 'copy') { 'true' } else { 'false' }
+    $expected = "errorFlag=$flag`nlocked=old runtime`nasset=new asset"
+    if ((Get-Content -LiteralPath $probeResult -Raw).Replace("`r`n", "`n").TrimEnd() -ne $expected) {
+      throw "Unexpected NSIS $mode replacement result"
+    }
+  }
+  Write-Output 'Electron cleanup and NSIS cleanup/replacement smokes passed.'
+} finally {
+  $tempRoot = [System.IO.Path]::GetFullPath([System.IO.Path]::GetTempPath())
+  $resolvedScratch = [System.IO.Path]::GetFullPath($scratch)
+  if (-not $resolvedScratch.StartsWith($tempRoot, [System.StringComparison]::OrdinalIgnoreCase)) {
+    throw "Refusing cleanup outside the temporary root: $resolvedScratch"
+  }
+  Remove-Item -LiteralPath $resolvedScratch -Recurse -Force
+}

+ 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)
 }
 
 /**

+ 148 - 0
apps/desktop/src/backend-controller.ts

@@ -0,0 +1,148 @@
+/** Owns one backend startup and its quiescent teardown independently of windows. */
+
+import { desktopErrorState } from './startup-error.ts'
+
+/** Backend availability presented by the desktop window. */
+export type DesktopBackendState = { readonly phase: 'starting' } | { readonly phase: 'ready' } | { readonly phase: 'error'; readonly message: string; readonly profileRecovery?: boolean }
+
+/** Child lifecycle owned by the desktop backend controller. */
+export interface DesktopBackendHost {
+  /** @returns Readiness after the child accepts application requests. */
+  start(): Promise<unknown>
+  /** @returns Completion of child exit. */
+  stop(): Promise<void>
+}
+
+interface Attempt<Host> {
+  cancelled: boolean
+  failure?: Error
+  host?: Host
+  cleanup?: Promise<void>
+}
+
+/** Serializes retries and prevents children from outliving a closed window. */
+export class DesktopBackendController<Host extends DesktopBackendHost> {
+  private current: DesktopBackendState = { phase: 'starting' }
+  private attempt: Attempt<Host> | undefined
+  private pending: Promise<void> | undefined
+  private stopping: Promise<void> | undefined
+  private closed = false
+
+  /**
+   * @param createHost - Allocate a child and route its fatal failures to the supplied callback.
+   * @param publish - Receive availability changes until the controller closes.
+   */
+  constructor(
+    private readonly createHost: (onFailure: (error: Error) => void) => Host,
+    private readonly publish: (state: DesktopBackendState) => void,
+  ) {}
+
+  /** Current availability, including the last startup or child failure. */
+  get state(): DesktopBackendState { return this.current }
+
+  /** Child available to application requests; absent during startup and teardown. */
+  get host(): Host | undefined { return !this.closed && !this.attempt?.cancelled && this.current.phase === 'ready' ? this.attempt?.host : undefined }
+
+  /**
+   * Prepare the profile and start one child; concurrent callers share the attempt.
+   * @param prepare - Profile preparation that must finish before spawning.
+   * @returns Completion of startup, rejecting on preparation, startup, or cleanup failure.
+   */
+  start(prepare: () => Promise<void>): Promise<void> {
+    if (this.closed) return Promise.reject(new Error('desktop backend is closed'))
+    if (this.stopping !== undefined) return Promise.reject(new Error('desktop backend is stopping'))
+    if (this.pending !== undefined) return this.pending
+    if (this.current.phase === 'ready') return Promise.resolve()
+    const previous = this.attempt
+    const attempt: Attempt<Host> = { cancelled: false, ...(previous?.cleanup === undefined ? {} : { cleanup: previous.cleanup }) }
+    this.attempt = attempt
+    this.update({ phase: 'starting' })
+    const pending = Promise.resolve().then(async () => {
+      try {
+        await previous?.cleanup
+        delete attempt.cleanup
+        if (attempt.cancelled) return
+        await prepare()
+        // stop() can cancel this attempt while preparation is pending.
+        // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
+        if (attempt.cancelled) return
+        const host = this.createHost((error) => { this.failed(attempt, error) })
+        attempt.host = host
+        await host.start()
+        if (attempt.failure !== undefined) throw attempt.failure
+        // stop() can cancel this attempt while the child starts.
+        // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
+        if (!attempt.cancelled) this.update({ phase: 'ready' })
+      } catch (error) {
+        const cancelled = attempt.cancelled
+        attempt.cancelled = true
+        let failure = error
+        try { await this.cleanup(attempt) } catch (cleanupError) {
+          if (cleanupError !== error) failure = new AggregateError([error, cleanupError], 'desktop backend startup and cleanup failed')
+        }
+        if (!cancelled) this.update(desktopErrorState(failure))
+        throw failure
+      }
+    }).finally(() => { if (this.pending === pending) this.pending = undefined })
+    this.pending = pending
+    return pending
+  }
+
+  /**
+   * Stop pending preparation and the child before allowing another start.
+   * @returns Completion of pending work and child exit; rejects if cleanup fails.
+   */
+  stop(): Promise<void> {
+    if (this.stopping !== undefined) return this.stopping
+    const attempt = this.attempt
+    if (attempt !== undefined) attempt.cancelled = true
+    if (!this.closed) this.update({ phase: 'starting' })
+    const pending = this.pending
+    const stopping = Promise.allSettled([
+      attempt === undefined ? Promise.resolve() : this.cleanup(attempt),
+      pending,
+    ]).then((results) => {
+      const cleanup = results[0]
+      if (cleanup.status === 'rejected') throw cleanup.reason
+      if (this.attempt === attempt) this.attempt = undefined
+    }).finally(() => { if (this.stopping === stopping) this.stopping = undefined })
+    this.stopping = stopping
+    return stopping
+  }
+
+  /**
+   * Permanently prevent startup and suppress further availability notifications.
+   * @returns Completion of pending work and child exit; rejects if cleanup fails.
+   */
+  close(): Promise<void> {
+    this.closed = true
+    return this.stop()
+  }
+
+  private cleanup(attempt: Attempt<Host>): Promise<void> {
+    if (attempt.cleanup === undefined) {
+      attempt.cleanup = Promise.resolve().then(async () => { await attempt.host?.stop() })
+    }
+    return attempt.cleanup
+  }
+
+  private failed(attempt: Attempt<Host>, error: Error): void {
+    if (this.attempt !== attempt || attempt.cancelled) return
+    attempt.failure = error
+    if (this.current.phase !== 'ready') return
+    attempt.cancelled = true
+    const cleanup = this.cleanup(attempt)
+    this.update(desktopErrorState(error))
+    void cleanup.catch((cleanupError: unknown) => {
+      if (this.attempt === attempt) this.update(desktopErrorState(new AggregateError([error, cleanupError], 'Desktop backend failed and could not stop')))
+    })
+  }
+
+  private update(state: DesktopBackendState): void {
+    if (this.closed) return
+    this.current = state
+    try { this.publish(state) } catch (error) {
+      console.error('desktop backend state listener failed', error)
+    }
+  }
+}

+ 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.
  */

+ 20 - 6
apps/desktop/src/host-process.ts

@@ -83,31 +83,39 @@ export class DesktopHostProcess {
   })
   private exitPromise: Promise<void> | undefined
   private stderr = ''
+  private failureReported = false
 
   /**
    * @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.
+   * @param onFailure - Receives the first fatal child or transport failure, including after readiness.
    */
   constructor(
     private readonly node: string,
+    private readonly runtimeDir: string,
     private readonly projectDir: string,
     private readonly inspectPort?: number,
+    private readonly environment: NodeJS.ProcessEnv = process.env,
+    private readonly onFailure?: (error: Error) => void,
   ) {}
 
   /** 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'],
     })
@@ -144,7 +152,7 @@ export class DesktopHostProcess {
     })
     child.once('error', (error) => { this.fail(error) })
     this.exitPromise = new Promise<void>((resolve) => {
-      child.once('exit', (code) => {
+      child.once('close', (code) => {
         const suffix = this.stderr.trim() === '' ? '' : `: ${this.stderr.trim()}`
         if (code !== 0 && code !== null) this.fail(new Error(`dsh desktop host exited with ${String(code)}${suffix}`))
         else this.fail(new Error(`dsh desktop host stopped${suffix}`))
@@ -273,7 +281,7 @@ export class DesktopHostProcess {
   private send(message: DesktopHostCommand): void {
     const child = this.child
     if (child === undefined || !child.connected) throw new Error('dsh desktop host IPC is unavailable')
-    child.send(message)
+    child.send(message, (error) => { if (error !== null) this.fail(error) })
   }
 
   private acceptResponseBytes(chunk: Buffer): void {
@@ -400,6 +408,12 @@ export class DesktopHostProcess {
 
   private fail(error: Error): void {
     this.readyReject(error)
+    if (!this.failureReported) {
+      this.failureReported = true
+      try { this.onFailure?.(error) } catch (listenerError) {
+        console.error('desktop host failure listener failed', listenerError)
+      }
+    }
     for (const pending of this.pending.values()) {
       void pending.requestReader?.cancel(error).catch(() => undefined)
       if (pending.controller === undefined) pending.reject(error)

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

@@ -2,6 +2,7 @@
 
 import type { DesktopPluginRecord } from './project-manager.ts'
 import type { DesktopLocale } from './locale.ts'
+import type { DesktopBackendState } from './backend-controller.ts'
 
 /** IPC channel names kept private to the desktop application bundle. */
 export const DESKTOP_IPC = {
@@ -10,6 +11,13 @@ 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',
+  applicationRestart: 'dsh-desktop:application-restart',
+  configurationReset: 'dsh-desktop:configuration-reset',
+  backendState: 'dsh-desktop:backend-state',
   updatesCheck: 'dsh-desktop:updates-check',
   updatesInstall: 'dsh-desktop:updates-install',
   updatesState: 'dsh-desktop:updates-state',
@@ -31,6 +39,13 @@ 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<DesktopBackendState>
+    retry(): Promise<void>
+    subscribe(listener: (state: DesktopBackendState) => void): () => void
   }
   readonly updates: {
     check(): Promise<DesktopUpdateState>
@@ -38,3 +53,11 @@ export interface DshDesktopApi {
     subscribe(listener: (state: DesktopUpdateState) => void): () => void
   }
 }
+
+/** Startup-page controls, unavailable to backend-provided application documents. */
+export interface DshDesktopStartupApi extends Pick<DshDesktopApi, 'protocolVersion' | 'locale'> {
+  readonly backend: Omit<DshDesktopApi['backend'], 'retry'>
+  disablePlugins(): Promise<void>
+  restart(): Promise<void>
+  resetConfiguration(): Promise<void>
+}

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

@@ -3,6 +3,14 @@
 export const en = {
   application: 'Application',
   startupFailed: 'DeepSeek Harness could not start',
+  startupLoading: 'Starting DeepSeek Harness…',
+  startupLoadingDescription: 'Your workspace will open when it is ready.',
+  startupErrorDescription: 'Choose a recovery action below. Disabling third-party plugins retains their files.',
+  startupReinstallAdvice: 'If application files are missing or damaged, close the application and reinstall it. Your tasks are stored separately.',
+  startupConfigurationAdvice: 'Reset Desktop deletes all Desktop profile configuration and third-party plugins without a backup, then starts a fresh profile. Shared tasks and settings are retained.',
+  restartApplication: 'Close and restart',
+  resetConfiguration: 'Reset Desktop and retry',
+  disableThirdPartyPlugins: 'Disable all third-party plugins and retry',
   pluginsMenu: 'Desktop Plugins…',
   pluginsMenuPackagedOnly: 'Desktop Plugins… (available in packaged applications)',
   checkUpdatesMenu: 'Check for Updates…',
@@ -20,6 +28,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',
@@ -42,6 +57,14 @@ export type DesktopMessages = { readonly [Key in keyof typeof en]: string }
 export const zh = {
   application: '应用',
   startupFailed: 'DeepSeek Harness 无法启动',
+  startupLoading: '正在启动 DeepSeek Harness…',
+  startupLoadingDescription: '准备就绪后将自动打开工作区。',
+  startupErrorDescription: '请选择下方的恢复操作。禁用第三方插件会保留插件文件。',
+  startupReinstallAdvice: '如果应用文件缺失或损坏,请关闭应用并重新安装。任务数据存储在独立位置。',
+  startupConfigurationAdvice: '重置 Desktop 会删除桌面端的全部 profile 配置和第三方插件,不保留备份,然后重新初始化并启动。共享任务和设置会保留。',
+  restartApplication: '关闭并重启',
+  resetConfiguration: '重置 Desktop 并重试',
+  disableThirdPartyPlugins: '禁用全部第三方插件并重试',
   pluginsMenu: '桌面插件…',
   pluginsMenuPackagedOnly: '桌面插件…(打包应用中可用)',
   checkUpdatesMenu: '检查更新…',
@@ -59,6 +82,13 @@ export const zh = {
   pluginWindowTitle: 'DeepSeek Harness — 桌面插件',
   pluginManagerDescription: '插件只安装到桌面端自己的 node_modules,并由内置 pnpm 管理。',
   refresh: '刷新',
+  enable: '启用',
+  disable: '禁用',
+  disabled: '已禁用',
+  retry: '重试启动',
+  disableAll: '禁用全部插件并重试',
+  recoveryDescription: '后端无法启动。请更新或禁用不兼容插件,然后重试。已安装插件和配置会保留。',
+  changingActivation: '正在更改插件启用状态…',
   npmPackage: 'npm 包',
   install: '安装',
   installed: '已安装',

+ 217 - 93
apps/desktop/src/main.ts

@@ -15,16 +15,31 @@ import {
 import { resolveDesktopPaths } from './paths.ts'
 import { DesktopProjectManager, type DesktopProjectHooks } from './project-manager.ts'
 import { DesktopHostProcess } from './host-process.ts'
+import { DesktopBackendController, type DesktopBackendState } from './backend-controller.ts'
 import { DESKTOP_IPC, type DesktopUpdateState } from './ipc.ts'
 import { formatDesktopMessage, resolveDesktopLocale } from './locale.ts'
 import { claimDesktopSingleInstance } from './single-instance.ts'
 import { DesktopUpdateCoordinator } from './update-coordinator.ts'
+import { desktopErrorState } from './startup-error.ts'
+import { startupFailureDocument } from './startup-document.ts'
 
 const SCHEME = 'dsh-app'
 let focusPrimaryWindow = (): void => {}
+type RecoveryAction = 'restart' | 'plugins' | 'reset'
+let profileRecoveryAvailable = (): boolean => false
+const emergencyPages = new WeakMap<BrowserWindow, { url: string; message: string; busy: boolean }>()
+let recoverApplication = (action: RecoveryAction): Promise<void> => {
+  if (action !== 'restart') return Promise.reject(new Error('Desktop recovery could not initialize; reinstall the application'))
+  app.relaunch()
+  app.quit()
+  return Promise.resolve()
+}
 
-function errorOf(reason: unknown, fallback: string): Error {
-  return reason instanceof Error ? reason : new Error(fallback)
+async function showEmergencyDocument(window: BrowserWindow, message: string): Promise<void> {
+  const document = startupFailureDocument(resolveDesktopLocale(app.getLocale()), message, profileRecoveryAvailable())
+  const url = `data:text/html;charset=utf-8,${encodeURIComponent(document)}`
+  emergencyPages.set(window, { url, message, busy: false })
+  await window.loadURL(url)
 }
 
 protocol.registerSchemesAsPrivileged([{
@@ -49,7 +64,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,15 +73,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 }
-}
-
-function developmentProject(): string | undefined {
-  const configured = process.env.DSH_DESKTOP_DEV_PROJECT_DIR
-  if (configured === undefined || configured === '') return undefined
-  if (app.isPackaged) throw new Error('dsh desktop: development project override is unavailable in packaged applications')
-  return resolve(configured)
+  const dsh = (development ? process.env.DSH_DESKTOP_DSH_DIR : undefined) ?? join(process.resourcesPath, 'dsh')
+  return { node, pnpm, dsh }
 }
 
 function developmentHostInspectPort(enabled: boolean): number | undefined {
@@ -79,13 +87,13 @@ function developmentHostInspectPort(enabled: boolean): number | undefined {
   return port
 }
 
-function createWindow(preload: string): BrowserWindow {
+function createWindow(preload: string, show = false): BrowserWindow {
   const window = new BrowserWindow({
     width: 1280,
     height: 840,
     minWidth: 880,
     minHeight: 600,
-    show: false,
+    show,
     webPreferences: {
       preload,
       nodeIntegration: false,
@@ -97,6 +105,15 @@ function createWindow(preload: string): BrowserWindow {
   window.webContents.setWindowOpenHandler(() => ({ action: 'deny' }))
   window.webContents.on('will-navigate', (event, url) => {
     if (new URL(url).protocol !== `${SCHEME}:`) event.preventDefault()
+    const page = emergencyPages.get(window)
+    if (page === undefined || page.busy || window.webContents.getURL() !== page.url) return
+    const action = new URL(url)
+    if (action.protocol !== 'dsh-recovery:' || !['restart', 'plugins', 'reset'].includes(action.hostname)) return
+    if (action.hostname !== 'restart' && !profileRecoveryAvailable()) return
+    page.busy = true
+    void recoverApplication(action.hostname as RecoveryAction).catch(async (error: unknown) => {
+      if (!window.isDestroyed()) await showEmergencyDocument(window, `${page.message}\n${desktopErrorState(error).message}`)
+    }).catch((error: unknown) => { console.error(error) }).finally(() => { page.busy = false })
   })
   return window
 }
@@ -133,12 +150,13 @@ async function serveShellAsset(request: Request): Promise<Response> {
 async function main(): Promise<void> {
   const resources = runtimeResources()
   const paths = resolveDesktopPaths()
-  const development = developmentProject()
+  const development = app.isPackaged ? undefined : join(app.getAppPath(), '.desktop-build', 'development', 'project')
   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
+  profileRecoveryAvailable = () => development === undefined && manager.canRecoverProfile()
+  let pageError: Extract<DesktopBackendState, { phase: 'error' }> | undefined
+  let quitting = false
+  let startup: Promise<void> | undefined
   let mainWindow: BrowserWindow | undefined
   let pluginWindow: BrowserWindow | undefined
   let shellInstallerOwnsQuit = false
@@ -147,6 +165,56 @@ async function main(): Promise<void> {
   const messages = locale.messages
   const appPreload = fileURLToPath(new URL('./preload-app.cjs', import.meta.url))
   const managementPreload = fileURLToPath(new URL('./preload.cjs', import.meta.url))
+  const startupUrl = `${SCHEME}://shell/startup.html`
+  const applicationUrl = `${SCHEME}://app/index.html`
+  let navigation: { window: BrowserWindow; url: string; promise: Promise<void> } | undefined
+  let emergencyDocument = false
+
+  const showEmergencyError = async (error: unknown): Promise<void> => {
+    if (quitting || emergencyDocument) return
+    emergencyDocument = true
+    const diagnostic = desktopErrorState(error).message
+    pageError = { phase: 'error', message: diagnostic }
+    if (mainWindow !== undefined) await showEmergencyDocument(mainWindow, diagnostic)
+  }
+
+  const navigateMain = (url: string): Promise<void> => {
+    const window = mainWindow
+    if (quitting || emergencyDocument || window === undefined || window.isDestroyed()) return Promise.resolve()
+    if (navigation?.window === window && navigation.url === url) return navigation.promise
+    const next = { window, url, promise: Promise.resolve() }
+    next.promise = window.loadURL(url).catch((error: unknown) => {
+      if (quitting || window.isDestroyed() || navigation !== next) return
+      navigation = undefined
+      throw error
+    })
+    navigation = next
+    return next.promise
+  }
+  const backendState = (): DesktopBackendState => {
+    const state = pageError ?? backend.state
+    return state.phase === 'error' ? { ...state, profileRecovery: profileRecoveryAvailable() } : state
+  }
+  const publishBackend = (state: DesktopBackendState): void => {
+    for (const window of BrowserWindow.getAllWindows()) {
+      window.webContents.send(DESKTOP_IPC.backendState, state)
+    }
+  }
+  const backend = new DesktopBackendController((onFailure) => {
+    if (development === undefined) manager.assertProfileRuntime(activeProject)
+    const hostInspectPort = developmentHostInspectPort(development !== undefined)
+    const host = new DesktopHostProcess(resources.node, development ?? resources.dsh, activeProject,
+      hostInspectPort, process.env, onFailure)
+    return {
+      start: () => host.start(),
+      stop: () => host.stop(),
+      fetch: (request: Request) => host.fetch(request),
+    }
+  }, (state) => {
+    if (state.phase === 'starting' && !emergencyDocument) pageError = undefined
+    publishBackend(backendState())
+    if (state.phase === 'error') void navigateMain(startupUrl).catch((error: unknown) => { console.error(error) })
+  })
 
   const publishUpdate = (state: DesktopUpdateState): DesktopUpdateState => {
     updateState = state
@@ -156,76 +224,73 @@ async function main(): Promise<void> {
     return state
   }
 
-  const startHost = async (projectDir = activeProject): Promise<DesktopHostProcess> => {
-    const next = new DesktopHostProcess(resources.node, projectDir, hostInspectPort)
-    await next.start()
-    return next
-  }
   const hooks: DesktopProjectHooks = {
-    healthCheck: async (projectDir) => {
-      const active = host
-      host = undefined
-      await active?.stop()
-      let healthFailure: unknown
-      let probe: DesktopHostProcess | undefined
-      try {
-        probe = await startHost(projectDir)
-        await probe.stop()
-      } catch (error) {
-        healthFailure = error
-        await probe?.stop().catch(() => undefined)
-      }
-      let restartFailure: unknown
-      if (active !== undefined) {
-        try {
-          host = await startHost()
-        } catch (error) {
-          restartFailure = error
-        }
-      }
-      if (healthFailure !== undefined && restartFailure !== undefined) {
-        throw new AggregateError([
-          errorOf(healthFailure, 'desktop project: staged health check failed'),
-          errorOf(restartFailure, 'desktop project: active backend restart failed'),
-        ], 'desktop project: staged health check and active backend restart failed')
-      }
-      if (healthFailure !== undefined) throw errorOf(healthFailure, 'desktop project: staged health check failed')
-      if (restartFailure !== undefined) throw errorOf(restartFailure, 'desktop project: active backend restart failed')
-    },
-    beforeActivate: async () => {
-      const active = host
-      host = undefined
-      await active?.stop()
-    },
-    afterActivate: async () => {
-      host = await startHost()
-    },
+    beforeChange: () => backend.stop(),
+    afterChange: () => backend.start(async () => {}),
   }
 
-  if (development === undefined) {
-    await manager.applyRelease(resources.seed, app.getVersion(), {
-      ...hooks,
-      beforeActivate: async () => {},
-      afterActivate: async () => {},
-    })
+  recoverApplication = async (action): Promise<void> => {
+    await startup?.catch(() => undefined)
+    await backend.stop()
+    if (action === 'restart') {
+      app.relaunch()
+      app.quit()
+      return
+    }
+    if (!profileRecoveryAvailable()) throw new Error(messages.startupReinstallAdvice)
+    if (action === 'reset') await manager.resetConfiguration(hooks)
+    else await manager.mutate({ type: 'plugins-disable-all' }, hooks)
+    emergencyDocument = false
+    pageError = undefined
+    navigation = undefined
+    await navigateMain(applicationUrl)
+  }
+
+  const showStartupError = async (error: unknown): Promise<void> => {
+    if (quitting) return
+    pageError = desktopErrorState(error)
+    try { await navigateMain(startupUrl) }
+    catch (navigationError) {
+      await showEmergencyError(new AggregateError([error, navigationError], messages.startupFailed))
+    }
+    publishBackend(backendState())
+  }
+  const reconcileBackend = (): Promise<void> => {
+    startup ??= (async () => {
+      pageError = undefined
+      await navigateMain(startupUrl)
+      await backend.start(async () => {
+        if (development === undefined) {
+          await manager.applyRelease()
+        }
+      })
+      if (backend.host !== undefined) await navigateMain(applicationUrl)
+    })().catch(async (error: unknown) => {
+      await showStartupError(error)
+      throw error
+    }).finally(() => { startup = undefined })
+    return startup
   }
-  host = await startHost()
 
   const updates = new DesktopUpdateCoordinator(
     publishUpdate,
     async () => {
       shellInstallerOwnsQuit = true
-      const active = host
-      host = undefined
-      await active?.stop()
+      await backend.stop()
     },
   )
 
   protocol.handle(SCHEME, (request) => {
     const url = new URL(request.url)
-    if (url.hostname === 'shell') return serveShellAsset(request)
+    if (url.hostname === 'shell') return serveShellAsset(request).then((response) => {
+      if (response.status >= 400 && ['/startup.html', '/startup.js', '/startup.css'].includes(url.pathname)) {
+        void showEmergencyError(new Error(`Desktop recovery resource could not be loaded: ${url.pathname} (HTTP ${response.status})`))
+          .catch((error: unknown) => { console.error(error) })
+      }
+      return response
+    })
     if (url.hostname !== 'app') return Promise.resolve(new Response(null, { status: 404 }))
-    const active = host
+    const active = backend.host
     if (active === undefined) return Promise.resolve(new Response('backend unavailable', { status: 503 }))
     return active.fetch(request)
   })
@@ -235,8 +300,16 @@ async function main(): Promise<void> {
     if (development !== undefined) {
       throw new Error('dsh desktop: plugin package changes require a packaged application')
     }
-    await manager.mutate(mutation, hooks)
-    if (mainWindow !== undefined && !mainWindow.isDestroyed()) mainWindow.webContents.reload()
+    await startup?.catch(() => undefined)
+    pageError = undefined
+    await navigateMain(startupUrl)
+    try {
+      await manager.mutate(mutation, hooks)
+      await navigateMain(applicationUrl)
+    } catch (error) {
+      await showStartupError(error)
+      throw error
+    }
   }
   ipcMain.handle(DESKTOP_IPC.localeGet, (event) => {
     assertDesktopSender(event, ['shell'])
@@ -261,6 +334,42 @@ 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 backendState()
+  })
+  ipcMain.handle(DESKTOP_IPC.backendRetry, async (event) => {
+    assertDesktopSender(event, ['shell'])
+    await reconcileBackend()
+    focusPrimaryWindow()
+  })
+  ipcMain.handle(DESKTOP_IPC.applicationRestart, async (event) => {
+    assertDesktopSender(event, ['shell'])
+    try {
+      await recoverApplication('restart')
+    } catch (error) {
+      await showStartupError(error)
+    }
+  })
+  ipcMain.handle(DESKTOP_IPC.configurationReset, async (event) => {
+    assertDesktopSender(event, ['shell'])
+    if (development !== undefined) throw new Error('Desktop configuration reset requires a packaged application')
+    const failure = backendState()
+    if (failure.phase !== 'error') {
+      throw new Error('Desktop profile reset requires a startup failure')
+    }
+    await startup?.catch(() => undefined)
+    try {
+      await recoverApplication('reset')
+    } catch (error) {
+      await showStartupError(error)
+    }
+  })
   ipcMain.handle(DESKTOP_IPC.updatesCheck, async (event) => {
     assertDesktopSender(event, ['shell'])
     return updates.check()
@@ -341,17 +450,26 @@ async function main(): Promise<void> {
   }]))
 
   const createMainWindow = (): BrowserWindow => {
-    const window = createWindow(appPreload)
+    const window = createWindow(appPreload, true)
     mainWindow = window
-    window.once('ready-to-show', () => { if (!window.isDestroyed()) window.show() })
     window.on('closed', () => { if (mainWindow === window) mainWindow = undefined })
+    window.webContents.on('preload-error', (_event, _path, error) => {
+      void showEmergencyError(error).catch((failure: unknown) => { console.error(failure) })
+    })
+    window.webContents.on('render-process-gone', (_event, details) => {
+      navigation = undefined
+      emergencyDocument = false
+      void showStartupError(new Error(`Desktop renderer exited: ${details.reason}`))
+        .catch((failure: unknown) => { console.error(failure) })
+    })
     return window
   }
   focusPrimaryWindow = () => {
     const window = mainWindow
     if (window === undefined || window.isDestroyed()) {
-      const replacement = createMainWindow()
-      void replacement.loadURL(`${SCHEME}://app/index.html`)
+      createMainWindow()
+      void navigateMain(backendState().phase === 'ready' ? applicationUrl : startupUrl)
+        .catch((error: unknown) => { console.error(error) })
       return
     }
     if (window.isMinimized()) window.restore()
@@ -359,14 +477,6 @@ 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') {
-    mainWindow.webContents.openDevTools({ mode: 'detach' })
-  }
-  publishUpdate(updateState)
-  setTimeout(() => { void checkAndPrompt(false) }, 10_000)
-
   app.on('activate', () => {
     if (BrowserWindow.getAllWindows().length === 0) focusPrimaryWindow()
   })
@@ -374,13 +484,23 @@ async function main(): Promise<void> {
     if (process.platform !== 'darwin') app.quit()
   })
   app.on('before-quit', (event) => {
-    if (shellInstallerOwnsQuit) return
-    if (host === undefined) return
+    if (shellInstallerOwnsQuit || quitting) return
     event.preventDefault()
-    const active = host
-    host = undefined
-    void active.stop().finally(() => { app.quit() })
+    quitting = true
+    void backend.close().catch((error: unknown) => { console.error(error) }).finally(() => { app.quit() })
   })
+
+  mainWindow = createMainWindow()
+  await reconcileBackend().catch(() => undefined)
+  // Window lifecycle callbacks run while backend startup is pending.
+  // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
+  if (quitting) return
+  // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
+  if (mainWindow !== undefined && development !== undefined && process.env.DSH_DESKTOP_OPEN_DEVTOOLS !== '0') {
+    mainWindow.webContents.openDevTools({ mode: 'detach' })
+  }
+  publishUpdate(updateState)
+  setTimeout(() => { void checkAndPrompt(false) }, 10_000)
 }
 
 const ownsDesktopInstance = claimDesktopSingleInstance(app, () => { focusPrimaryWindow() })
@@ -392,6 +512,10 @@ if (ownsDesktopInstance) void app.whenReady().then(main).catch(async (error: unk
   if (diagnosticFile !== undefined) {
     await writeFile(diagnosticFile, `${error instanceof Error ? error.stack ?? message : message}\n`).catch(() => undefined)
   }
-  dialog.showErrorBox(resolveDesktopLocale(app.getLocale()).messages.startupFailed, message)
+  const window = BrowserWindow.getAllWindows()[0] ?? createWindow(fileURLToPath(new URL('./preload-app.cjs', import.meta.url)), true)
+  window.once('closed', () => { app.quit() })
+  await showEmergencyDocument(window, message)
+}).catch((error: unknown) => {
+  console.error(error)
   app.exit(1)
 })

+ 26 - 0
apps/desktop/src/owned-directory.ts

@@ -0,0 +1,26 @@
+/** Desktop transaction cleanup that unlinks directory links without visiting their targets. */
+
+import { lstatSync, readdirSync, rmdirSync, unlinkSync } from 'node:fs'
+import { join } from 'node:path'
+
+/**
+ * Remove an owned directory and its contents, unlinking root and nested links.
+ * Missing roots are ignored; existing roots must be directories or links.
+ * @param path - Owned directory or link to remove; link targets are preserved.
+ */
+export function removeOwnedDirectory(path: string): void {
+  const stat = lstatSync(path, { throwIfNoEntry: false })
+  if (stat === undefined) return
+  if (stat.isSymbolicLink()) {
+    unlinkSync(path)
+    return
+  }
+  if (!stat.isDirectory()) throw new Error(`desktop project: owned directory path is not a directory: ${path}`)
+  // Electron's recursive rm follows nested Windows junctions into installed resources.
+  for (const entry of readdirSync(path, { withFileTypes: true })) {
+    const child = join(path, entry.name)
+    if (entry.isDirectory()) removeOwnedDirectory(child)
+    else unlinkSync(child)
+  }
+  rmdirSync(path)
+}

+ 1 - 7
apps/desktop/src/paths.ts

@@ -7,9 +7,6 @@ import { resolveDshHome } from '@deepseek-ai/dsh-home-paths'
 export interface DesktopPaths {
   readonly root: string
   readonly profile: string
-  readonly staging: string
-  readonly rollback: string
-  readonly pending: string
   readonly lock: string
   readonly pnpm: {
     readonly root: string
@@ -32,10 +29,7 @@ export function resolveDesktopPaths(dshHome: string = resolveDshHome()): Desktop
   return {
     root,
     profile: join(dshHome, 'profiles', 'desktop'),
-    staging: join(root, 'staging'),
-    rollback: join(root, 'rollback', 'profile'),
-    pending: join(root, 'pending.json'),
-    lock: join(root, 'lock'),
+    lock: join(dshHome, 'profiles', 'desktop', 'lock'),
     pnpm: {
       root: pnpm,
       store: join(pnpm, 'store'),

+ 22 - 3
apps/desktop/src/preload-app.ts

@@ -1,5 +1,24 @@
-/** Minimal marker that selects the desktop custom-protocol API carrier. */
+/** Startup controls for shell documents; application documents receive only the carrier marker. */
 
-import { contextBridge } from 'electron'
+import { contextBridge, ipcRenderer } from 'electron'
+import { DESKTOP_IPC, type DshDesktopStartupApi } from './ipc.ts'
+import type { DesktopBackendState } from './backend-controller.ts'
 
-contextBridge.exposeInMainWorld('dshDesktop', { protocolVersion: 1 })
+const startup: DshDesktopStartupApi = {
+  protocolVersion: 1,
+  locale: () => ipcRenderer.invoke(DESKTOP_IPC.localeGet) as ReturnType<DshDesktopStartupApi['locale']>,
+  backend: {
+    status: () => ipcRenderer.invoke(DESKTOP_IPC.backendStatus) as ReturnType<DshDesktopStartupApi['backend']['status']>,
+    subscribe(listener) {
+      const handle = (_event: Electron.IpcRendererEvent, state: DesktopBackendState): void => { listener(state) }
+      ipcRenderer.on(DESKTOP_IPC.backendState, handle)
+      return () => { ipcRenderer.off(DESKTOP_IPC.backendState, handle) }
+    },
+  },
+  disablePlugins: () => ipcRenderer.invoke(DESKTOP_IPC.pluginsDisableAll) as Promise<void>,
+  restart: () => ipcRenderer.invoke(DESKTOP_IPC.applicationRestart) as Promise<void>,
+  resetConfiguration: () => ipcRenderer.invoke(DESKTOP_IPC.configurationReset) as Promise<void>,
+}
+
+contextBridge.exposeInMainWorld('dshDesktop', location.protocol === 'dsh-app:' && location.hostname === 'shell'
+  ? startup : { protocolVersion: 1 })

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

@@ -2,6 +2,7 @@
 
 import { contextBridge, ipcRenderer } from 'electron'
 import { DESKTOP_IPC, type DshDesktopApi, type DesktopUpdateState } from './ipc.ts'
+import type { DesktopBackendState } from './backend-controller.ts'
 
 const api: DshDesktopApi = {
   protocolVersion: 1,
@@ -10,8 +11,19 @@ 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>,
+    subscribe(listener) {
+      const handle = (_event: Electron.IpcRendererEvent, state: DesktopBackendState): void => { listener(state) }
+      ipcRenderer.on(DESKTOP_IPC.backendState, handle)
+      return () => { ipcRenderer.off(DESKTOP_IPC.backendState, handle) }
+    },
+  },
   updates: {
     check: () => ipcRenderer.invoke(DESKTOP_IPC.updatesCheck) as Promise<DesktopUpdateState>,
     install: () => ipcRenderer.invoke(DESKTOP_IPC.updatesInstall) as Promise<void>,

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

@@ -0,0 +1,238 @@
+/** Desktop-owned host links and validation of the external plugin dependency graph. */
+
+import { createHash } from 'node:crypto'
+import { 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
+}
+
+/** Runtime identity and managed links; package preparation may still be pending. */
+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 - Desktop 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)
+  }
+}
+
+/**
+ * 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.native(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.native(profile)
+  const shared = new Map(runtime.sharedPackages.map((entry) => {
+    return [entry.name, realpathSync.native(runtimePath(root, entry.path))] as const
+  }))
+  for (const [name, path] of shared) {
+    if (packageFrom(profile, name) !== path) throw new Error(`desktop profile: missing or incorrect host link ${name}`)
+  }
+  if (activePlugins.length === 0) return
+  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.native(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.native(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)
+  }
+}

+ 194 - 308
apps/desktop/src/project-manager.ts

@@ -1,11 +1,8 @@
-/** Transactional owner of the reserved desktop profile and its private pnpm state. */
+/** In-place 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 {
-  constants,
-  copyFileSync,
-  cpSync,
   existsSync,
   fsyncSync,
   ftruncateSync,
@@ -13,41 +10,33 @@ import {
   mkdirSync,
   openSync,
   closeSync,
-  readdirSync,
   readFileSync,
-  renameSync,
-  rmSync,
+  readdirSync,
+  realpathSync,
   unlinkSync,
   writeFileSync,
   writeSync,
 } from 'node:fs'
-import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
+import { delimiter, dirname, join, 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 { removeOwnedDirectory } from './owned-directory.ts'
+import type { DesktopRelease } from './release.ts'
+import { desktopRuntimeId, readDesktopRuntime, type DesktopRuntimeDescriptor } from './runtime-tree.ts'
+import {
+  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. */
@@ -63,28 +52,19 @@ interface DesktopProjectManifest {
   }
 }
 
-/** Journaled activation step used for crash recovery. */
-interface DesktopPendingTransaction {
-  readonly schemaVersion: 1
-  readonly id: string
-  readonly stagingProfile: string
-  readonly step: 'prepared' | 'active-moved' | 'staging-activated'
-}
-
 /** Exact executables the desktop shell bundles. */
 export interface DesktopRuntimeExecutables {
   readonly node: string
   readonly pnpm: string
+  readonly dsh: string
 }
 
-/** Hooks that bind project replacement to backend lifecycle and health. */
+/** Hooks that stop the backend before profile writes and restart it after success. */
 export interface DesktopProjectHooks {
-  /** Prove the staged dependency graph while the active backend is stopped. */
-  healthCheck(projectDir: string): Promise<void>
-  /** Stop the active backend and await process exit before directory moves. */
-  beforeActivate(): Promise<void>
-  /** Start the selected active project after commit or rollback. */
-  afterActivate(): Promise<void>
+  /** Stop the active backend and await process exit before modifying its files. */
+  beforeChange(): Promise<void>
+  /** Start the modified profile after package preparation succeeds. */
+  afterChange(): Promise<void>
 }
 
 /** Supported dependency mutation. */
@@ -92,12 +72,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,19 +109,10 @@ 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
 }
 
-function isDescendant(root: string, target: string): boolean {
-  const child = relative(root, target)
-  return child !== '' && child !== '..' && !child.startsWith(`..${sep}`) && !isAbsolute(child)
-}
-
 function assertPackageName(name: string): void {
   if (!PACKAGE_NAME_PATTERN.test(name)) throw new Error(`desktop project: invalid npm package name ${JSON.stringify(name)}`)
 }
@@ -155,11 +122,11 @@ function assertVersion(version: string): void {
 }
 
 /**
- * Validate one registry package spec and return its requested package name when explicit.
+ * Validate one registry package spec and return its package name.
  * @param spec - npm registry name with an optional version or tag.
- * @returns package name, or undefined when the spec's final name is registry-resolved.
+ * @returns Requested package name.
  */
-export function packageNameFromSpec(spec: string): string | undefined {
+export function packageNameFromSpec(spec: string): string {
   if (spec === '' || spec.startsWith('-') || /[\s\\]/u.test(spec) || spec.includes('://') || spec.startsWith('file:')) {
     throw new Error(`desktop project: unsupported npm package spec ${JSON.stringify(spec)}`)
   }
@@ -179,94 +146,20 @@ export function packageNameFromSpec(spec: string): string | undefined {
   return name
 }
 
-function removeOwnedDirectory(path: string): void {
-  if (!existsSync(path)) return
-  const stat = lstatSync(path)
-  if (stat.isSymbolicLink()) {
-    unlinkSync(path)
-    return
-  }
-  if (!stat.isDirectory()) throw new Error(`desktop project: owned directory path is not a directory: ${path}`)
-  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 +178,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 +189,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 +215,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. */
+/** Desktop npm project manager with direct writes and no rollback. */
 export class DesktopProjectManager {
   private lockDescriptor: number | undefined
+  private descriptor: DesktopRuntimeDescriptor | undefined
 
   /**
    * @param paths - Electron-owned package state and reserved desktop profile paths.
@@ -338,136 +232,156 @@ export class DesktopProjectManager {
     readonly runtime: DesktopRuntimeExecutables,
   ) {}
 
-  /** Recover an interrupted directory replacement before reading the active project. */
-  recover(): void {
-    if (!existsSync(this.paths.pending)) return
-    const value = readJson(this.paths.pending)
-    if (!isRecord(value) || value.schemaVersion !== 1
-      || typeof value.id !== 'string' || typeof value.stagingProfile !== 'string'
-      || !isDescendant(this.paths.staging, value.stagingProfile)
-      || (value.step !== 'prepared' && value.step !== 'active-moved' && value.step !== 'staging-activated')) {
-      throw new Error(`desktop project: invalid activation journal ${this.paths.pending}`)
-    }
-    const pending: DesktopPendingTransaction = {
-      schemaVersion: 1,
-      id: value.id,
-      stagingProfile: value.stagingProfile,
-      step: value.step,
-    }
-    if (!existsSync(this.paths.profile) && existsSync(this.paths.rollback)) {
-      mkdirSync(dirname(this.paths.profile), { recursive: true })
-      renameSync(this.paths.rollback, this.paths.profile)
-    }
-    removeOwnedDirectory(pending.stagingProfile)
-    unlinkSync(this.paths.pending)
-  }
-
   /** Read the active desktop plugin inventory. */
   listPlugins(): readonly DesktopPluginRecord[] {
     if (!existsSync(this.paths.profile)) return []
     return pluginRecords(this.paths.profile)
   }
 
-  /** Read the exact dsh version installed in the active desktop project. */
+  /**
+   * Reinitialize the profile, deleting configuration and third-party packages without a backup.
+   * @param hooks - Stop the Host before resetting files; restart after preparation succeeds.
+   * @returns Completion of reset; the held lock and shared product data are preserved.
+   */
+  async resetConfiguration(hooks: DesktopProjectHooks): Promise<void> {
+    await this.withLock(async () => {
+      await hooks.beforeChange()
+      this.descriptor = this.readRuntime()
+      for (const entry of readdirSync(this.paths.profile, { withFileTypes: true })) {
+        const path = join(this.paths.profile, entry.name)
+        if (path === this.paths.lock) continue
+        if (entry.isDirectory()) removeOwnedDirectory(path)
+        else unlinkSync(path)
+      }
+      createPluginProfile(this.paths.profile)
+      this.prepareProfile(this.paths.profile)
+      await hooks.afterChange()
+    })
+  }
+
+  /** 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
+  }
+
+  /** 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
   }
 
-  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`)
+  /** Reject a profile whose dependency links were prepared for another runtime. */
+  assertProfileRuntime(projectDir: string): void {
+    if (existsSync(this.pendingPackages)) throw new Error('desktop project: package preparation is incomplete; retry startup')
+    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
+  /** @returns Whether application resources support profile recovery. */
+  canRecoverProfile(): boolean {
+    return this.descriptor !== undefined && existsSync(this.runtime.node) && existsSync(this.runtime.dsh)
   }
 
-  /** Install or reconcile the active project to the Electron package's exact release. */
-  async applyRelease(seedDir: string, electronVersion: string, hooks: DesktopProjectHooks): Promise<boolean> {
+  private get pendingPackages(): string { return join(this.paths.profile, 'desktop-packages-pending') }
+
+  private currentRuntime(): DesktopRuntimeDescriptor {
+    if (this.descriptor === undefined) throw new Error('desktop project: runtime metadata has not been loaded')
+    return this.descriptor
+  }
+
+  private readRuntime(): DesktopRuntimeDescriptor {
+    this.descriptor = undefined
+    return readDesktopRuntime(this.runtime.dsh)
+  }
+
+  private prepareProfile(projectDir: string): void {
+    const runtime = this.currentRuntime()
+    linkDesktopHostPackages(projectDir, this.runtime.dsh, runtime)
+    validateDesktopPluginGraph(projectDir, this.runtime.dsh, runtime, profilePluginNames(projectDir))
+  }
+
+  /** Read release metadata and reconcile its external profile without installing core packages. */
+  async applyRelease(): 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}`)
-      }
-      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)
+      const target = this.readRuntime()
+      this.descriptor = target
+      const previous = readDesktopProfileState(this.paths.profile)
+      if (!existsSync(this.pendingPackages) && previous?.runtimeId === desktopRuntimeId(target)
+        && previous.lockHash === desktopPluginLockHash(this.paths.profile)
+        && previous.links.length === target.sharedPackages.length
+        && previous.links.every(link => existsSync(link.target)
+          && existsSync(join(this.paths.profile, 'node_modules', link.name))
+          && realpathSync.native(link.target) === realpathSync.native(join(this.runtime.dsh, 'node_modules', link.name)))) {
         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'])
-        }
-        await hooks.healthCheck(stagingProfile)
-        await this.activate(stagingProfile, hooks)
-        return true
-      } catch (error) {
-        removeOwnedDirectory(stagingProfile)
-        throw error
-      }
+      if (previous === undefined) createPluginProfile(this.paths.profile)
+      await this.reconcileProfile(this.paths.profile, previous)
+      return true
     })
   }
 
-  /** Apply one exact dependency mutation through a staging project. */
+  /** Modify the current profile while its backend is stopped; failures retain partial changes. */
   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()
+      await hooks.beforeChange()
+      if (mutation.type === 'plugins-disable-all') {
+        const manifest = projectManifest(this.paths.profile)
+        writeJson(join(this.paths.profile, 'package.json'), {
+          ...manifest,
+          dsh: { ...manifest.dsh, profile: { ...manifest.dsh.profile, bundles: [...DESKTOP_PROFILE_BUNDLES] } },
+        })
+        this.prepareProfile(this.paths.profile)
+        await hooks.afterChange()
+        return
+      }
+      const previous = readDesktopProfileState(this.paths.profile)
+      const packagesChanged = mutation.type !== 'plugin-toggle'
+      if (packagesChanged) unlinkDesktopHostPackages(this.paths.profile)
       try {
-        copyMetadata(this.paths.profile, stagingProfile)
-        await this.applyMutation(stagingProfile, mutation)
-        await hooks.healthCheck(stagingProfile)
-        await this.activate(stagingProfile, hooks)
-      } catch (error) {
-        removeOwnedDirectory(stagingProfile)
-        throw error
+        await this.applyMutation(this.paths.profile, mutation)
+      } finally {
+        if (packagesChanged) linkDesktopHostPackages(this.paths.profile, this.runtime.dsh, this.currentRuntime())
       }
+      await this.reconcileProfile(this.paths.profile, previous, packagesChanged)
+      await hooks.afterChange()
     })
   }
 
-  private newStagingProfile(): string {
-    const path = join(this.paths.staging, randomUUID(), 'profile')
-    mkdirSync(path, { recursive: true, mode: 0o700 })
-    return path
+  private async reconcileProfile(projectDir: string, previous: DesktopProfileState | undefined, packagesChanged = false): Promise<void> {
+    const target = this.currentRuntime()
+    const rebuild = (!packagesChanged && existsSync(this.pendingPackages))
+      || (previous !== undefined && pluginRecords(projectDir).length > 0
+      && (previous.nodeVersion !== target.release.nodeVersion || previous.platform !== target.platform || previous.arch !== target.arch))
+    if (rebuild) {
+      writeFileSync(this.pendingPackages, '')
+      unlinkDesktopHostPackages(projectDir)
+      removeOwnedDirectory(join(projectDir, 'node_modules'))
+      await this.runPnpm(projectDir, ['install', '--frozen-lockfile', '--ignore-scripts'])
+    }
+    if (rebuild || packagesChanged) await this.finishPackageOperation(projectDir)
+    else this.prepareProfile(projectDir)
+  }
+
+  private async finishPackageOperation(projectDir: string): Promise<void> {
+    this.prepareProfile(projectDir)
+    await this.runPnpm(projectDir, ['rebuild', '--pending'])
+    this.prepareProfile(projectDir)
+    unlinkSync(this.pendingPackages)
   }
 
-  private async applyMutation(projectDir: string, mutation: DesktopProjectMutation): Promise<void> {
+  private async applyMutation(projectDir: string, mutation: Exclude<DesktopProjectMutation, { type: 'plugins-disable-all' }>): Promise<void> {
     switch (mutation.type) {
       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 +391,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,54 +414,20 @@ export class DesktopProjectManager {
           )
         }
         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,
-      step: 'prepared',
-    }
-    writeJson(this.paths.pending, pending)
-    await hooks.beforeActivate()
-    let activeMoved = false
-    try {
-      removeOwnedDirectory(this.paths.rollback)
-      mkdirSync(dirname(this.paths.rollback), { recursive: true, mode: 0o700 })
-      writeJson(this.paths.pending, { ...pending, step: 'active-moved' } satisfies DesktopPendingTransaction)
-      if (existsSync(this.paths.profile)) {
-        renameSync(this.paths.profile, this.paths.rollback)
-        activeMoved = true
-      }
-      mkdirSync(dirname(this.paths.profile), { recursive: true, mode: 0o700 })
-      writeJson(this.paths.pending, { ...pending, step: 'staging-activated' } satisfies DesktopPendingTransaction)
-      renameSync(stagingProfile, this.paths.profile)
-      await hooks.afterActivate()
-      unlinkSync(this.paths.pending)
-    } catch (error) {
-      if (existsSync(this.paths.profile)) 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)
-      throw error
-    }
-  }
-
   private async runPnpm(projectDir: string, args: readonly string[]): Promise<void> {
     const [command, ...commandArgs] = args
     if (command === undefined) throw new Error('desktop project: pnpm command is required')
@@ -558,8 +438,9 @@ 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)
     )))
+    writeFileSync(this.pendingPackages, '')
     await new Promise<void>((settle, reject) => {
       const child = spawn(this.runtime.node, [
         this.runtime.pnpm,
@@ -585,19 +466,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 +487,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 +500,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')
+      }
     })
   }
 
@@ -643,7 +520,8 @@ export class DesktopProjectManager {
   }
 
   private async withLock<T>(operation: () => Promise<T>): Promise<T> {
-    mkdirSync(this.paths.root, { recursive: true, mode: 0o700 })
+    mkdirSync(this.paths.profile, { recursive: true, mode: 0o700 })
+    if (lstatSync(this.paths.profile).isSymbolicLink()) throw new Error('desktop project: profile directory must not be a link')
     let descriptor: number
     try {
       descriptor = openSync(this.paths.lock, 'wx', 0o600)
@@ -682,10 +560,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 +571,12 @@ 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)
 }
 
 /**
@@ -721,5 +598,14 @@ export function createDevelopmentProjectMetadata(projectDir: string, release: De
   }
   writeJson(join(projectDir, 'package.json'), manifest)
   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`. */

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

@@ -0,0 +1,222 @@
+/** Relocatable, integrity-recorded production packages carried by one Desktop release. */
+
+import { createHash } from 'node:crypto'
+import { lstatSync, readdirSync, readFile, readFileSync, writeFileSync } from 'node:fs'
+import { isAbsolute, join, relative, sep } from 'node:path'
+import { promisify } from 'node:util'
+import { valid } from 'semver'
+import { DESKTOP_HOST_PACKAGE } 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
+const readRuntimeFile = promisify(readFile)
+
+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('/'))
+}
+
+function runtimeFiles(root: string): { path: string; name: string }[] {
+  const files: { path: string; name: string }[] = []
+  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()) files.push({ path, name })
+      else throw new Error(`desktop runtime: unsupported filesystem entry ${name}`)
+    }
+  }
+  visit(root)
+  return files
+}
+
+function runtimeFile(path: string, name: string, body: Buffer): DesktopRuntimeFile {
+  return { path: name, bytes: body.byteLength, sha256: createHash('sha256').update(body).digest('hex'),
+    // Windows has no portable Unix executable permission bits.
+    executable: process.platform !== 'win32' && (lstatSync(path).mode & 0o111) !== 0 }
+}
+
+/**
+ * Inventory a materialized runtime without following links or including its descriptor.
+ * @param root - Self-contained runtime directory.
+ * @returns Sorted final-file inventory; executable permissions are false on Windows.
+ */
+export function inventoryDesktopRuntime(root: string): DesktopRuntimeFile[] {
+  return runtimeFiles(root).map(({ path, name }) => runtimeFile(path, name, readFileSync(path)))
+    .sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0)
+}
+
+async function inventoryRuntimeForVerification(root: string): Promise<DesktopRuntimeFile[]> {
+  const entries = runtimeFiles(root)
+  const files: DesktopRuntimeFile[] = []
+  const remaining = entries.values()
+  let failed = false
+  const workers = Array.from({ length: Math.min(8, entries.length) }, async () => {
+    while (!failed) {
+      const next = remaining.next()
+      if (next.done) return
+      const { path, name } = next.value
+      try {
+        files.push(runtimeFile(path, name, await readRuntimeFile(path)))
+      } catch (error) {
+        failed = true
+        throw error
+      }
+    }
+  })
+  // Failure returns only after every outstanding file read has closed its descriptor.
+  const results = await Promise.allSettled(workers)
+  for (const result of results) if (result.status === 'rejected') throw result.reason
+  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
+}
+
+/**
+ * Read packaged metadata and check shared package records.
+ * @param root - Current application's runtime resources.
+ * @returns Runtime metadata whose release compatibility is verified during packaging.
+ */
+export function readDesktopRuntime(root: string): DesktopRuntimeDescriptor {
+  const value: unknown = JSON.parse(readFileSync(join(root, DESKTOP_RUNTIME_FILE), 'utf8'))
+  if (!record(value) || typeof value.platform !== 'string' || typeof value.arch !== 'string'
+    || !Array.isArray(value.sharedPackages) || !Array.isArray(value.files)) {
+    throw new Error('desktop runtime: invalid descriptor')
+  }
+  if (!record(value.release) || typeof value.release.version !== 'string'
+    || typeof value.release.nodeVersion !== 'string' || typeof value.release.pnpmVersion !== 'string') {
+    throw new Error('desktop runtime: invalid release fields')
+  }
+  const release = value.release as unknown as DesktopRelease
+  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 as DesktopRuntimeFile[]
+  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}`)
+    }
+  }
+  return { schemaVersion: value.schemaVersion as 1, release, platform: value.platform as NodeJS.Platform,
+    arch: value.arch, sharedPackages, files }
+}
+
+/**
+ * Verify every packaged runtime file against its recorded bytes and permissions at build time.
+ * @param root - Materialized runtime resources.
+ * @param electronVersion - Expected shell version.
+ * @param target - Required execution target; defaults to the current process.
+ * @returns Validated runtime descriptor.
+ */
+export async function verifyDesktopRuntime(
+  root: string, electronVersion: string, target: { platform: NodeJS.Platform; arch: string } = process,
+): Promise<DesktopRuntimeDescriptor> {
+  const descriptor = readDesktopRuntime(root)
+  // readDesktopRuntime preserves the disk schema value without validating release compatibility.
+  // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
+  if (descriptor.schemaVersion !== 1 || descriptor.platform !== target.platform || descriptor.arch !== target.arch) {
+    throw new Error('desktop runtime: invalid descriptor or incompatible platform/architecture')
+  }
+  const release = parseDesktopRelease(descriptor.release)
+  if (release.version !== electronVersion) throw new Error(`desktop runtime: ${release.version} does not match Electron ${electronVersion}`)
+  for (const entry of descriptor.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}`)
+    }
+  }
+  const actual = await inventoryRuntimeForVerification(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(descriptor.files)) !== JSON.stringify(comparable(actual))) {
+    throw new Error('desktop runtime: integrity verification failed')
+  }
+  return descriptor
+}
+
+/**
+ * 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,
-    })
-  }
-}

+ 26 - 0
apps/desktop/src/startup-document.ts

@@ -0,0 +1,26 @@
+/** Self-contained recovery document for an unavailable shell renderer or preload. */
+
+import type { DesktopLocale } from './locale.ts'
+
+/**
+ * Render escaped diagnostics without depending on application resource files.
+ * @param locale - Shell-owned translations.
+ * @param message - Failure details displayed as plain text.
+ * @param profileRecovery - Whether the initialized application can repair its profile.
+ * @returns An HTML document suitable for an isolated emergency window.
+ */
+export function startupFailureDocument(locale: DesktopLocale, message: string, profileRecovery = false): string {
+  const escape = (value: string): string => value.replaceAll('&', '&amp;').replaceAll('<', '&lt;')
+    .replaceAll('>', '&gt;').replaceAll('"', '&quot;').replaceAll("'", '&#39;')
+  return `<!doctype html><html lang="${locale.id}"><meta charset="utf-8">
+<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; form-action dsh-recovery:">
+<title>${escape(locale.messages.startupFailed)}</title>
+<style>:root{color-scheme:light dark;font-family:system-ui}body{max-width:720px;margin:10vh auto;padding:24px}pre{white-space:pre-wrap;overflow-wrap:anywhere}</style>
+<main><h1>${escape(locale.messages.startupFailed)}</h1><p>${escape(locale.messages.startupReinstallAdvice)}</p>
+${profileRecovery ? `<p>${escape(locale.messages.startupConfigurationAdvice)}</p>` : ''}
+<pre role="alert">${escape(message)}</pre>
+<form action="dsh-recovery://restart"><button>${escape(locale.messages.restartApplication)}</button></form>
+${profileRecovery ? `<form action="dsh-recovery://plugins"><button>${escape(locale.messages.disableThirdPartyPlugins)}</button></form>
+<form action="dsh-recovery://reset"><button>${escape(locale.messages.resetConfiguration)}</button></form>` : ''}
+</main></html>`
+}

+ 13 - 0
apps/desktop/src/startup-error.ts

@@ -0,0 +1,13 @@
+/** Serializable Desktop failure diagnostics. */
+
+/**
+ * Preserve nested diagnostics when sending failures to a renderer.
+ * @param error - Startup or runtime failure.
+ * @returns Serializable error state.
+ */
+export function desktopErrorState(error: unknown): { phase: 'error'; message: string } {
+  const message = error instanceof AggregateError
+    ? [error.message, ...error.errors.map(item => desktopErrorState(item).message)].join('\n')
+    : error instanceof Error ? error.message : String(error)
+  return { phase: 'error', message }
+}

+ 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'

+ 170 - 0
apps/desktop/tests/backend-controller.spec.ts

@@ -0,0 +1,170 @@
+import { describe, expect, it, vi } from 'vitest'
+import { DesktopBackendController, type DesktopBackendState } from '../src/backend-controller.ts'
+
+function deferred() {
+  let resolve!: () => void
+  let reject!: (error: Error) => void
+  const promise = new Promise<void>((accept, decline) => { resolve = accept; reject = decline })
+  return { promise, resolve, reject }
+}
+
+function fixture() {
+  const started = deferred()
+  const ready = deferred()
+  const stopping = deferred()
+  const exited = deferred()
+  const states: DesktopBackendState[] = []
+  let fail!: (error: Error) => void
+  const host = {
+    start: vi.fn(() => { started.resolve(); return ready.promise }),
+    stop: vi.fn(() => { stopping.resolve(); return exited.promise }),
+  }
+  const create = vi.fn((onFailure: (error: Error) => void) => { fail = onFailure; return host })
+  const controller = new DesktopBackendController(create, state => states.push(state))
+  return { controller, host, create, states, started, ready, stopping, exited, fail: (error: Error) => { fail(error) } }
+}
+
+describe('desktop backend controller', () => {
+  it('shares preparation and startup between concurrent retries', async () => {
+    const f = fixture()
+    const prepare = vi.fn(async () => {})
+    const first = f.controller.start(prepare)
+    expect(f.controller.start(prepare)).toBe(first)
+    await f.started.promise
+    expect(f.controller.host).toBeUndefined()
+    expect(f.states).toEqual([{ phase: 'starting' }])
+    f.ready.resolve()
+    await first
+    expect(f.controller.host).toBe(f.host)
+    await f.controller.start(prepare)
+    expect(prepare).toHaveBeenCalledTimes(1)
+    expect(f.host.start).toHaveBeenCalledTimes(1)
+    f.exited.resolve()
+    await f.controller.close()
+  })
+
+  it('waits for pending preparation on close and never spawns afterward', async () => {
+    const f = fixture()
+    const preparing = deferred()
+    const prepared = deferred()
+    const start = f.controller.start(() => { preparing.resolve(); return prepared.promise })
+    await preparing.promise
+    let closed = false
+    const close = f.controller.close().then(() => { closed = true })
+    await Promise.resolve()
+    expect(closed).toBe(false)
+    prepared.resolve()
+    await Promise.all([start, close])
+    expect(f.create).not.toHaveBeenCalled()
+    expect(f.states).toEqual([{ phase: 'starting' }])
+    await expect(f.controller.start(async () => {})).rejects.toThrow('closed')
+  })
+
+  it('stops a pending child once and waits for startup and child exit on close', async () => {
+    const f = fixture()
+    const start = f.controller.start(async () => {})
+    const rejected = expect(start).rejects.toThrow('stopped')
+    await f.started.promise
+    const close = f.controller.close()
+    expect(f.controller.close()).toBe(close)
+    await f.stopping.promise
+    let closed = false
+    void close.then(() => { closed = true })
+    f.ready.reject(new Error('stopped'))
+    await Promise.resolve()
+    expect(closed).toBe(false)
+    f.exited.resolve()
+    await Promise.all([rejected, close])
+    expect(f.host.stop).toHaveBeenCalledTimes(1)
+    expect(f.states).toEqual([{ phase: 'starting' }])
+    expect(f.controller.host).toBeUndefined()
+  })
+
+  it('publishes preparation errors and permits retry', async () => {
+    const f = fixture()
+    await expect(f.controller.start(async () => { throw new Error('invalid profile') })).rejects.toThrow('invalid profile')
+    expect(f.controller.state).toEqual({ phase: 'error', message: 'invalid profile' })
+    expect(f.create).not.toHaveBeenCalled()
+    f.ready.resolve()
+    await f.controller.start(async () => {})
+    expect(f.controller.state).toEqual({ phase: 'ready' })
+    f.exited.resolve()
+    await f.controller.close()
+  })
+
+  it('cleans up a failed startup before rejecting and displays the actual failure', async () => {
+    const f = fixture()
+    const start = f.controller.start(async () => {})
+    const rejected = expect(start).rejects.toThrow('plugin failed')
+    await f.started.promise
+    f.ready.reject(new Error('plugin failed'))
+    await f.stopping.promise
+    f.exited.resolve()
+    await rejected
+    expect(f.controller.state).toEqual({ phase: 'error', message: 'plugin failed' })
+    expect(f.host.stop).toHaveBeenCalledTimes(1)
+    await f.controller.close()
+  })
+
+  it('waits for failed ready child cleanup before preparing a retry', async () => {
+    const f = fixture()
+    f.ready.resolve()
+    await f.controller.start(async () => {})
+    f.fail(new Error('transport failed'))
+    expect(f.controller.state).toEqual({ phase: 'error', message: 'transport failed' })
+    expect(f.controller.host).toBeUndefined()
+    await f.stopping.promise
+    const prepare = vi.fn(async () => {})
+    const retry = f.controller.start(prepare)
+    await Promise.resolve()
+    expect(prepare).not.toHaveBeenCalled()
+    f.exited.resolve()
+    await retry
+    expect(prepare).toHaveBeenCalledTimes(1)
+    expect(f.create).toHaveBeenCalledTimes(2)
+    await f.controller.close()
+  })
+
+  it('does not publish ready when the child fails as readiness settles', async () => {
+    const f = fixture()
+    const start = f.controller.start(async () => {})
+    const rejected = expect(start).rejects.toThrow('immediate failure')
+    await f.started.promise
+    f.ready.resolve()
+    f.fail(new Error('immediate failure'))
+    await f.stopping.promise
+    f.exited.resolve()
+    await rejected
+    expect(f.states).toEqual([{ phase: 'starting' }, { phase: 'error', message: 'immediate failure' }])
+    await f.controller.close()
+  })
+
+  it('ignores failure callbacks caused by intentional stop and permits subsequent start', async () => {
+    const f = fixture()
+    f.ready.resolve()
+    await f.controller.start(async () => {})
+    const stop = f.controller.stop()
+    await f.stopping.promise
+    f.fail(new Error('stopped'))
+    await expect(f.controller.start(async () => {})).rejects.toThrow('stopping')
+    expect(f.controller.state).toEqual({ phase: 'starting' })
+    f.exited.resolve()
+    await stop
+    await f.controller.start(async () => {})
+    expect(f.create).toHaveBeenCalledTimes(2)
+    await f.controller.close()
+  })
+
+  it('propagates cleanup failure and prevents retry from overlapping the remaining child', async () => {
+    const f = fixture()
+    f.ready.resolve()
+    await f.controller.start(async () => {})
+    f.fail(new Error('fatal'))
+    await f.stopping.promise
+    f.exited.reject(new Error('child did not exit'))
+    await expect(f.controller.start(async () => {})).rejects.toThrow('child did not exit')
+    await expect(f.controller.start(async () => {})).rejects.toThrow('child did not exit')
+    expect(f.create).toHaveBeenCalledTimes(1)
+    await expect(f.controller.close()).rejects.toThrow('child did not exit')
+  })
+})

+ 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'))
   })
 

+ 8 - 0
apps/desktop/tests/expected/startup-en-profile.txt

@@ -0,0 +1,8 @@
+DeepSeek Harness could not start
+Choose a recovery action below. Disabling third-party plugins retains their files.
+Reset Desktop deletes all Desktop profile configuration and third-party plugins without a backup, then starts a fresh profile. Shared tasks and settings are retained.
+If application files are missing or damaged, close the application and reinstall it. Your tasks are stored separately.
+Failure details
+Close and restart
+Disable all third-party plugins and retry
+Reset Desktop and retry

+ 5 - 0
apps/desktop/tests/expected/startup-en-restart.txt

@@ -0,0 +1,5 @@
+DeepSeek Harness could not start
+Choose a recovery action below. Disabling third-party plugins retains their files.
+If application files are missing or damaged, close the application and reinstall it. Your tasks are stored separately.
+Failure details
+Close and restart

+ 8 - 0
apps/desktop/tests/expected/startup-zh-CN-profile.txt

@@ -0,0 +1,8 @@
+DeepSeek Harness 无法启动
+请选择下方的恢复操作。禁用第三方插件会保留插件文件。
+重置 Desktop 会删除桌面端的全部 profile 配置和第三方插件,不保留备份,然后重新初始化并启动。共享任务和设置会保留。
+如果应用文件缺失或损坏,请关闭应用并重新安装。任务数据存储在独立位置。
+Failure details
+关闭并重启
+禁用全部第三方插件并重试
+重置 Desktop 并重试

+ 5 - 0
apps/desktop/tests/expected/startup-zh-CN-restart.txt

@@ -0,0 +1,5 @@
+DeepSeek Harness 无法启动
+请选择下方的恢复操作。禁用第三方插件会保留插件文件。
+如果应用文件缺失或损坏,请关闭应用并重新安装。任务数据存储在独立位置。
+Failure details
+关闭并重启

+ 70 - 0
apps/desktop/tests/fixtures/installer-cleanup-smoke.nsi

@@ -0,0 +1,70 @@
+; Compile with OUTPUT_FILE and RESULT_FILE in a private test directory, then run silently.
+Unicode true
+RequestExecutionLevel user
+SilentInstall silent
+Name "Desktop installer cleanup smoke"
+OutFile "${OUTPUT_FILE}"
+!include "..\..\scripts\installer.nsh"
+
+Section
+  InitPluginsDir
+  SetOutPath "$PLUGINSDIR"
+  CreateDirectory "$PLUGINSDIR\7z-out\nested"
+  FileOpen $1 "$PLUGINSDIR\7z-out\nested\extracted-file" w
+  FileWrite $1 "remove"
+  FileClose $1
+  FileOpen $1 "$PLUGINSDIR\archive.7z" w
+  FileWrite $1 "archive sentinel"
+  FileClose $1
+  FileOpen $1 "$PLUGINSDIR\plugin.dll" w
+  FileWrite $1 "plugin sentinel"
+  FileClose $1
+  CreateDirectory "$PLUGINSDIR\old-install"
+  FileOpen $1 "$PLUGINSDIR\old-install\sentinel" w
+  FileWrite $1 "rollback sentinel"
+  FileClose $1
+
+  StrCpy $0 "register sentinel"
+  ClearErrors
+  !insertmacro customInstall
+  IfErrors failed
+  StrCmp $0 "register sentinel" 0 failed
+  StrCmp $OUTDIR $PLUGINSDIR 0 failed
+  IfFileExists "$PLUGINSDIR\7z-out\*.*" failed
+
+  FileOpen $1 "$PLUGINSDIR\archive.7z" r
+  FileRead $1 $2
+  FileClose $1
+  StrCmp $2 "archive sentinel" 0 failed
+  FileOpen $1 "$PLUGINSDIR\plugin.dll" r
+  FileRead $1 $2
+  FileClose $1
+  StrCmp $2 "plugin sentinel" 0 failed
+  FileOpen $1 "$PLUGINSDIR\old-install\sentinel" r
+  FileRead $1 $2
+  FileClose $1
+  StrCmp $2 "rollback sentinel" 0 failed
+
+  CreateDirectory "$PLUGINSDIR\7z-out"
+  SetErrors
+  !insertmacro customInstall
+  IfErrors +2
+    Goto failed
+  IfFileExists "$PLUGINSDIR\7z-out\*.*" failed
+
+  ClearErrors
+  !insertmacro customInstall
+  IfErrors failed
+  FileOpen $1 "${RESULT_FILE}" w
+  FileWrite $1 "scratch removed; archive, plugin, rollback, registers and error flags preserved"
+  FileClose $1
+  SetErrorLevel 0
+  Quit
+
+  failed:
+  FileOpen $1 "${RESULT_FILE}" w
+  FileWrite $1 "cleanup smoke failed"
+  FileClose $1
+  SetErrorLevel 1
+  Quit
+SectionEnd

+ 55 - 0
apps/desktop/tests/fixtures/installer-write-failure-smoke.nsi

@@ -0,0 +1,55 @@
+; Compile with OUTPUT_FILE, RESULT_FILE, PAYLOAD_FILE, TARGET_DIR and PLUGIN_DIR.
+; All paths must belong to a private test directory, except the NSIS plugin directory.
+; PAYLOAD_FILE contains locked.txt="new runtime" and asset.txt="new asset".
+; Before running /S, create TARGET_DIR\locked.txt="old runtime" and hold it open
+; for reading with FileShare.Read until the native process exits. asset.txt is absent.
+; Define DIRECT for direct extraction; otherwise extract to temporary files and copy.
+; Both modes retain "old runtime" and write "new asset" under that lock. The copy
+; sets errorFlag=true; direct extraction reports false despite the mixed versions.
+; Exit code 0 alone cannot establish successful extraction; inspect RESULT_FILE.
+Unicode true
+RequestExecutionLevel user
+SilentInstall silent
+Name "Desktop occupied-file extraction smoke"
+OutFile "${OUTPUT_FILE}"
+!addplugindir /x86-unicode "${PLUGIN_DIR}"
+
+Section
+  InitPluginsDir
+  SetOutPath "${TARGET_DIR}"
+  !ifdef DIRECT
+    ClearErrors
+    Nsis7z::Extract "${PAYLOAD_FILE}"
+  !else
+    SetOutPath "$PLUGINSDIR\7z-out"
+    Nsis7z::Extract "${PAYLOAD_FILE}"
+    SetOutPath "${TARGET_DIR}"
+    ClearErrors
+    CopyFiles /SILENT "$PLUGINSDIR\7z-out\*" $OUTDIR
+  !endif
+
+  StrCpy $0 "false"
+  IfErrors 0 +2
+    StrCpy $0 "true"
+  ClearErrors
+  FileOpen $1 "${RESULT_FILE}" w
+  IfErrors failed
+  FileWrite $1 "errorFlag=$0$\r$\n"
+  FileOpen $2 "${TARGET_DIR}\locked.txt" r
+  IfErrors failed
+  FileRead $2 $3
+  FileClose $2
+  FileWrite $1 "locked=$3$\r$\n"
+  FileOpen $2 "${TARGET_DIR}\asset.txt" r
+  IfErrors failed
+  FileRead $2 $3
+  FileClose $2
+  FileWrite $1 "asset=$3$\r$\n"
+  FileClose $1
+  SetErrorLevel 0
+  Quit
+
+  failed:
+  SetErrorLevel 1
+  Quit
+SectionEnd

+ 29 - 0
apps/desktop/tests/fixtures/owned-directory-smoke.mjs

@@ -0,0 +1,29 @@
+/** Built Desktop cleanup smoke; run with Electron and ELECTRON_RUN_AS_NODE=1. */
+
+import assert from 'node:assert/strict'
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, symlinkSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { removeOwnedDirectory } from '../../lib/types/owned-directory.js'
+import { inventoryDesktopRuntime } from '../../lib/types/runtime-tree.js'
+
+assert.ok(process.versions.electron, 'This regression must run under Electron')
+const root = mkdtempSync(join(tmpdir(), 'desktop-electron-cleanup-'))
+try {
+  const resources = join(root, 'resources')
+  mkdirSync(resources)
+  writeFileSync(join(resources, 'sentinel'), 'installed runtime bytes')
+  const inventory = inventoryDesktopRuntime(resources)
+  const profile = join(root, 'rollback-profile')
+  const packages = join(profile, 'node_modules', '@unknown')
+  mkdirSync(packages, { recursive: true })
+  symlinkSync(resources, join(packages, 'host-package'), process.platform === 'win32' ? 'junction' : 'dir')
+  writeFileSync(join(packages, 'private-file'), 'removed')
+  removeOwnedDirectory(profile)
+  assert.equal(existsSync(profile), false)
+  assert.deepEqual(inventoryDesktopRuntime(resources), inventory)
+  assert.equal(readFileSync(join(resources, 'sentinel'), 'utf8'), 'installed runtime bytes')
+  console.log(JSON.stringify({ electron: process.versions.electron, node: process.version, preservedLinkTarget: true }))
+} finally {
+  removeOwnedDirectory(root)
+}

+ 138 - 0
apps/desktop/tests/fixtures/runtime-payload-smoke.mjs

@@ -0,0 +1,138 @@
+/** Exercise filtered Desktop native and HTML dependencies under its bundled Node. */
+
+import assert from 'node:assert/strict'
+import { closeSync, mkdtempSync, openSync, readFileSync, readSync, writeFileSync } from 'node:fs'
+import { rm } from 'node:fs/promises'
+import { createRequire } from 'node:module'
+import { tmpdir } from 'node:os'
+import { join, resolve } from 'node:path'
+
+const runtime = process.argv[2]
+assert.ok(runtime, 'Pass the filtered resources/dsh directory')
+const root = resolve(runtime)
+const descriptor = JSON.parse(readFileSync(join(root, 'desktop-runtime.json'), 'utf8'))
+assert.equal(process.versions.node, descriptor.release.nodeVersion, 'Run with the bundled Node version')
+assert.equal(process.platform, descriptor.platform)
+assert.equal(process.arch, descriptor.arch)
+const requireRuntime = createRequire(join(root, 'package.json'))
+const scratch = mkdtempSync(join(tmpdir(), 'dsh-runtime-payload-'))
+
+/** Spawn only a fixed Node program and await the terminal's drained exit event. */
+async function checkPty() {
+  const pty = requireRuntime('node-pty')
+  const script = join(scratch, 'pty.cjs')
+  writeFileSync(script, "process.stdout.write('runtime-payload-pty-ok\\n')\n", { flag: 'wx', mode: 0o600 })
+  const env = Object.fromEntries(Object.entries(process.env).filter(([name]) => (
+    /^(?:path|systemroot|windir|comspec)$/iu.test(name)
+  )))
+  Object.assign(env, { HOME: scratch, USERPROFILE: scratch, TMP: scratch, TEMP: scratch, TMPDIR: scratch })
+  const terminal = pty.spawn(process.execPath, [script], { cwd: scratch, env, cols: 80, rows: 24 })
+  let output = ''
+  let exited = false
+  let timedOut = false
+  let exitSubscription
+  const exit = new Promise(resolveExit => {
+    exitSubscription = terminal.onExit(event => {
+      exited = true
+      resolveExit(event)
+    })
+  })
+  const dataSubscription = terminal.onData(data => { output += data })
+  let timer
+  try {
+    const deadline = new Promise((_, reject) => {
+      timer = setTimeout(() => {
+        timedOut = true
+        reject(new Error('Packaged PTY did not exit within 45 seconds'))
+      }, 45_000)
+    })
+    const result = await Promise.race([exit, deadline])
+    assert.equal(timedOut, false)
+    assert.ok(result.signal === undefined || result.signal === 0, 'PTY exited without a signal')
+    assert.equal(result.exitCode, 0)
+    assert.match(output, /runtime-payload-pty-ok/u)
+  } finally {
+    clearTimeout(timer)
+    dataSubscription.dispose()
+    try {
+      // node-pty's Windows natural-exit event closes output but leaves its ConPTY worker owned by kill().
+      if (!exited || process.platform === 'win32') terminal.kill()
+      await exit
+    } finally {
+      exitSubscription.dispose()
+    }
+  }
+}
+
+/** fs-ext implements seek on Windows through SetFilePointerEx and on POSIX through lseek. */
+function checkFsExt() {
+  const fsExt = requireRuntime('fs-ext')
+  const file = join(scratch, 'seek.txt')
+  writeFileSync(file, 'abcdef', { flag: 'wx', mode: 0o600 })
+  const fd = openSync(file, 'r')
+  try {
+    assert.equal(fsExt.seekSync(fd, 2, fsExt.constants.SEEK_SET), 2)
+    const bytes = Buffer.alloc(4)
+    assert.equal(readSync(fd, bytes, 0, bytes.length, null), 4)
+    assert.equal(bytes.toString(), 'cdef')
+  } finally {
+    closeSync(fd)
+  }
+}
+
+/** Resolve one system function through Koffi's packaged native module. */
+function checkKoffi() {
+  const koffi = requireRuntime('koffi')
+  const library = koffi.load(process.platform === 'win32' ? 'kernel32.dll' : null)
+  try {
+    const getPid = process.platform === 'win32'
+      ? library.func('uint32_t __stdcall GetCurrentProcessId(void)')
+      : library.func('int getpid(void)')
+    assert.equal(getPid(), process.pid)
+  } finally {
+    library.unload()
+  }
+}
+
+/** Encode and decode a pixel through the packaged libvips binary. */
+async function checkSharp() {
+  const sharp = requireRuntime('sharp')
+  const pixel = Buffer.from([17, 103, 231])
+  const png = await sharp(pixel, { raw: { width: 1, height: 1, channels: 3 } }).png().toBuffer()
+  const decoded = await sharp(png).raw().toBuffer({ resolveWithObject: true })
+  assert.equal(decoded.info.width, 1)
+  assert.equal(decoded.info.height, 1)
+  assert.equal(decoded.info.channels, 3)
+  assert.deepEqual(decoded.data, pixel)
+}
+
+/** Exercise Domino parsing through the HTML converter and GFM plugin used by web_fetch. */
+function checkHtml() {
+  const Turndown = requireRuntime('turndown')
+  const { gfm } = requireRuntime('@joplin/turndown-plugin-gfm')
+  const converter = new Turndown({ bulletListMarker: '-' })
+  converter.use(gfm)
+  const markdown = converter.turndown('<p>A &amp; B &copy;</p><ul><li>first</li><li>second</li></ul>'
+    + '<table><thead><tr><th>Name</th><th>Value</th></tr></thead><tbody><tr><td>x</td><td>7</td></tr></tbody></table>')
+  assert.match(markdown, /A & B ©/u)
+  assert.match(markdown, /-\s+first\n-\s+second/u)
+  assert.match(markdown, /\| Name \| Value \|/u)
+  assert.match(markdown, /\| x\s+\| 7\s+\|/u)
+}
+
+try {
+  checkFsExt()
+  checkKoffi()
+  await checkSharp()
+  checkHtml()
+  await checkPty()
+} finally {
+  // This private tree contains only fixture files; Windows may release handles after terminal exit.
+  await rm(scratch, { recursive: true, force: true, maxRetries: 20, retryDelay: 50 })
+}
+
+// Natural event-loop drain includes node-pty's worker and console-list helper teardown.
+process.once('beforeExit', () => {
+  console.log(JSON.stringify({ node: process.versions.node, platform: process.platform, arch: process.arch,
+    fsExt: true, koffi: true, sharp: true, html: true, pty: true }))
+})

+ 53 - 8
apps/desktop/tests/host-process.spec.ts

@@ -1,7 +1,7 @@
-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'
+import { afterEach, describe, expect, it, vi } from 'vitest'
 import { DesktopHostProcess } from '../src/host-process.ts'
 
 const roots: string[] = []
@@ -75,6 +75,51 @@ afterEach(() => {
 })
 
 describe('desktop host process', () => {
+  it('reports a fatal event after readiness once and stops the child', async () => {
+    const runtime = projectWithHost(`
+process.send({ type: 'ready', protocolVersion: 3, dshVersion: '1.0.0' })
+function onRequestFrame(frame) {
+  if (frame.type === 1) process.send({ type: 'fatal', message: 'plugin unavailable' })
+}
+`)
+    const failure = vi.fn()
+    const host = new DesktopHostProcess(process.execPath, runtime, runtime, undefined, process.env, failure)
+    try {
+      await host.start()
+      await expect(host.fetch(new Request('dsh-app://app/'))).rejects.toThrow('plugin unavailable')
+      await host.stop()
+      expect(failure).toHaveBeenCalledTimes(1)
+      expect(failure).toHaveBeenCalledWith(new Error('plugin unavailable'))
+    } finally { await host.stop() }
+  })
+
+  it('settles teardown when the executable cannot be spawned', async () => {
+    const runtime = projectWithHost('function onRequestFrame() {}')
+    const host = new DesktopHostProcess(join(runtime, 'missing-node'), runtime, runtime)
+    try { await expect(host.start()).rejects.toThrow() } finally { await host.stop() }
+  })
+
+  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 +143,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 +169,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 +196,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 +229,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 +247,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 +255,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)
-  })
-})

+ 79 - 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(?:/|$)', '\\.pak$'],
       },
       dmg: {
         sign: true,
@@ -64,6 +77,41 @@ describe('desktop macOS release signature', () => {
     expect(typeof config.artifactBuildCompleted).toBe('function')
   })
 
+  it('seals PAK resources with their enclosing bundle while signing executable code', async () => {
+    const { createElectronBuilderConfig } = await import('../electron-builder.config.mjs')
+    const config = createElectronBuilderConfig(RELEASE_ENVIRONMENT, 'darwin', 'arm64')
+    const ignored = (path: string): boolean => config.mac.signIgnore.some(pattern => new RegExp(pattern).test(path))
+    expect(ignored('/App.app/Contents/Frameworks/Electron.framework/Versions/A/Resources/en.lproj/locale.pak')).toBe(true)
+    expect(ignored('/App.app/Contents/Frameworks/Electron.framework/Versions/A/Resources/resources.pak')).toBe(true)
+    for (const path of [
+      '/App.app/Contents/Resources/runtime/node/node',
+      '/App.app/Contents/Resources/runtime/pnpm/addon.node',
+      '/App.app/Contents/Frameworks/Electron.framework/Versions/A/library.dylib',
+      '/App.app/Contents/Frameworks/Electron.framework',
+      '/App.app',
+    ]) expect(ignored(path)).toBe(false)
+  })
+
+  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))
+      await expect(verifyDesktopRuntime(join(destination, 'dsh'), '1.0.0')).rejects.toThrow(/ENOENT/u)
+      rmSync(destination, { recursive: true })
+      await copyFiles(matchers)
+      await expect(verifyDesktopRuntime(join(destination, 'dsh'), '1.0.0')).resolves.toMatchObject({ release: { version: '1.0.0' } })
+    } 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({
@@ -72,6 +120,29 @@ describe('desktop macOS release signature', () => {
     }, 'win32')).toThrow(/DSH_DESKTOP_WINDOWS_CER_FILE/u)
   })
 
+  it('isolates unsigned Windows artifacts and omits updater metadata without release credentials', async () => {
+    const { createElectronBuilderConfig } = await import('../electron-builder.config.mjs')
+    const config = createElectronBuilderConfig({
+      DSH_DESKTOP_APP_ID: RELEASE_ENVIRONMENT.DSH_DESKTOP_APP_ID,
+      DSH_DESKTOP_TARGET_PLATFORM: 'win32',
+      DSH_DESKTOP_UNSIGNED: '1',
+    }, 'win32', 'x64')
+    expect(portablePath(config.directories.output)).toContain('/targets/win-x64/unsigned-artifacts')
+    expect(portablePath(config.nsis.include)).toMatch(/\/scripts\/installer\.nsh$/u)
+    expect(config).toMatchObject({
+      win: { forceCodeSigning: false, signtoolOptions: { sign: undefined } },
+      publish: null,
+    })
+  })
+
+  it('rejects unsigned macOS builds and malformed signing modes', async () => {
+    const { createElectronBuilderConfig } = await import('../electron-builder.config.mjs')
+    expect(() => createElectronBuilderConfig({ ...RELEASE_ENVIRONMENT, DSH_DESKTOP_UNSIGNED: '1' }))
+      .toThrow(/unsigned builds require Windows/u)
+    expect(() => createElectronBuilderConfig({ ...RELEASE_ENVIRONMENT, DSH_DESKTOP_UNSIGNED: 'yes' }))
+      .toThrow(/must be 0 or 1/u)
+  })
+
   it('accepts the configured authority and team', () => {
     const expected = resolveMacOSSigningEnvironment(RELEASE_ENVIRONMENT)
     expect(() => {
@@ -82,7 +153,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 +161,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)
   })
 

+ 36 - 0
apps/desktop/tests/macos-signing-walk.spec.ts

@@ -0,0 +1,36 @@
+/** Exercise the installed macOS signer against Framework file and directory aliases. */
+
+import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
+import { createRequire } from 'node:module'
+import { tmpdir } from 'node:os'
+import { dirname, join } from 'node:path'
+import { expect, it } from 'vitest'
+
+const builderRequire = createRequire(createRequire(import.meta.url).resolve('app-builder-lib'))
+const { walkAsync } = builderRequire(join(dirname(builderRequire.resolve('@electron/osx-sign')), 'util.js')) as {
+  walkAsync: (path: string) => Promise<string[]>
+}
+
+// macOS Framework aliases use POSIX file and directory symlinks, unavailable on unprivileged Windows runners.
+it.skipIf(process.platform === 'win32')('signs each real Framework file once and retains nested bundle signing', async () => {
+  const root = mkdtempSync(join(tmpdir(), 'desktop-signing-walk-'))
+  try {
+    const contents = join(root, 'Contents')
+    const framework = join(contents, 'Frameworks', 'Test.framework')
+    const version = join(framework, 'Versions', 'A')
+    const resource = join(version, 'Resources', 'en.lproj', 'locale.pak')
+    const library = join(version, 'library.dylib')
+    const helper = join(contents, 'Frameworks', 'Helper.app')
+    const executable = join(helper, 'Contents', 'MacOS', 'helper')
+    for (const file of [resource, library, executable]) {
+      mkdirSync(dirname(file), { recursive: true })
+      writeFileSync(file, Buffer.from([0xcf, 0xfa, 0xed, 0xfe, 0, 0, 0, 0]))
+    }
+    symlinkSync('A', join(framework, 'Versions', 'Current'))
+    symlinkSync('Versions/Current/Resources', join(framework, 'Resources'))
+    symlinkSync('Versions/Current/library.dylib', join(framework, 'library.dylib'))
+    const files = await walkAsync(contents)
+    expect(files.sort()).toEqual([resource, library, executable, framework, helper].sort())
+    expect(new Set(files.map(file => realpathSync(file))).size).toBe(files.length)
+  } finally { rmSync(root, { recursive: true, force: true }) }
+})

+ 368 - 0
apps/desktop/tests/main-startup.spec.ts

@@ -0,0 +1,368 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { join } from 'node:path'
+import { DESKTOP_IPC } from '../src/ipc.ts'
+
+const harness = await vi.hoisted(async () => {
+  const { EventEmitter } = await import('node:events')
+  function deferred() {
+    let resolve!: () => void
+    let reject!: (error: Error) => void
+    const promise = new Promise<void>((accept, decline) => { resolve = accept; reject = decline })
+    return { promise, resolve, reject }
+  }
+  const windows: FakeWindow[] = []
+  const hosts: FakeHost[] = []
+  const handlers = new Map<string, (event: { senderFrame: { url: string } }) => unknown>()
+  let pluginsEnabled = false
+  let preparing = deferred()
+  let prepared = deferred()
+  let hostStarted = deferred()
+  let navigated = deferred()
+  let errorPublished = deferred()
+  let quitCompleted = deferred()
+  class FakeWindow extends EventEmitter {
+    destroyed = false
+    readonly urls: string[] = []
+    readonly webContents = Object.assign(new EventEmitter(), {
+      setWindowOpenHandler: vi.fn(),
+      openDevTools: vi.fn(),
+      getURL: () => this.urls.at(-1) ?? '',
+      send: vi.fn((channel: string, state: { phase?: string }) => {
+        if (channel === 'dsh-desktop:backend-state' && state.phase === 'error') errorPublished.resolve()
+      }),
+    })
+    readonly show = vi.fn()
+    readonly focus = vi.fn()
+    readonly restore = vi.fn()
+    constructor(readonly options: { show: boolean }) { super(); windows.push(this) }
+    isDestroyed() { return this.destroyed }
+    isMinimized() { return false }
+    async loadURL(url: string) {
+      this.urls.push(url)
+      if (url === 'dsh-app://app/index.html') navigated.resolve()
+    }
+    static getAllWindows() { return windows.filter(window => !window.destroyed) }
+    close() { this.destroyed = true; this.emit('closed') }
+  }
+  class FakeHost {
+    readonly ready = deferred()
+    readonly exited = deferred()
+    readonly stopping = deferred()
+    readonly start = vi.fn(() => { hostStarted.resolve(); return this.ready.promise })
+    readonly stop = vi.fn(() => {
+      this.stopping.resolve()
+      this.ready.reject(new Error('child stopped'))
+      return this.exited.promise
+    })
+    constructor(readonly node: string, readonly runtime: string, readonly profile: string) { hosts.push(this) }
+  }
+  const app = Object.assign(new EventEmitter(), {
+    isPackaged: true,
+    name: 'Desktop test',
+    whenReady: () => Promise.resolve(),
+    getLocale: () => 'en-US',
+    getVersion: () => '1.0.0',
+    getAppPath: () => 'desktop-test-app',
+    requestSingleInstanceLock: () => true,
+    exit: vi.fn(),
+    relaunch: vi.fn(),
+    quit: vi.fn(() => {
+      const event = { preventDefault: vi.fn() }
+      app.emit('before-quit', event)
+      if (event.preventDefault.mock.calls.length === 0) quitCompleted.resolve()
+    }),
+  })
+  return {
+    windows, hosts, handlers, app, FakeWindow, FakeHost,
+    dialog: { showErrorBox: vi.fn(), showMessageBox: vi.fn() },
+    applyRelease: vi.fn(() => { preparing.resolve(); return prepared.promise }),
+    assertProfileRuntime: vi.fn(),
+    canRecoverProfile: vi.fn(() => true),
+    get preparing() { return preparing }, get prepared() { return prepared },
+    get hostStarted() { return hostStarted }, get navigated() { return navigated },
+    get errorPublished() { return errorPublished }, get quitCompleted() { return quitCompleted },
+    nextHostStart() { hostStarted = deferred(); return hostStarted.promise },
+    get pluginsEnabled() { return pluginsEnabled },
+    set pluginsEnabled(value: boolean) { pluginsEnabled = value },
+    reset() {
+      windows.length = 0; hosts.length = 0; handlers.clear(); app.removeAllListeners()
+      app.isPackaged = true
+      pluginsEnabled = false
+      preparing = deferred(); prepared = deferred(); hostStarted = deferred()
+      navigated = deferred(); errorPublished = deferred(); quitCompleted = deferred()
+    },
+  }
+})
+
+vi.mock('electron', () => ({
+  app: harness.app,
+  BrowserWindow: harness.FakeWindow,
+  dialog: harness.dialog,
+  ipcMain: {
+    handle: (channel: string, handler: (event: { senderFrame: { url: string } }) => unknown) => { harness.handlers.set(channel, handler) },
+  },
+  Menu: { setApplicationMenu: vi.fn(), buildFromTemplate: vi.fn() },
+  protocol: { registerSchemesAsPrivileged: vi.fn(), handle: vi.fn() },
+}))
+vi.mock('../src/paths.ts', () => ({ resolveDesktopPaths: () => ({ profile: 'desktop-test-profile' }) }))
+vi.mock('../src/project-manager.ts', () => ({
+  DesktopProjectManager: class {
+    readonly applyRelease = harness.applyRelease
+    readonly assertProfileRuntime = harness.assertProfileRuntime
+    canRecoverProfile = harness.canRecoverProfile
+    async mutate(_mutation: unknown, hooks: { beforeChange(): Promise<void>; afterChange(): Promise<void> }) {
+      await hooks.beforeChange()
+      harness.pluginsEnabled = false
+      await hooks.afterChange()
+    }
+    async resetConfiguration(hooks: { beforeChange(): Promise<void>; afterChange(): Promise<void> }) {
+      await this.mutate(undefined, hooks)
+    }
+  },
+}))
+vi.mock('../src/host-process.ts', () => ({ DesktopHostProcess: harness.FakeHost }))
+vi.mock('../src/update-coordinator.ts', () => ({ DesktopUpdateCoordinator: vi.fn() }))
+
+function invoke(channel: string): unknown {
+  const handler = harness.handlers.get(channel)
+  if (handler === undefined) throw new Error(`missing handler ${channel}`)
+  return handler({ senderFrame: { url: 'dsh-app://shell/startup.html' } })
+}
+
+beforeEach(() => {
+  vi.resetModules()
+  vi.clearAllMocks()
+  vi.useFakeTimers()
+  harness.reset()
+  vi.stubEnv('DSH_DESKTOP_NODE_BINARY', 'test-node')
+  vi.stubEnv('DSH_DESKTOP_PNPM_ENTRY', 'test-pnpm')
+  vi.stubEnv('DSH_DESKTOP_DSH_DIR', 'test-runtime')
+  vi.stubGlobal('process', { ...process, resourcesPath: 'desktop-test-resources' })
+  vi.stubEnv('DSH_DESKTOP_HOST_INSPECT_PORT', undefined)
+})
+
+afterEach(async () => {
+  harness.prepared.resolve()
+  for (const host of harness.hosts) { host.ready.resolve(); host.exited.resolve() }
+  harness.app.quit()
+  await harness.quitCompleted.promise
+  vi.restoreAllMocks()
+  harness.canRecoverProfile.mockReturnValue(true)
+  vi.clearAllTimers()
+  vi.useRealTimers()
+  vi.unstubAllEnvs()
+  vi.unstubAllGlobals()
+})
+
+describe('desktop main startup', () => {
+  it('exits with a diagnostic when both initialization and emergency navigation fail', async () => {
+    const exited = Promise.withResolvers<undefined>()
+    vi.spyOn(harness.app, 'getLocale').mockImplementationOnce(() => { throw new Error('locale unavailable') })
+    vi.spyOn(harness.FakeWindow.prototype, 'loadURL').mockRejectedValueOnce(new Error('emergency navigation failed'))
+    vi.spyOn(console, 'error').mockImplementation(() => {})
+    harness.app.exit.mockImplementationOnce(() => { exited.resolve(undefined) })
+    await import('../src/main.ts')
+    await exited.promise
+    expect(harness.app.exit).toHaveBeenCalledWith(1)
+    expect(console.error).toHaveBeenCalledWith(expect.objectContaining({ message: 'emergency navigation failed' }))
+  })
+
+  it('withholds profile recovery after application resources fail to load', async () => {
+    harness.canRecoverProfile.mockReturnValue(false)
+    await import('../src/main.ts')
+    await harness.preparing.promise
+    harness.prepared.reject(new Error('runtime resources missing'))
+    await harness.errorPublished.promise
+    expect(invoke(DESKTOP_IPC.backendStatus)).toMatchObject({ phase: 'error', profileRecovery: false })
+    const window = harness.windows[0]!
+    window.webContents.emit('preload-error', {}, 'preload-app.cjs', new Error('preload unavailable'))
+    const html = decodeURIComponent(window.urls.at(-1)!)
+    expect(html).toContain('dsh-recovery://restart')
+    expect(html).not.toContain('dsh-recovery://reset')
+    expect(html).not.toContain('dsh-recovery://plugins')
+  })
+
+  it('reloads a crashed startup renderer in the same window', async () => {
+    await import('../src/main.ts')
+    await harness.preparing.promise
+    const window = harness.windows[0]!
+    window.webContents.emit('render-process-gone', {}, { reason: 'crashed' })
+    await harness.errorPublished.promise
+    expect(window.urls).toEqual(['dsh-app://shell/startup.html', 'dsh-app://shell/startup.html'])
+    expect(invoke(DESKTOP_IPC.backendStatus)).toMatchObject({ phase: 'error', message: 'Desktop renderer exited: crashed' })
+  })
+
+  it.each(['plugins', 'reset'])('runs %s recovery from a document with a broken preload', async (action) => {
+    await import('../src/main.ts')
+    await harness.preparing.promise
+    const window = harness.windows[0]!
+    window.webContents.emit('preload-error', {}, 'preload-app.cjs', new Error('preload unavailable'))
+    harness.prepared.resolve()
+    await harness.hostStarted.promise
+    harness.hosts[0]!.ready.resolve()
+    await Promise.resolve(invoke(DESKTOP_IPC.backendRetry))
+    const started = harness.nextHostStart()
+    const event = { preventDefault: vi.fn() }
+    window.webContents.emit('will-navigate', event, `dsh-recovery://${action}/?`)
+    await harness.hosts[0]!.stopping.promise
+    harness.hosts[0]!.exited.resolve()
+    await started
+    harness.hosts[1]!.ready.resolve()
+    await harness.navigated.promise
+    expect(event.preventDefault).toHaveBeenCalled()
+    expect(window.urls.at(-1)).toBe('dsh-app://app/index.html')
+  })
+
+  it('allows a full profile reset for an unclassified startup failure', async () => {
+    await import('../src/main.ts')
+    await harness.preparing.promise
+    harness.prepared.resolve()
+    await harness.hostStarted.promise
+    harness.hosts[0]!.exited.resolve()
+    harness.hosts[0]!.ready.reject(new Error('Unknown startup failure'))
+    await harness.errorPublished.promise
+    const started = harness.nextHostStart()
+    const reset = Promise.resolve(invoke(DESKTOP_IPC.configurationReset))
+    await started
+    harness.hosts[1]!.ready.resolve()
+    await reset
+    expect(invoke(DESKTOP_IPC.backendStatus)).toEqual({ phase: 'ready' })
+  })
+
+  it('keeps a self-contained reinstall document in the main window after preload failure', async () => {
+    await import('../src/main.ts')
+    await harness.preparing.promise
+    const window = harness.windows[0]!
+    window.webContents.emit('preload-error', {}, 'preload-app.cjs', new Error('preload unavailable'))
+    expect(window.urls.at(-1)).toContain('data:text/html')
+    expect(decodeURIComponent(window.urls.at(-1)!)).toContain('preload unavailable')
+    harness.prepared.resolve()
+    await harness.hostStarted.promise
+    harness.hosts[0]!.ready.resolve()
+    await Promise.resolve(invoke(DESKTOP_IPC.backendRetry))
+    expect(harness.windows).toHaveLength(1)
+    expect(window.urls.at(-1)).toContain('data:text/html')
+    expect(harness.dialog.showErrorBox).not.toHaveBeenCalled()
+  })
+
+  it('offers plugin recovery and disables plugins before restarting in the same window', async () => {
+    harness.pluginsEnabled = true
+    await import('../src/main.ts')
+    await harness.preparing.promise
+    harness.prepared.resolve()
+    await harness.hostStarted.promise
+    harness.hosts[0]!.exited.resolve()
+    harness.hosts[0]!.ready.reject(new Error('Plugin initialization failed'))
+    await harness.errorPublished.promise
+    expect(invoke(DESKTOP_IPC.backendStatus)).toMatchObject({ phase: 'error', profileRecovery: true })
+    const nextStarted = harness.nextHostStart()
+    const recovery = Promise.resolve(invoke(DESKTOP_IPC.pluginsDisableAll))
+    await nextStarted
+    expect(harness.pluginsEnabled).toBe(false)
+    harness.hosts[1]!.ready.resolve()
+    await recovery
+    expect(harness.windows).toHaveLength(1)
+    expect(invoke(DESKTOP_IPC.backendStatus)).toEqual({ phase: 'ready' })
+  })
+
+  it('waits for Host exit before relaunching the application', async () => {
+    await import('../src/main.ts')
+    await harness.preparing.promise
+    harness.prepared.resolve()
+    await harness.hostStarted.promise
+    harness.hosts[0]!.ready.resolve()
+    await harness.navigated.promise
+    const restart = Promise.resolve(invoke(DESKTOP_IPC.applicationRestart))
+    await harness.hosts[0]!.stopping.promise
+    expect(harness.app.relaunch).not.toHaveBeenCalled()
+    harness.hosts[0]!.exited.resolve()
+    await restart
+    expect(harness.app.relaunch).toHaveBeenCalledOnce()
+  })
+
+  it('shows the loading window before profile preparation and starts one actual Host', async () => {
+    await import('../src/main.ts')
+    await harness.preparing.promise
+    expect(harness.windows).toHaveLength(1)
+    const window = harness.windows[0]!
+    expect(window.options.show).toBe(true)
+    expect(window.urls).toEqual(['dsh-app://shell/startup.html'])
+    expect(harness.hosts).toHaveLength(0)
+    const retry = invoke(DESKTOP_IPC.backendRetry)
+    const secondRetry = invoke(DESKTOP_IPC.backendRetry)
+    harness.prepared.resolve()
+    await harness.hostStarted.promise
+    expect(harness.hosts).toHaveLength(1)
+    expect(window.urls).toEqual(['dsh-app://shell/startup.html'])
+    harness.hosts[0]!.ready.resolve()
+    await Promise.all([retry, secondRetry, harness.navigated.promise])
+    expect(harness.applyRelease).toHaveBeenCalledTimes(1)
+    expect(harness.assertProfileRuntime).toHaveBeenCalledWith('desktop-test-profile')
+    expect(harness.hosts[0]).toMatchObject({
+      node: join('desktop-test-resources', 'runtime', 'node', process.platform === 'win32' ? 'node.exe' : 'node'),
+      runtime: join('desktop-test-resources', 'dsh'),
+      profile: 'desktop-test-profile',
+    })
+    expect(harness.hosts[0]!.start).toHaveBeenCalledTimes(1)
+    expect(harness.windows).toHaveLength(1)
+    expect(window.urls).toEqual(['dsh-app://shell/startup.html', 'dsh-app://app/index.html'])
+    expect(invoke(DESKTOP_IPC.backendStatus)).toEqual({ phase: 'ready' })
+  })
+
+  it('starts the unpackaged Host from the application development directory', async () => {
+    harness.app.isPackaged = false
+    await import('../src/main.ts')
+    await harness.hostStarted.promise
+    const project = join(harness.app.getAppPath(), '.desktop-build', 'development', 'project')
+    expect(harness.hosts[0]).toMatchObject({ node: 'test-node', runtime: project, profile: project })
+    expect(harness.applyRelease).not.toHaveBeenCalled()
+    expect(harness.assertProfileRuntime).not.toHaveBeenCalled()
+    harness.hosts[0]!.ready.resolve()
+    await harness.navigated.promise
+    expect(harness.dialog.showErrorBox).not.toHaveBeenCalled()
+  })
+
+  it('keeps startup errors and a successful retry in the same window', async () => {
+    await import('../src/main.ts')
+    await harness.preparing.promise
+    harness.prepared.resolve()
+    await harness.hostStarted.promise
+    const first = harness.hosts[0]!
+    const failedRetry = expect(Promise.resolve(invoke(DESKTOP_IPC.backendRetry))).rejects.toThrow('plugin composition failed')
+    first.exited.resolve()
+    first.ready.reject(new Error('plugin composition failed'))
+    await harness.errorPublished.promise
+    await failedRetry
+    expect(invoke(DESKTOP_IPC.backendStatus)).toEqual({ phase: 'error', message: 'plugin composition failed', profileRecovery: true })
+    expect(harness.windows[0]!.urls).toEqual(['dsh-app://shell/startup.html'])
+    const nextStarted = harness.nextHostStart()
+    const retry = Promise.resolve(invoke(DESKTOP_IPC.backendRetry))
+    await nextStarted
+    expect(harness.hosts).toHaveLength(2)
+    harness.hosts[1]!.ready.resolve()
+    await retry
+    expect(harness.windows).toHaveLength(1)
+    expect(harness.windows[0]!.urls.at(-1)).toBe('dsh-app://app/index.html')
+    expect(harness.dialog.showErrorBox).not.toHaveBeenCalled()
+  })
+
+  it('waits for a pending child to exit on quit without late window navigation', async () => {
+    await import('../src/main.ts')
+    await harness.preparing.promise
+    harness.prepared.resolve()
+    await harness.hostStarted.promise
+    const window = harness.windows[0]!
+    const host = harness.hosts[0]!
+    host.stop.mockImplementation(() => { host.stopping.resolve(); return host.exited.promise })
+    window.close()
+    harness.app.quit()
+    await host.stopping.promise
+    expect(harness.app.quit).toHaveBeenCalledTimes(1)
+    host.ready.resolve()
+    host.exited.resolve()
+    await harness.quitCompleted.promise
+    expect(host.stop).toHaveBeenCalledTimes(1)
+    expect(window.urls).toEqual(['dsh-app://shell/startup.html'])
+    expect(harness.windows).toHaveLength(1)
+  })
+})

+ 53 - 0
apps/desktop/tests/owned-directory.spec.ts

@@ -0,0 +1,53 @@
+import { existsSync, lstatSync, mkdirSync, 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 { removeOwnedDirectory } from '../src/owned-directory.ts'
+
+const roots: string[] = []
+function fixture(): string {
+  const root = mkdtempSync(join(tmpdir(), 'desktop-owned-directory-'))
+  roots.push(root)
+  return root
+}
+
+afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) })
+
+it('removes nested files and directories while preserving unknown directory-link targets', () => {
+  const root = fixture()
+  const target = join(root, 'target')
+  mkdirSync(target)
+  writeFileSync(join(target, 'sentinel'), 'preserved')
+  const owned = join(root, 'owned')
+  const nested = join(owned, 'node_modules', '@unknown', 'private')
+  mkdirSync(nested, { recursive: true })
+  writeFileSync(join(nested, 'file'), 'remove')
+  symlinkSync(target, join(nested, 'link'), process.platform === 'win32' ? 'junction' : 'dir')
+  symlinkSync(join(root, 'missing-target'), join(owned, 'broken'), process.platform === 'win32' ? 'junction' : 'dir')
+  removeOwnedDirectory(owned)
+  expect(existsSync(owned)).toBe(false)
+  expect(readFileSync(join(target, 'sentinel'), 'utf8')).toBe('preserved')
+})
+
+it.each([false, true])('unlinks a root directory link with missing target: %s', (missing) => {
+  const root = fixture()
+  const target = join(root, 'target')
+  if (!missing) {
+    mkdirSync(target)
+    writeFileSync(join(target, 'sentinel'), 'preserved')
+  }
+  const link = join(root, 'link')
+  symlinkSync(target, link, process.platform === 'win32' ? 'junction' : 'dir')
+  removeOwnedDirectory(link)
+  expect(lstatSync(link, { throwIfNoEntry: false })).toBeUndefined()
+  if (!missing) expect(readFileSync(join(target, 'sentinel'), 'utf8')).toBe('preserved')
+})
+
+it('ignores a missing root and refuses to delete a regular-file root', () => {
+  const root = fixture()
+  expect(() => { removeOwnedDirectory(join(root, 'missing')) }).not.toThrow()
+  const file = join(root, 'file')
+  writeFileSync(file, 'preserved')
+  expect(() => { removeOwnedDirectory(file) }).toThrow(/not a directory/u)
+  expect(readFileSync(file, 'utf8')).toBe('preserved')
+})

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

@@ -1,6 +1,7 @@
 import { describe, expect, it } from 'vitest'
 import {
   desktopElectronBuilderArguments,
+  desktopElectronBuilderEnvironment,
   parseDesktopPackageInvocation,
   resolveDesktopPackageTarget,
   withoutDesktopUploadCredentials,
@@ -56,7 +57,46 @@ describe('desktop package target', () => {
     expect(desktopElectronBuilderArguments(target, true)).toContain('--dir')
   })
 
-  it('keeps Windows signing fields out of build and seed preparation subprocesses', () => {
+  it('accepts unsigned Windows artifacts and rejects other targets or preparation-only use', () => {
+    expect(parseDesktopPackageInvocation(['win-x64', '--unsigned'], 'win32', 'x64').unsigned).toBe(true)
+    expect(parseDesktopPackageInvocation(['win-x64'], 'win32', 'x64').unsigned).toBe(false)
+    expect(parseDesktopPackageInvocation(['--unsigned', '--dir'], 'win32', 'x64')).toMatchObject({
+      unsigned: true, directory: true,
+    })
+    expect(() => parseDesktopPackageInvocation(['mac-arm64', '--unsigned'], 'darwin', 'arm64'))
+      .toThrow(/requires win-x64/u)
+    expect(() => parseDesktopPackageInvocation(['--unsigned', '--prepare-only'], 'win32', 'x64'))
+      .toThrow(/cannot use --prepare-only/u)
+  })
+
+  it('removes ambient certificate inputs for unsigned builds and overrides an inherited signing mode', () => {
+    const environment = {
+      DSH_DESKTOP_APP_ID: 'com.example.desktop',
+      DSH_DESKTOP_WINDOWS_TOKEN_PIN: 'token-secret',
+      CSC_LINK: 'private.pfx',
+      CSC_KEY_PASSWORD: 'secret',
+      WIN_CSC_LINK: 'windows.pfx',
+      CSC_IDENTITY_AUTO_DISCOVERY: 'true',
+      DSH_DESKTOP_UNSIGNED: '1',
+    }
+    expect(desktopElectronBuilderEnvironment(environment, true)).toEqual({
+      DSH_DESKTOP_APP_ID: 'com.example.desktop',
+      CSC_IDENTITY_AUTO_DISCOVERY: 'false',
+      DSH_DESKTOP_UNSIGNED: '1',
+    })
+    expect(desktopElectronBuilderEnvironment(environment, false)).toEqual({ ...environment, DSH_DESKTOP_UNSIGNED: '0' })
+  })
+
+  it.each([false, true])('pins the Windows archive filter for the NSIS decoder (unsigned: %s)', (unsigned) => {
+    expect(desktopElectronBuilderEnvironment({
+      DSH_DESKTOP_TARGET_PLATFORM: 'win32', ELECTRON_BUILDER_7Z_FILTER: 'ARM64',
+    }, unsigned).ELECTRON_BUILDER_7Z_FILTER).toBe('BCJ')
+    expect(desktopElectronBuilderEnvironment({
+      DSH_DESKTOP_TARGET_PLATFORM: 'darwin', ELECTRON_BUILDER_7Z_FILTER: 'ARM',
+    }, unsigned).ELECTRON_BUILDER_7Z_FILTER).toBe('ARM')
+  })
+
+  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 ? { phase: 'ready' } : { phase: 'error', message: '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 = { beforeChange: async () => {}, afterChange: async () => {} }
+    await manager.applyRelease()
+    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)

+ 39 - 0
apps/desktop/tests/preload-app.spec.ts

@@ -0,0 +1,39 @@
+import { afterEach, expect, it, vi } from 'vitest'
+import { DESKTOP_IPC, type DshDesktopStartupApi } from '../src/ipc.ts'
+
+const electron = vi.hoisted(() => ({
+  contextBridge: { exposeInMainWorld: vi.fn() },
+  ipcRenderer: { invoke: vi.fn(), on: vi.fn(), off: vi.fn() },
+}))
+vi.mock('electron', () => electron)
+
+afterEach(() => { vi.unstubAllGlobals(); vi.clearAllMocks(); vi.resetModules() })
+
+it.each(['dsh-app://app/index.html', 'https://shell/startup.html'])('exposes only the carrier marker to %s', async (url) => {
+  vi.stubGlobal('location', new URL(url))
+  await import('../src/preload-app.ts')
+  expect(electron.contextBridge.exposeInMainWorld).toHaveBeenCalledWith('dshDesktop', { protocolVersion: 1 })
+})
+
+it('provides startup controls and a removable state subscription to shell documents', async () => {
+  vi.stubGlobal('location', new URL('dsh-app://shell/startup.html'))
+  await import('../src/preload-app.ts')
+  const api = electron.contextBridge.exposeInMainWorld.mock.calls[0]?.[1] as DshDesktopStartupApi
+  await api.locale()
+  await api.backend.status()
+  await api.disablePlugins()
+  await api.resetConfiguration()
+  await api.restart()
+  expect(electron.ipcRenderer.invoke.mock.calls).toEqual([
+    [DESKTOP_IPC.localeGet], [DESKTOP_IPC.backendStatus],
+    [DESKTOP_IPC.pluginsDisableAll], [DESKTOP_IPC.configurationReset], [DESKTOP_IPC.applicationRestart],
+  ])
+  const listener = vi.fn()
+  const dispose = api.backend.subscribe(listener)
+  const handler = electron.ipcRenderer.on.mock.calls[0]?.[1] as (event: unknown, state: unknown) => void
+  handler({}, { phase: 'error', message: 'startup failed' })
+  expect(listener).toHaveBeenCalledWith({ phase: 'error', message: 'startup failed' })
+  dispose()
+  expect(electron.ipcRenderer.off).toHaveBeenCalledWith(DESKTOP_IPC.backendState, handler)
+  expect(api).not.toHaveProperty('plugins')
+})

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

@@ -0,0 +1,78 @@
+import { execFileSync } from 'node:child_process'
+import { mkdtempSync, 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 { 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('removes broken owned links without following them', () => {
+  const { root, profile } = fixture()
+  writePackage(join(profile, 'node_modules'), 'plugin')
+  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)
+})

+ 341 - 350
apps/desktop/tests/project-manager.spec.ts

@@ -1,168 +1,65 @@
-import { createHash } from 'node:crypto'
-import { existsSync, mkdtempSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, unlinkSync, realpathSync, writeFileSync } from 'node:fs'
 import { tmpdir } from 'node:os'
-import { dirname, join, relative, sep } from 'node:path'
+import { 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 { runtimeFixture } from './runtime-fixture.ts'
 
 const roots: string[] = []
 const releaseWorkers: Array<() => Promise<void>> = []
-
 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 { beforeChange: async () => {}, afterChange: 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(async () => {
   const cleanups = releaseWorkers.splice(0)
   const directories = roots.splice(0)
@@ -172,239 +69,333 @@ afterEach(async () => {
   if (failures.length > 0) throw new AggregateError(failures, 'desktop worker cleanup failed')
 })
 
-describe('desktop package policy', () => {
-  it('accepts registry package specs but rejects alternate sources and flags', () => {
+describe('desktop external plugin profile', () => {
+  it('reuses plugin files without scanning manifests and can disable or reset them', async () => {
+    const { manager } = setup()
+    await manager.applyRelease()
+    await manager.mutate({ type: 'plugin-add', spec: 'plugin@1.0.0' }, hooks())
+    const manifest = join(manager.paths.profile, 'node_modules/plugin/package.json')
+    writeFileSync(manifest, '{broken')
+    await expect(manager.applyRelease()).resolves.toBe(false)
+    await manager.mutate({ type: 'plugins-disable-all' }, hooks())
+    await expect(manager.applyRelease()).resolves.toBe(false)
+    expect(readFileSync(manifest, 'utf8')).toBe('{broken')
+    await manager.resetConfiguration(hooks())
+    expect(existsSync(manifest)).toBe(false)
+    await expect(manager.applyRelease()).resolves.toBe(false)
+  })
+
+  it('disables every third-party bundle without reading a broken plugin patch declaration', async () => {
+    const { root, manager } = setup()
+    await manager.applyRelease()
+    await manager.mutate({ type: 'plugin-add', spec: 'plugin@1.0.0' }, hooks())
+    const patch = join(manager.paths.profile, 'node_modules/plugin/bundle.yml')
+    unlinkSync(patch)
+    await manager.mutate({ type: 'plugins-disable-all' }, hooks({ afterChange: async () => {
+      expect((JSON.parse(readFileSync(join(manager.paths.profile, 'package.json'), 'utf8')) as {
+        dsh: { profile: { bundles: string[] } }
+      }).dsh.profile.bundles).not.toContain('plugin')
+    } }))
+    expect((JSON.parse(readFileSync(join(manager.paths.profile, 'package.json'), 'utf8')) as {
+      dsh: { profile: { bundles: string[] } }
+    }).dsh.profile.bundles).not.toContain('plugin')
+    expect(existsSync(join(manager.paths.profile, 'node_modules/plugin/package.json'))).toBe(true)
+    expect(calls(root)).toHaveLength(2)
+    await expect(manager.applyRelease()).resolves.toBe(false)
+  })
+
+  it('resets the entire profile without backups while retaining its lock and shared data', async () => {
+    const { root, manager } = setup()
+    await manager.applyRelease()
+    await manager.mutate({ type: 'plugin-add', spec: 'plugin@1.0.0' }, hooks())
+    const profile = manager.paths.profile
+    expect(manager.paths.lock).toBe(join(profile, 'lock'))
+    const task = join(root, '.dsh', 'task-sentinel')
+    const homeEnvironment = join(root, '.dsh', '.env')
+    writeFileSync(homeEnvironment, 'HOME_SETTING=retained')
+    writeFileSync(task, 'retained task')
+    writeFileSync(join(profile, 'desktop-runtime-state.json'), '{broken')
+    writeFileSync(join(profile, 'cordis.patch.yml'), ': broken')
+    writeFileSync(join(profile, '.env'), 'NODE_OPTIONS=--bad')
+    mkdirSync(join(profile, '.extra'))
+    writeFileSync(join(profile, '.extra', 'custom-file'), 'remove')
+    const shared = join(root, 'shared-data')
+    mkdirSync(shared)
+    writeFileSync(join(shared, 'sentinel'), 'preserve')
+    symlinkSync(shared, join(profile, 'external-link'), process.platform === 'win32' ? 'junction' : 'dir')
+    await expect(manager.applyRelease()).rejects.toThrow()
+    await manager.resetConfiguration(hooks({
+      beforeChange: async () => { expect(readFileSync(join(profile, 'cordis.patch.yml'), 'utf8')).toBe(': broken') },
+      afterChange: async () => {
+        manager.assertProfileRuntime(profile)
+        expect(readFileSync(manager.paths.lock, 'utf8').trim()).toBe(String(process.pid))
+        await expect(manager.applyRelease()).rejects.toThrow('another package transaction is active')
+      },
+    }))
+    expect(manager.listPlugins()).toEqual([])
+    expect(existsSync(join(profile, 'node_modules/plugin'))).toBe(false)
+    expect(existsSync(join(profile, 'cordis.patch.yml'))).toBe(false)
+    expect(existsSync(join(profile, '.env'))).toBe(false)
+    expect(existsSync(join(profile, '.extra'))).toBe(false)
+    expect(existsSync(join(profile, 'external-link'))).toBe(false)
+    expect(readFileSync(join(shared, 'sentinel'), 'utf8')).toBe('preserve')
+    expect(readFileSync(task, 'utf8')).toBe('retained task')
+    expect(readFileSync(homeEnvironment, 'utf8')).toBe('HOME_SETTING=retained')
+    expect(readdirSync(profile).some(name => name.includes('backup'))).toBe(false)
+    expect(calls(root)).toHaveLength(2)
+    await expect(manager.applyRelease()).resolves.toBe(false)
+    expect(existsSync(homeEnvironment)).toBe(true)
+  })
+
+  it('reports damaged application metadata as a reinstall failure', async () => {
+    const { manager } = setup()
+    writeFileSync(join(manager.runtime.dsh, 'desktop-runtime.json'), '{broken')
+    await expect(manager.applyRelease()).rejects.toThrow()
+    expect(manager.canRecoverProfile()).toBe(false)
+  })
+
+  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)
+    for (const spec of ['file:../plugin', '--registry=evil', 'https://example.test/plugin.tgz']) {
+      expect(() => packageNameFromSpec(spec)).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)
+  it('retries installation after an interrupted runtime rebuild removed plugin files', async () => {
+    const { root, manager } = setup()
+    await manager.applyRelease()
+    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 failing = join(root, 'fail-install.mjs')
+    writeFileSync(failing, 'process.exitCode = 1')
+    const worker = new DesktopProjectManager(manager.paths, { ...manager.runtime, dsh, pnpm: failing })
+    await expect(worker.applyRelease()).rejects.toThrow('pnpm exited with 1')
+    expect(existsSync(join(manager.paths.profile, 'node_modules/plugin'))).toBe(false)
+    const retry = new DesktopProjectManager(manager.paths, { ...manager.runtime, dsh })
+    await expect(retry.applyRelease()).resolves.toBe(true)
+    expect(retry.listPlugins()).toEqual([{ name: 'plugin', version: '1.0.0', enabled: true }])
+    await expect(retry.applyRelease()).resolves.toBe(false)
   })
-})
 
-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
+  it('preserves unknown files when initializing a profile', async () => {
+    const { manager } = setup()
+    mkdirSync(manager.paths.profile, { recursive: true })
+    writeFileSync(join(manager.paths.profile, '.DS_Store'), 'metadata')
+    writeFileSync(join(manager.paths.profile, 'user-file'), 'retain')
+    await expect(manager.applyRelease()).resolves.toBe(true)
+    expect(readFileSync(join(manager.paths.profile, '.DS_Store'), 'utf8')).toBe('metadata')
+    expect(readFileSync(join(manager.paths.profile, 'user-file'), 'utf8')).toBe('retain')
+  })
+
+  it.each(['plugin-add', 'runtime-change'] as const)('retries failed rebuild after %s across manager instances', async (operation) => {
+    const { root, manager } = setup()
+    await manager.applyRelease()
+    let dsh = manager.runtime.dsh
+    if (operation === 'runtime-change') {
+      await manager.mutate({ type: 'plugin-add', spec: 'plugin@1.0.0' }, hooks())
+      dsh = join(root, 'new-node')
+      runtimeFixture(dsh, '1.1.0', '24.18.0')
     }
-    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()
+    const failing = join(root, 'fail-rebuild.mjs')
+    writeFileSync(failing, `await import(${JSON.stringify(pathToFileURL(manager.runtime.pnpm).href)}); if (process.argv.includes('rebuild')) process.exitCode = 1`)
+    const worker = new DesktopProjectManager(manager.paths, { ...manager.runtime, dsh, pnpm: failing })
+    if (operation === 'plugin-add') {
+      await worker.applyRelease()
+      await expect(worker.mutate({ type: 'plugin-add', spec: 'plugin@1.0.0' }, hooks())).rejects.toThrow('pnpm exited with 1')
+    } else await expect(worker.applyRelease()).rejects.toThrow('pnpm exited with 1')
+    expect(() => { worker.assertProfileRuntime(worker.paths.profile) }).toThrow('package preparation is incomplete')
+    const count = calls(root).length
+    const retry = new DesktopProjectManager(manager.paths, { ...manager.runtime, dsh })
+    await expect(retry.applyRelease()).resolves.toBe(true)
+    expect(calls(root).slice(count).map(call => call.args.find(arg => !arg.startsWith('--config.')))).toEqual(['install', 'rebuild'])
+    await expect(retry.applyRelease()).resolves.toBe(false)
+    expect(calls(root)).toHaveLength(count + 2)
   })
 
-  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()).resolves.toBe(true)
+    await expect(manager.applyRelease()).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('repairs a removed managed link without running pnpm', async () => {
+    const { root, manager } = setup()
+    await manager.applyRelease()
+    unlinkSync(join(manager.paths.profile, 'node_modules/@deepseek-ai/cordis'))
+    await expect(manager.applyRelease()).resolves.toBe(true)
+    expect(calls(root)).toEqual([])
+  })
+
+  it.skipIf(process.platform !== 'win32')('reuses the profile when the launch path changes only Windows letter casing', async () => {
+    const { manager } = setup()
+    await manager.applyRelease()
+    const relaunched = new DesktopProjectManager(manager.paths, { ...manager.runtime, dsh: manager.runtime.dsh.toUpperCase() })
+    await expect(relaunched.applyRelease()).resolves.toBe(false)
+  })
+
+  it.each(['changed', 'same-size', 'extra', 'missing'])('starts and reuses a profile without checking %s runtime bytes', async (operation) => {
+    const { root, manager } = setup()
+    if (operation === 'changed') writeFileSync(join(manager.runtime.dsh, 'package.json'), '{}')
+    if (operation === 'same-size') writeFileSync(join(manager.runtime.dsh, 'package.json'), '{"type":"Module"}\n')
+    if (operation === 'extra') writeFileSync(join(manager.runtime.dsh, 'extra'), '')
+    if (operation === 'missing') unlinkSync(join(manager.runtime.dsh, 'package.json'))
+    await expect(manager.applyRelease()).resolves.toBe(true)
+    const relaunched = new DesktopProjectManager(manager.paths, manager.runtime)
+    await expect(relaunched.applyRelease()).resolves.toBe(false)
+    expect(existsSync(manager.paths.profile)).toBe(true)
+    expect(calls(root)).toEqual([])
   })
 
-  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())
+  it('installs only plugins and checks the graph before running lifecycle scripts', async () => {
+    const { root, manager } = setup()
+    await manager.applyRelease()
     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`)
+    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)
+    await expect(manager.applyRelease()).resolves.toBe(false)
+    expect(calls(root)).toHaveLength(2)
+  })
 
-    manager.recover()
+  it('retains disabled plugin versions through updates and enables them explicitly', async () => {
+    const { root, manager } = setup()
+    await manager.applyRelease()
+    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([])
+  })
 
-    expect(manager.listPlugins()).toEqual([{ name: '@scope/plugin', version: '2.0.0' }])
-    expect(existsSync(stagingProfile)).toBe(false)
-    expect(existsSync(paths.pending)).toBe(false)
+  it('keeps plugin files and patches through a compatible release and application relocation', async () => {
+    const { root, manager } = setup()
+    await manager.applyRelease()
+    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()).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')))
+    expect(readFileSync(join(manager.paths.profile, 'node_modules/plugin/bundle.yml'), 'utf8')).toBe('[]\n')
   })
 
-  it('records the live pnpm worker as transaction owner until it exits', async ({ task, signal }) => {
-    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())
+  it('reinstalls the locked plugin graph when bundled Node changes', async () => {
+    const { root, manager } = setup()
+    await manager.applyRelease()
+    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()
+    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 }])
+  })
+
+  it('allows incompatible plugins to be disabled in recovery without deleting them', async () => {
+    const { root, manager } = setup()
+    await manager.applyRelease()
+    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()).rejects.toThrow(/requires @deepseek-ai\/cordis/u)
+    expect(next.releaseVersion()).toBe('2.0.0')
+    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.each(['before', 'after'] as const)('retains direct writes when the %s change hook fails', async (phase) => {
+    const { manager } = setup()
+    await manager.applyRelease()
+    let starts = 0
+    await expect(manager.mutate({ type: 'plugin-add', spec: 'plugin@1.0.0' }, hooks({
+      beforeChange: async () => {
+        expect(manager.listPlugins()).toEqual([])
+        if (phase === 'before') throw new Error('before failed')
+      },
+      afterChange: async () => { starts++; throw new Error('after failed') },
+    }))).rejects.toThrow(`${phase} failed`)
+    expect(manager.listPlugins()).toEqual(phase === 'before' ? [] : [{ name: 'plugin', version: '1.0.0', enabled: true }])
+    expect(starts).toBe(phase === 'before' ? 0 : 1)
+    expect(existsSync(join(manager.paths.root, 'staging'))).toBe(false)
+    expect(existsSync(join(manager.paths.root, 'rollback'))).toBe(false)
+    expect(existsSync(join(manager.paths.root, 'pending.json'))).toBe(false)
+  })
+
+  it('keeps partial package changes and restores host links after pnpm fails', async () => {
+    const { root, manager } = setup()
+    await manager.applyRelease()
+    const failingPnpm = join(root, 'failing.mjs')
+    writeFileSync(failingPnpm, `await import(${JSON.stringify(pathToFileURL(manager.runtime.pnpm).href)}); process.exitCode = 1`)
+    const worker = new DesktopProjectManager(manager.paths, { ...manager.runtime, pnpm: failingPnpm })
+    await worker.applyRelease()
+    let starts = 0
+    await expect(worker.mutate({ type: 'plugin-add', spec: 'plugin@1.0.0' }, hooks({
+      afterChange: async () => { starts++ },
+    }))).rejects.toThrow(/pnpm exited with 1/u)
+    expect(worker.listPlugins()).toEqual([{ name: 'plugin', version: '1.0.0', enabled: false }])
+    expect(starts).toBe(0)
+    expect(existsSync(manager.paths.lock)).toBe(false)
+    expect(realpathSync(join(manager.paths.profile, 'node_modules/@deepseek-ai/cordis')))
+      .toBe(realpathSync(join(manager.runtime.dsh, 'node_modules/@deepseek-ai/cordis')))
+    await manager.mutate({ type: 'plugin-remove', name: 'plugin' }, hooks())
+    expect(manager.listPlugins()).toEqual([])
+  })
+
+  it('holds the transaction lock until the pnpm worker exits', async ({ task, signal }) => {
+    const { root, manager } = setup()
+    await manager.applyRelease()
+    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()
+    const pending = worker.mutate({ type: 'plugin-add', spec: 'plugin@1.0.0' }, hooks())
     // Teardown observes failures even if the runner has abandoned the test body.
-    const completed = installing.then(value => ({ value }), (error: unknown) => ({ error }))
+    const completed = pending.then(value => ({ value }), (error: unknown) => ({ error }))
     releaseWorkers.push(async () => {
-      writeFileSync(releaseWorker, 'continue')
+      writeFileSync(release, 'continue')
       const outcome = await completed
       if ('error' in outcome) throw outcome.error
     })
-    // Child startup shares the test budget; an aborted poll must not resume ownership assertions.
-    await expect.poll(() => {
-      signal.throwIfAborted()
-      return existsSync(ready)
-    }, { timeout: task.timeout }).toBe(true)
-    signal.throwIfAborted()
-    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 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())
+      // Child startup shares the test budget; an aborted poll must not resume ownership assertions.
+      await expect.poll(() => {
+        signal.throwIfAborted()
+        return existsSync(ready)
+      }, { timeout: task.timeout }).toBe(true)
+      signal.throwIfAborted()
+      expect(readFileSync(manager.paths.lock, 'utf8').trim()).toBe(readFileSync(ready, 'utf8'))
+      await expect(manager.applyRelease()).rejects.toThrow(/another package transaction/u)
     } finally {
-      if (previousLog === undefined) delete process.env.TEST_PNPM_LOG
-      else process.env.TEST_PNPM_LOG = previousLog
+      writeFileSync(release, 'continue')
+      await pending
     }
-
-    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('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())
-
-    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)
-
-    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[] } }
-    }
-    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)
   })
 })

+ 81 - 0
apps/desktop/tests/runtime-file-policy.spec.ts

@@ -0,0 +1,81 @@
+import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join, relative } from 'node:path'
+import { expect, it } from 'vitest'
+import { desktopRuntimeFileExclusion } from '../scripts/runtime-file-policy.ts'
+import { verifyDesktopRuntime, writeDesktopRuntime } from '../src/runtime-tree.ts'
+import { runtimeFixture } from './runtime-fixture.ts'
+
+const windows = { platform: 'win32' as const, arch: 'x64' }
+
+it('omits development artifacts while preserving executable modules, assets and license files', async () => {
+  const root = mkdtempSync(join(tmpdir(), 'desktop-file-policy-'))
+  const source = join(root, 'source')
+  const output = join(root, 'output')
+  const removed = [
+    'example/index.d.ts', 'example/index.d.mts', 'example/index.d.cts',
+    'example/index.js.map', 'example/index.mjs.map', 'example/index.cjs.map',
+    'example/style.css.map', 'example/index.d.ts.map', 'example/index.d.mts.map',
+    'example/index.d.cts.map', 'example/tsconfig.tsbuildinfo',
+    'fs-ext/build/Release/obj/fs_ext/native.obj', 'fs-ext/build/Release/fs_ext.pdb',
+    'fs-ext/build/Release/fs_ext.lib', 'fs-ext/build/Release/fs_ext.exp',
+    'fs-ext/build/Release/fs_ext.iobj', 'fs-ext/build/Release/fs_ext.ipdb',
+    'fs-ext/build/binding.sln', 'fs-ext/build/config.gypi',
+    'fs-ext/build/fs_ext.vcxproj', 'fs-ext/build/fs_ext.vcxproj.filters',
+    'node-pty/prebuilds/win32-arm64/conpty.node',
+    'node-pty/prebuilds/linux-x64/pty.node', 'node-pty/prebuilds/darwin-x64/pty.node',
+    'node-pty/prebuilds/win32-x64/conpty.pdb',
+    '@koromix/koffi-win32-x64/win32_x64/koffi.lib',
+    '@mixmark-io/domino/test/entities.html',
+    '.modules.yaml', '.pnpm-workspace-state-v1.json', '.bin/tool', '.pnpm/cache',
+  ]
+  const retained = [
+    'example/index.js', 'example/index.cjs', 'example/index.mjs', 'example/worker.js',
+    'example/source.ts', 'example/src/entry.ts', 'example/test/runtime-fixture.json',
+    'example/locale.json', 'example/data.map', 'example/module.wasm',
+    'example/package.json', 'example/LICENSE', 'example/NOTICE', 'example/README.md',
+    'example/native.lib', 'example/native.obj', 'example/symbols.pdb',
+    'fs-ext/build/Release/fs_ext.node', 'fs-ext/build/Release/runtime.dll',
+    'node-pty/prebuilds/win32-x64/conpty.node',
+    'node-pty/prebuilds/win32-x64/conpty_console_list.node',
+    'node-pty/prebuilds/win32-x64/conpty/conpty.dll',
+    'node-pty/prebuilds/win32-x64/conpty/OpenConsole.exe',
+    'node-pty/third_party/conpty/win10-x64/OpenConsole.exe',
+    '@koromix/koffi-win32-x64/win32_x64/koffi.node',
+    '@mixmark-io/domino/lib/HTMLParser.js', '@mixmark-io/domino/lib/EntityParser.js',
+    '@img/sharp-win32-x64/lib/libvips-42.dll',
+  ]
+  try {
+    const runtime = runtimeFixture(source)
+    const modules = join(source, 'node_modules')
+    for (const path of [...removed, ...retained]) {
+      mkdirSync(join(modules, path, '..'), { recursive: true })
+      writeFileSync(join(modules, path), `payload:${path}`)
+    }
+    cpSync(modules, join(output, 'node_modules'), {
+      recursive: true, dereference: true,
+      filter: path => desktopRuntimeFileExclusion(relative(modules, path), windows) === undefined,
+    })
+    for (const path of removed) expect(existsSync(join(output, 'node_modules', path)), path).toBe(false)
+    for (const path of retained) expect(readFileSync(join(output, 'node_modules', path), 'utf8'), path).toBe(`payload:${path}`)
+    const sealed = writeDesktopRuntime(output, runtime.release, runtime.sharedPackages.map(entry => entry.name))
+    expect(await verifyDesktopRuntime(output, runtime.release.version)).toEqual(sealed)
+    expect(readFileSync(join(modules, removed[0]!), 'utf8')).toBe(`payload:${removed[0]}`)
+  } finally {
+    rmSync(root, { recursive: true, force: true })
+  }
+})
+
+it('applies package-specific rules inside scoped and nested dependency containers', () => {
+  expect(desktopRuntimeFileExclusion('outer/node_modules/@mixmark-io/domino/test/data.html', windows)).toBeDefined()
+  expect(desktopRuntimeFileExclusion('outer\\node_modules\\node-pty\\prebuilds\\win32-arm64\\conpty.node', windows)).toBeDefined()
+  expect(desktopRuntimeFileExclusion('outer/node_modules/unrelated/test/data.html', windows)).toBeUndefined()
+  expect(desktopRuntimeFileExclusion('outer/fs-ext/build/Release/fs_ext.lib', windows)).toBeUndefined()
+})
+
+it('retains native prebuilds for the selected macOS architecture', () => {
+  const mac = { platform: 'darwin' as const, arch: 'arm64' }
+  expect(desktopRuntimeFileExclusion('node-pty/prebuilds/darwin-arm64/pty.node', mac)).toBeUndefined()
+  expect(desktopRuntimeFileExclusion('node-pty/prebuilds/darwin-x64/pty.node', mac)).toBeDefined()
+  expect(desktopRuntimeFileExclusion('node-pty/prebuilds/win32-x64/conpty.node', mac)).toBeDefined()
+})

+ 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)
+}

+ 49 - 0
apps/desktop/tests/runtime-tree-read-failure.spec.ts

@@ -0,0 +1,49 @@
+import { mkdtempSync, readFile, readFileSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { setImmediate } from 'node:timers/promises'
+import { expect, it, vi } from 'vitest'
+import { verifyDesktopRuntime } from '../src/runtime-tree.ts'
+import { runtimeFixture } from './runtime-fixture.ts'
+
+vi.mock('node:fs', async importOriginal => ({
+  ...await importOriginal<typeof import('node:fs')>(),
+  readFile: vi.fn(),
+}))
+
+it('drains outstanding reads before rejecting and stops scheduling after a read failure', async () => {
+  const root = mkdtempSync(join(tmpdir(), 'desktop-runtime-read-failure-'))
+  const pending: ((error?: Error) => void)[] = []
+  vi.mocked(readFile).mockImplementation((...args: unknown[]) => {
+    const path = args[0]
+    const callback = args.at(-1)
+    if (typeof path !== 'string' || typeof callback !== 'function') throw new Error('unexpected readFile arguments')
+    const complete = callback as (error: Error | null, body: Buffer | undefined) => void
+    pending.push((error) => { complete(error ?? null, error === undefined ? readFileSync(path) : undefined) })
+  })
+  let outcome: Promise<unknown> | undefined
+  try {
+    runtimeFixture(root)
+    let settled = false
+    outcome = verifyDesktopRuntime(root, '1.0.0').finally(() => { settled = true }).catch((error: unknown) => error)
+    const inFlight = pending.length
+    expect(inFlight).toBeGreaterThan(1)
+    const failure = new Error('runtime read failed')
+    pending.shift()!(failure)
+    try {
+      // Pending callbacks keep the reads open across a complete event-loop turn.
+      await setImmediate()
+      expect(settled).toBe(false)
+      expect(pending).toHaveLength(inFlight - 1)
+    } finally {
+      for (const complete of pending.splice(0)) complete()
+    }
+    expect(await outcome).toBe(failure)
+    expect(pending).toHaveLength(0)
+  } finally {
+    for (const complete of pending.splice(0)) complete(new Error('test cleanup'))
+    await outcome
+    vi.mocked(readFile).mockReset()
+    rmSync(root, { recursive: true, force: true })
+  }
+})

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

@@ -0,0 +1,107 @@
+import { cpSync, mkdirSync, 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_HOST_PACKAGE, DESKTOP_HOST_RUNTIME_FILES } from '../src/core-package-set.ts'
+import { DESKTOP_RUNTIME_FILE, desktopRuntimeId, readDesktopRuntime, 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', async () => {
+  const root = fixture()
+  const before = await verifyDesktopRuntime(join(root, 'dsh'), '1.0.0')
+  cpSync(join(root, 'dsh'), join(root, 'moved'), { recursive: true })
+  expect(desktopRuntimeId(await verifyDesktopRuntime(join(root, 'moved'), '1.0.0'))).toBe(desktopRuntimeId(before))
+})
+it.each(['changed', 'same-size', 'extra', 'missing'])('checks %s runtime bytes only during build verification', async (operation) => {
+  const dsh = join(fixture(), 'dsh')
+  const before = readDesktopRuntime(dsh)
+  if (operation === 'changed') writeFileSync(join(dsh, 'package.json'), '{}')
+  if (operation === 'same-size') writeFileSync(join(dsh, 'package.json'), '{"type":"Module"}\n')
+  if (operation === 'extra') writeFileSync(join(dsh, 'extra'), '')
+  if (operation === 'missing') rmSync(join(dsh, 'package.json'))
+  expect(readDesktopRuntime(dsh)).toEqual(before)
+  await expect(verifyDesktopRuntime(dsh, '1.0.0')).rejects.toThrow(/integrity/u)
+})
+it('rejects filesystem links and incompatible targets', async () => {
+  const dsh = join(fixture(), 'dsh')
+  await expect(verifyDesktopRuntime(dsh, '1.0.0', { platform: process.platform, arch: 'wrong' })).rejects.toThrow(/incompatible/u)
+  symlinkSync(join(dsh, 'node_modules'), join(dsh, 'outside'), process.platform === 'win32' ? 'junction' : 'dir')
+  expect(readDesktopRuntime(dsh).release.version).toBe('1.0.0')
+  await expect(verifyDesktopRuntime(dsh, '1.0.0')).rejects.toThrow(/unsupported filesystem/u)
+})
+it('reads file inventory records unchanged during startup', () => {
+  const dsh = join(fixture(), 'dsh')
+  const path = join(dsh, DESKTOP_RUNTIME_FILE)
+  const descriptor = JSON.parse(readFileSync(path, 'utf8')) as { files: unknown[] }
+  descriptor.files.unshift({ path: '../outside', bytes: -1.5, sha256: 'unchecked', executable: 'unchecked' })
+  writeFileSync(path, JSON.stringify(descriptor))
+  expect(readDesktopRuntime(dsh).files).toEqual(descriptor.files)
+})
+it.each(['missing', 'directory'])('checks a %s Host entry only during build verification', async (operation) => {
+  const dsh = join(fixture(), 'dsh')
+  const path = join(dsh, 'node_modules', DESKTOP_HOST_PACKAGE, DESKTOP_HOST_RUNTIME_FILES[0])
+  rmSync(path)
+  if (operation === 'directory') mkdirSync(path)
+  expect(readDesktopRuntime(dsh).release.version).toBe('1.0.0')
+  await expect(verifyDesktopRuntime(dsh, '1.0.0')).rejects.toThrow(/integrity/u)
+})
+it('checks the shell version only during build verification', async () => {
+  const dsh = join(fixture(), 'dsh')
+  expect(readDesktopRuntime(dsh).release.version).toBe('1.0.0')
+  await expect(verifyDesktopRuntime(dsh, '2.0.0')).rejects.toThrow(/does not match Electron/u)
+})
+it.each([
+  { schemaVersion: 2 },
+  { platform: 'other' },
+  { arch: 'other' },
+  { release: { schemaVersion: 2 } },
+  { release: { hostProtocolVersion: 999 } },
+  { release: { nodeVersion: 'invalid' } },
+  { release: { pnpmVersion: 'invalid' } },
+])('checks release compatibility only during build verification: %j', async (patch) => {
+  const dsh = join(fixture(), 'dsh')
+  const path = join(dsh, DESKTOP_RUNTIME_FILE)
+  const original = readDesktopRuntime(dsh)
+  const descriptor = { ...original, ...patch, release: { ...original.release, ...patch.release } }
+  writeFileSync(path, JSON.stringify(descriptor))
+  expect(readDesktopRuntime(dsh)).toEqual(descriptor)
+  await expect(verifyDesktopRuntime(dsh, '1.0.0')).rejects.toThrow(/invalid|incompatible/u)
+})
+it.each(['missing', 'invalid-json', 'mismatched'])('checks %s shared manifests only during build verification', async (operation) => {
+  const dsh = join(fixture(), 'dsh')
+  const before = readDesktopRuntime(dsh)
+  const path = join(dsh, 'node_modules', DESKTOP_HOST_PACKAGE, 'package.json')
+  if (operation === 'missing') rmSync(path)
+  else writeFileSync(path, operation === 'invalid-json' ? '{' : '{}')
+  expect(readDesktopRuntime(dsh)).toEqual(before)
+  await expect(verifyDesktopRuntime(dsh, '1.0.0')).rejects.toThrow()
+})
+it('rejects a descriptor that maps a shared package outside node_modules', async () => {
+  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))
+  await expect(verifyDesktopRuntime(dsh, '1.0.0')).rejects.toThrow(/shared package record/u)
+})
+it('verifies recorded executable permissions only on Unix', async () => {
+  const dsh = join(fixture(), 'dsh')
+  const path = join(dsh, DESKTOP_RUNTIME_FILE)
+  const descriptor = JSON.parse(readFileSync(path, 'utf8')) as { files: { executable: boolean }[] }
+  descriptor.files[0]!.executable = !descriptor.files[0]!.executable
+  writeFileSync(path, JSON.stringify(descriptor))
+  if (process.platform === 'win32') await expect(verifyDesktopRuntime(dsh, '1.0.0')).resolves.toMatchObject(descriptor)
+  else await expect(verifyDesktopRuntime(dsh, '1.0.0')).rejects.toThrow(/integrity/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)
+})

Неке датотеке нису приказане због велике количине промена