From e84a4e857ea227c13003c9421c7fb3130f503a78 Mon Sep 17 00:00:00 2001 From: 07akioni <07akioni2@gmail.com> Date: Thu, 10 Sep 2026 22:08:33 +0800 Subject: [PATCH 01/35] refactor(desktop): run shared Web UI in a thin Electron shell --- ...on-desktop-packaging-and-updates.i18n.yaml | 4 +- ...-electron-desktop-packaging-and-updates.md | 41 +- ...ectron-desktop-packaging-and-updates.zh.md | 41 +- ...led-runtime-and-external-plugins.i18n.yaml | 4 +- ...op-bundled-runtime-and-external-plugins.md | 20 +- ...bundled-runtime-and-external-plugins.zh.md | 20 +- ...mmediate-window-and-direct-start.i18n.yaml | 4 +- ...sktop-immediate-window-and-direct-start.md | 4 +- ...op-immediate-window-and-direct-start.zh.md | 4 +- ...6-09-09-desktop-in-place-profile.i18n.yaml | 4 +- .../2026-09-09-desktop-in-place-profile.md | 6 +- .../2026-09-09-desktop-in-place-profile.zh.md | 6 +- .../2026-09-10-desktop-web-wrapper.i18n.yaml | 6 + .../2026-09-10-desktop-web-wrapper.md | 31 + .../2026-09-10-desktop-web-wrapper.zh.md | 31 + apps/cli/README.i18n.yaml | 4 +- apps/cli/README.md | 2 + apps/cli/README.zh.md | 2 + apps/cli/package.json | 10 +- apps/cli/src/profile-boot.ts | 228 ++++--- apps/cli/tests/resolved-profile-boot.spec.ts | 156 +++++ apps/cli/tsdown.config.ts | 6 +- .../config/desktop.cordis.patch.yml | 25 +- apps/desktop-host/package.json | 8 +- apps/desktop-host/src/index.ts | 604 +----------------- apps/desktop-host/src/wire.ts | 184 ------ apps/desktop-host/tsconfig.json | 25 +- apps/desktop/README.i18n.yaml | 4 +- apps/desktop/README.md | 30 +- apps/desktop/README.zh.md | 30 +- apps/desktop/scripts/development-project.ts | 21 +- apps/desktop/scripts/smoke-runtime.ts | 15 +- apps/desktop/src/host-process.ts | 347 +--------- apps/desktop/src/host-protocol.ts | 215 +------ apps/desktop/src/locale.ts | 2 - apps/desktop/src/main.ts | 58 +- apps/desktop/src/paths.ts | 20 - apps/desktop/src/profile-packages.ts | 139 +--- apps/desktop/src/project-manager.ts | 291 +++------ .../desktop/tests/development-project.spec.ts | 20 +- apps/desktop/tests/host-process.spec.ts | 313 +++------ apps/desktop/tests/host-protocol.spec.ts | 98 --- apps/desktop/tests/main-startup.spec.ts | 89 ++- apps/desktop/tests/plugin-pnpm.spec.ts | 47 +- apps/desktop/tests/profile-packages.spec.ts | 42 +- apps/desktop/tests/project-manager.spec.ts | 176 ++--- packages/boot/app-boot/README.i18n.yaml | 4 +- packages/boot/app-boot/README.md | 2 +- packages/boot/app-boot/README.zh.md | 2 +- packages/boot/app-boot/src/index.ts | 1 + packages/boot/app-boot/src/profile.ts | 33 +- packages/boot/app-boot/tests/profile.spec.ts | 51 ++ pnpm-lock.yaml | 18 - tsconfig.base.json | 1 + 54 files changed, 1110 insertions(+), 2439 deletions(-) create mode 100644 .agents/notes/implemented/architecture/2026-09-10-desktop-web-wrapper.i18n.yaml create mode 100644 .agents/notes/implemented/architecture/2026-09-10-desktop-web-wrapper.md create mode 100644 .agents/notes/implemented/architecture/2026-09-10-desktop-web-wrapper.zh.md create mode 100644 apps/cli/tests/resolved-profile-boot.spec.ts delete mode 100644 apps/desktop-host/src/wire.ts delete mode 100644 apps/desktop/tests/host-protocol.spec.ts diff --git a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.i18n.yaml index 3c31c033aa..905503e9fa 100644 --- a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.i18n.yaml +++ b/.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: f92f15542b1903cdfe5c7b2794ce872becab3517 -2026-08-25-electron-desktop-packaging-and-updates.zh.md: e67d00417fb4e80cff742862537572653ad8d22c +2026-08-25-electron-desktop-packaging-and-updates.md: 5eb10d58af4c9a2f4ff0db72d2d232d414d40442 +2026-08-25-electron-desktop-packaging-and-updates.zh.md: e568b5395931b596f51e1efbfa471ad8cf6ffa33 diff --git a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md index f92f15542b..5eb10d58af 100644 --- a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md +++ b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md @@ -16,7 +16,7 @@ The current GUI protocol binds the Web client and backend release. Independently ## Decision -Ship a small Electron shell with a bundled upstream Node.js executable and pinned pnpm. Electron starts the private Desktop Host package as an isolated child process; that package composes the installed dsh backend and matching client graph. Fetch metadata and bounded raw request and response chunks travel over two versioned framed byte pipes, Node IPC is reserved for readiness, fatal failure, and shutdown, and Electron serves validated assets through `dsh-app://`; it opens no listening port. Each frame carries a fixed marker, type, monotonic stream id, payload length, and validated payload. Serialized writers honor pipe drain, readers pause globally when a request or response stream applies backpressure, cancellation closes the matching stream, and late response frames for a retired stream stay inert. The Connection plugin provides its carrier-neutral RPC and Fetch registries without requiring `webServer`, while Client Modules provides the exact advertised combo-bundle responses to the shell-owned carrier; Web compositions attach their optional HTTP routes for both. The renderer keeps the same Fetch, RPC, and Remote-stream formats, while the child carrier avoids Base64 expansion and V8 serialization compatibility between Electron and the bundled upstream Node.js. Electron closes its request-pipe writer after sending shutdown, releasing an in-flight Windows pipe read before it waits for child exit. This follows the Electron reservation in the [GUI layering and RPC protocol note](../../archived/architecture/2026-07-19-gui-layering-and-rpc-protocol.md). +Ship a small Electron shell with a bundled upstream Node.js executable and pinned pnpm. The [thin-wrapper decision](2026-09-10-desktop-web-wrapper.md) owns Host boot and transport: the private Host runs the shared Web profile runner, Electron loads its authenticated HTTP URL, and child IPC carries lifecycle messages. Electron owns the reserved profile at `.dsh/profiles/desktop`. The [bundled-runtime decision](2026-09-08-desktop-bundled-runtime-and-external-plugins.md) owns core resource storage, external plugin dependencies, shared package links, and profile reconciliation. The private Desktop Host remains outside the public CLI package and is never published to npm. @@ -28,8 +28,8 @@ The browser Web UI, dsh backend, existing `dsh plugin` CLI, user npm, and user p | Owner | Responsibility | |---|---| -| Electron shell | Window and child lifecycle, framed byte pipes, lifecycle IPC, custom protocol, reserved desktop profile, plugin GUI, update coordination | -| Bundled Node.js and pnpm | Execute dsh and install exact desktop-project dependencies without consulting user `PATH` or pnpm state | +| Electron shell | Window and child lifecycle, local shell pages, reserved desktop profile, plugin GUI, update coordination | +| Bundled Node.js and pnpm | Execute dsh and install desktop-project dependencies using pnpm’s normal configuration | | Desktop profile | External plugin dependencies, ordered enabled bundles, and shared links defined by the bundled-runtime decision | | Private Desktop Host package | Electron-only child-process entry and composition overlay installed with dsh but excluded from the public CLI package and npm publication | | Installed dsh package | Backend, matching Web UI, boot manifest, client bundles, and product behavior | @@ -42,18 +42,11 @@ The renderer uses `nodeIntegration: false`, `contextIsolation: true`, and `sandb ```text ~/.dsh/ - desktop/ - pnpm/ - store/ - cache/ - state/ - config/ profiles/ desktop/ package.json pnpm-lock.yaml lock - desktop-packages-pending pnpm-workspace.yaml desktop-runtime-state.json node_modules/ @@ -61,7 +54,7 @@ The renderer uses `nodeIntegration: false`, `contextIsolation: true`, and `sandb storages/ ``` -`.dsh/profiles/desktop` is the only active desktop profile. Its executable package ownership and allowed resolution directories follow the [bundled-runtime decision](2026-09-08-desktop-bundled-runtime-and-external-plugins.md). Plugin package content uses `.dsh/desktop/pnpm/store`. +`.dsh/profiles/desktop` is the only active desktop profile. Its executable package ownership and allowed resolution directories follow the [bundled-runtime decision](2026-09-08-desktop-bundled-runtime-and-external-plugins.md). pnpm selects its store and cache from normal configuration. ## Installation and resolution @@ -81,13 +74,13 @@ The [immediate-window decision](2026-09-09-desktop-immediate-window-and-direct-s ## Security and release policy -Core dsh and the private Desktop Host come only from the signed application resource tree. Plugin installation accepts registry package specs allowed by desktop policy but never raw pnpm commands. Exact versions, lockfile integrity, a reviewed `allowBuilds` set, and user-only directory permissions are required before activation. +Core dsh and the private Desktop Host come only from the signed application resource tree. Plugin installation forwards package specs to pnpm, including local and remote sources, but never accepts raw pnpm commands. pnpm owns dependency resolution and the profile’s `allowBuilds` policy; the Host loads activated bundles. -Electron release artifacts are signed; macOS artifacts are notarized. Release automation must supply the application ID, macOS Developer ID qualifier, expected Team ID, and one complete notarytool credential strategy through explicit environment variables. Configuration loading rejects missing or malformed identifiers and incomplete notarization credentials, while macOS packaging requires signing so certificate discovery cannot silently select another installed identity or emit an unsigned release. Runtime preparation verifies the exact Authority and Team ID plus the timestamp and hardened-runtime flags on every embedded Mach-O file. An after-sign hook performs Apple's deep strict application verification and requires the same leaf Authority and Team ID before artifact creation continues. Electron-builder then notarizes and staples the application and signs the DMG. The DMG artifact-completion hook separately notarizes and staples every DMG before requiring the configured identity, a valid ticket, and Gatekeeper acceptance; the upload event runs only after that hook succeeds. DMG blockmaps are disabled because macOS updates consume the signed ZIP, and stapling would otherwise invalidate an already-generated DMG blockmap. The custom protocol serves the installed frontend distribution plus client files named by the active module graph and rejects traversal or access outside those roots. The plugin installer API is available only to the Electron-owned management GUI and is absent from the browser application and backend RPC. +Electron release artifacts are signed; macOS artifacts are notarized. Release automation must supply the application ID, macOS Developer ID qualifier, expected Team ID, and one complete notarytool credential strategy through explicit environment variables. Configuration loading rejects missing or malformed identifiers and incomplete notarization credentials, while macOS packaging requires signing so certificate discovery cannot silently select another installed identity or emit an unsigned release. Runtime preparation verifies the exact Authority and Team ID plus the timestamp and hardened-runtime flags on every embedded Mach-O file. An after-sign hook performs Apple's deep strict application verification and requires the same leaf Authority and Team ID before artifact creation continues. Electron-builder then notarizes and staples the application and signs the DMG. The DMG artifact-completion hook separately notarizes and staples every DMG before requiring the configured identity, a valid ticket, and Gatekeeper acceptance; the upload event runs only after that hook succeeds. DMG blockmaps are disabled because macOS updates consume the signed ZIP, and stapling would otherwise invalidate an already-generated DMG blockmap. The shared Web server owns frontend and client-module responses. The plugin installer API is available only to the Electron-owned management GUI and is absent from the browser application and backend RPC. The [pinned osx-sign patch](../../../../patches/@electron__osx-sign@1.3.3.patch) uses `lstat` in both published module builds, so Framework file and directory aliases do not trigger duplicate signing. The patch remains necessary until the selected upstream release skips those aliases. PAK files are resources sealed by the enclosing bundle; individual signatures add serial timestamp requests without additional resource integrity. Desktop preserves all locale files and skips only their standalone signatures. Executable code retains Developer ID signatures, secure timestamps, and hardened runtime. The [signer traversal regression](../../../../apps/desktop/tests/macos-signing-walk.spec.ts) exercises the installed dependency with real Framework aliases; release qualification still requires strict application verification, notarization, and startup. -Windows release packaging supplies the public EV leaf certificate named by `DSH_DESKTOP_WINDOWS_CER_FILE` to the configured SafeNet-compatible SignTool through `/f` and identifies its matching private key through the required `DSH_DESKTOP_WINDOWS_KEY_CONTAINER`. The certificate file remains outside source control, and the private key remains on the USB token. The electron-builder hook passes each artifact to the CRLF `windows-sign.cmd`, whose single SignTool invocation uses the SafeNet `/kc "[{{PIN}}]=container"` value and CSP, a SHA-256 file digest, and a DigiCert SHA-256 RFC 3161 timestamp. The hook never substitutes another SignTool and never retries a failed request. Package orchestration withholds every `DSH_DESKTOP_WINDOWS_*` field from build and runtime-preparation children and passes only the certificate path, SignTool path, key container, and PIN into electron-builder. The signer supplies only validated signing fields in an otherwise scrubbed CMD environment; the CMD disables delayed expansion, clears those fields before SignTool starts, and preserves the PIN only in the required SignTool command line. Every surfaced diagnostic replaces the PIN, and only the dedicated build account and administrators may inspect the runner. The signer signs electron-builder's temporary NSIS bootstrap before enterprise Code Integrity evaluates that executable and clears a generated executable's certificate-table entry only when it points beyond the file before applying the final signature. Packaging fails before producing unsigned artifacts when the SignTool, certificate, container, PIN, token, or signature is unavailable. The custom protocol serves the installed frontend distribution plus client files named by the active module graph and rejects traversal or access outside those roots. The plugin installer API is available only to the Electron-owned management GUI and is absent from the browser application and backend RPC. +Windows release packaging supplies the public EV leaf certificate named by `DSH_DESKTOP_WINDOWS_CER_FILE` to the configured SafeNet-compatible SignTool through `/f` and identifies its matching private key through the required `DSH_DESKTOP_WINDOWS_KEY_CONTAINER`. The certificate file remains outside source control, and the private key remains on the USB token. The electron-builder hook passes each artifact to the CRLF `windows-sign.cmd`, whose single SignTool invocation uses the SafeNet `/kc "[{{PIN}}]=container"` value and CSP, a SHA-256 file digest, and a DigiCert SHA-256 RFC 3161 timestamp. The hook never substitutes another SignTool and never retries a failed request. Package orchestration withholds every `DSH_DESKTOP_WINDOWS_*` field from build and runtime-preparation children and passes only the certificate path, SignTool path, key container, and PIN into electron-builder. The signer supplies only validated signing fields in an otherwise scrubbed CMD environment; the CMD disables delayed expansion, clears those fields before SignTool starts, and preserves the PIN only in the required SignTool command line. Every surfaced diagnostic replaces the PIN, and only the dedicated build account and administrators may inspect the runner. The signer signs electron-builder's temporary NSIS bootstrap before enterprise Code Integrity evaluates that executable and clears a generated executable's certificate-table entry only when it points beyond the file before applying the final signature. Packaging fails before producing unsigned artifacts when the SignTool, certificate, container, PIN, token, or signature is unavailable. The shared Web server owns frontend and client-module responses. The plugin installer API is available only to the Electron-owned management GUI and is absent from the browser application and backend RPC. Windows package invocations force `ELECTRON_BUILDER_7Z_FILTER=BCJ`. The bundled 7-Zip 24.09 encoder automatically selects ARM64 filters for ARM64 PE files, but the NSIS decoder from `nsis-resources-3.4.1` omits those entries during extraction. A native extraction probe with the actual NSIS plugin loses both `node-pty` ARM64 binaries under automatic filtering and restores both byte-for-byte with BCJ. Keeping a compatible filter preserves dependency contents and runtime integrity instead of removing architecture-specific files or weakening verification. @@ -106,17 +99,17 @@ The bundled upstream Node.js and pnpm are expected to add about 35–50 MB compr | Surface | Implementation | |---|---| | Shell | `apps/desktop` owns Electron windows, restricted preloads, the custom protocol, child lifecycle, project transactions, the plugin GUI, update coordination, and electron-builder configuration. | -| Installed runtime | Private `@deepseek-ai/dsh-desktop-host` boots the portless desktop composition from the active project and streams API and asset responses over validated framed byte pipes. | +| Installed runtime | Private `@deepseek-ai/dsh-desktop-host` invokes the shared profile runner and reports the authenticated Web URL to Electron. | | Package state | Bundled Node.js executes immutable core resources; bundled pnpm modifies only the external plugin graph in the Desktop profile. | | Qualification | macOS packaging requires the configured company identity and notary credentials, verifies every native runtime file before inventory generation, verifies the completed application signature, and requires notarization plus Gatekeeper acceptance for both the application and DMG. Windows packaging requires the configured public certificate, SafeNet private-key container, Token Password, and SignTool, and verifies every produced signature. Update hosting, previous-version installed-artifact tests, and platform GUI recordings remain release-environment gates. | -`dev:desktop` builds the current workspace, projects the built CLI and private Desktop Host packages plus their dependency links into a disposable project, uses an isolated Harness home, opens the Main, Renderer, and Host debuggers, and starts unpackaged Electron without preparing release resources. Package mutation is disabled in this mode because its linked dependency graph is not a pnpm-installed desktop project. Fixed macOS arm64, macOS x64, and Windows x64 package commands pass one target through runtime preparation, dsh preparation, and electron-builder; each also has an unpacked-directory variant for release-path verification before installer generation. +`dev:desktop` builds the current workspace, projects the built CLI and private Desktop Host packages plus their dependency links into a disposable project, uses an isolated Harness home, opens the Main, Renderer, and Host debuggers, and starts unpackaged Electron without preparing release resources. The development runtime supplies workspace links to a separate plugin profile; plugin management and recovery use the same flow as packaged applications. Fixed macOS arm64, macOS x64, and Windows x64 package commands pass one target through runtime preparation, dsh preparation, and electron-builder; each also has an unpacked-directory variant for release-path verification before installer generation. ## Alternatives considered **Use Electron's Node.js for dsh.** This saves package size but couples dsh to Electron's Node patches, fuses, native ABI, TLS behavior, and process lifecycle. A bundled upstream Node.js keeps dsh on its supported runtime. -**Carry Fetch bodies through JSON IPC as Base64.** JSON IPC keeps one message mechanism but expands every request and response body, constructs large strings in both processes, buffers each request before dispatch, and double-encodes image bytes already represented as Base64 inside RPC JSON. Raw framed pipes retain an explicit versioned protocol without relying on Electron and upstream Node.js to share V8 serialization behavior. +**Carry Fetch bodies through JSON IPC as Base64.** This expands request and response bodies, constructs large strings in both processes, and buffers requests before dispatch. Raw framed pipes avoid Base64 expansion but retain a second transport to maintain; the [thin-wrapper decision](2026-09-10-desktop-web-wrapper.md) selects the existing Web HTTP transport. **Bake the product Web UI into Electron.** Independent UI and backend updates would require a new versioned compatibility program. Installing backend and Web UI from the same dsh package preserves the current release binding. @@ -124,7 +117,7 @@ The bundled upstream Node.js and pnpm are expected to add about 35–50 MB compr **Let the desktop profile use CLI-managed packages or plugins.** Either product could change the other’s dependency graph, Cordis version, plugin version, or native module. Desktop rejects package resolution through the CLI profile fallback. -**Separate core and plugin resolution without shared package ownership.** That permits duplicate host modules and uncontrolled peer fallback. The [bundled-runtime decision](2026-09-08-desktop-bundled-runtime-and-external-plugins.md) supplies explicit links and dependency validation for the separate resource and profile directories. +**Separate core and plugin resolution without shared package links.** Plugins with host peers need access to the bundled runtime when pnpm does not install those packages. The [bundled-runtime decision](2026-09-08-desktop-bundled-runtime-and-external-plugins.md) supplies missing profile packages through explicit links while retaining pnpm-installed packages. **Remove non-target Mach-O files from registry packages.** Architecture pruning saves a small amount of runtime space, but packages can deliberately ship several architecture variants and callers can observe their installed file set. Signing every shipped Mach-O object satisfies notarization without inventing a Desktop-specific package layout. @@ -139,7 +132,7 @@ The bundled upstream Node.js and pnpm are expected to add about 35–50 MB compr - A clean offline machine without system Node.js or pnpm starts bundled dsh without installing core dependencies. - The signed application inventories final runtime files; every macOS native file has the release Developer ID, secure timestamp, and hardened runtime, and every Windows artifact has the configured hardware-backed EV signature. - `.dsh/profiles/desktop/node_modules` resolves shared host links and every GUI-installed desktop plugin. -- Every desktop pnpm operation uses the bundled executable and `.dsh/desktop/pnpm/store`; none reads user `PATH`, config, store, or profile `node_modules`. +- Every Desktop package operation uses bundled pnpm with the user’s normal environment and profile configuration. - The Electron-only GUI installs, removes, and updates ordinary npm plugin packages without exposing raw pnpm arguments. - The backend and browser application cannot mutate desktop packages. - npm/CLI dsh and Electron never resolve or install plugins from each other's `node_modules`. @@ -147,7 +140,7 @@ The bundled upstream Node.js and pnpm are expected to add about 35–50 MB compr - Package or Host failures retain partial profile changes and expose recovery controls; no automatic profile rollback is promised. - One Desktop version binds Electron and dsh; every dsh update arrives through one Electron update dialog and one user-visible restart. - Shared `.dsh` data rejects incompatible readers before migration or mutation. -- No loopback listener is opened, and the sandboxed renderer cannot access arbitrary filesystem or Electron APIs. +- The Web application owns HTTP authentication and serving; the sandboxed renderer cannot access arbitrary filesystem or Electron APIs. - Workspace development runs current built code without downloading release resources, while unpacked-package verification retains the production installation path. - Windows release packaging requires the validated SignTool, EV token, matching public leaf certificate, Token Password, and explicit key container; it never falls back to an unsigned artifact or an exportable key file. - A target update cannot expose new channel metadata until the completed signed build and every referenced artifact pass release validation; retained historical artifacts remain available for differential updates. @@ -166,16 +159,16 @@ The bundled upstream Node.js and pnpm are expected to add about 35–50 MB compr ## Risks -Plugin lifecycle scripts execute third-party code. The allowed registry, package policy, exact versions, integrity, `allowBuilds`, and diagnostics require security review before GUI installation ships. +Plugin lifecycle scripts execute third-party code. The profile’s `allowBuilds` configuration determines which builds may execute. -Updating the bound dsh can invalidate plugin peer dependencies or native modules. Reconciliation validates changed dependencies and rebuilds native packages; failures require explicit repair through the recovery UI. +Updating the bound dsh can invalidate plugin peer dependencies or native modules. Installed plugin files remain in place; loading failures require explicit repair through the recovery UI. An npm-installed dsh and desktop dsh may have different versions while sharing durable data. Each shared owner must enforce its format version and process lock before reading, migrating, or writing. -Interrupted package operations retain a pending marker. Installed-artifact tests must verify that a later launch retries the locked installation and approved native builds. +Interrupted package operations retain partial changes. Recovery retries the actual Host or permits explicit plugin repair without an automatic package reinstall. Code signing, notarization, and update hosting require production release infrastructure. Repository tests alone cannot complete that qualification. ## Related proposals -The [bundled-runtime decision](2026-09-08-desktop-bundled-runtime-and-external-plugins.md) supersedes this note’s offline runtime preparation and single-project package ownership. Release identity, signing, portless transport, process ownership, and Electron-only package authorization remain owned here. +The [bundled-runtime decision](2026-09-08-desktop-bundled-runtime-and-external-plugins.md) owns core resources and external plugin dependencies. The [thin-wrapper decision](2026-09-10-desktop-web-wrapper.md) supersedes portless transport and private backend composition. Release identity, signing, process ownership, and Electron-only package authorization remain owned here. diff --git a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md index e67d00417f..e568b53959 100644 --- a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md @@ -16,7 +16,7 @@ DeepSeek Harness 需要一个复用 Web UI 的 Electron 桌面应用。该应用 ## 决策 -交付一个小型 Electron 壳,其中内置上游 Node.js 可执行文件和固定版本的 pnpm。Electron 把私有 Desktop Host 包作为隔离子进程启动;该包组合已安装的 dsh 后端与匹配的客户端图。Fetch 元数据及有界的原始请求与响应分块通过两条带版本的分帧字节管道传递,Node IPC 只承载就绪、致命失败和关闭,Electron 通过 `dsh-app://` 提供经过验证的资源;它不会打开监听端口。每个帧都包含固定标记、类型、单调 stream id、负载长度和经过验证的负载。串行 writer 遵守 pipe drain,请求或响应 stream 施加背压时 reader 会全局暂停,取消会关闭匹配的 stream,已退役 stream 的迟到响应帧保持无效。Connection 插件无需 `webServer` 即可提供与载体无关的 RPC 与 Fetch 注册表,Client Modules 则向 shell-owned carrier 提供与广告内容完全一致的组合 bundle 响应;Web 组合为两者挂载可选 HTTP route。渲染进程保留相同的 Fetch、RPC 与 Remote-stream 格式,子进程载体则避免 Base64 膨胀,也不依赖 Electron 与内置上游 Node.js 之间的 V8 序列化兼容性。发送 shutdown 后,Electron 会关闭自己持有的请求管道写端,以便在等待子进程退出前释放 Windows 上仍在进行的管道读取。该设计沿用 [GUI 分层与 RPC 协议 Agent Note](../../archived/architecture/2026-07-19-gui-layering-and-rpc-protocol.md)中的 Electron 预留。 +交付一个小型 Electron 壳,其中内置上游 Node.js 可执行文件和固定版本 pnpm。[薄壳决策](2026-09-10-desktop-web-wrapper.zh.md)负责 Host 启动与传输:私有 Host 运行共享 Web profile runner,Electron 加载其认证 HTTP URL,子进程 IPC 承载生命周期消息。 Electron 拥有 `.dsh/profiles/desktop` 保留 profile。[内置运行时决策](2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md)负责核心资源存储、外部插件依赖、共享包链接和 profile 协调。私有 Desktop Host 保持独立于公共 CLI 包,且不会发布到 npm。 @@ -28,8 +28,8 @@ Electron 拥有 `.dsh/profiles/desktop` 保留 profile。[内置运行时决策] | Owner | 职责 | |---|---| -| Electron 壳 | 窗口与子进程生命周期、分帧字节管道、生命周期 IPC、自定义协议、保留 desktop profile、插件 GUI、更新协调 | -| 内置 Node.js 与 pnpm | 执行 dsh 并安装桌面项目的精确依赖,不读取用户 `PATH` 或 pnpm 状态 | +| Electron 壳 | 窗口与子进程生命周期、本地壳页面、保留 desktop profile、插件 GUI、更新协调 | +| 内置 Node.js 与 pnpm | 执行 dsh 并安装桌面项目依赖,使用 pnpm 的正常配置 | | Desktop profile | 由内置运行时决策定义的外部插件依赖、已启用 bundle 顺序和共享链接 | | 私有 Desktop Host 包 | 与 dsh 一起安装、但不进入公共 CLI 包或 npm 发布的 Electron 专用子进程入口与组合 overlay | | 已安装 dsh 包 | 后端、匹配的 Web UI、启动 manifest、客户端包和产品行为 | @@ -42,18 +42,11 @@ Electron 拥有 `.dsh/profiles/desktop` 保留 profile。[内置运行时决策] ```text ~/.dsh/ - desktop/ - pnpm/ - store/ - cache/ - state/ - config/ profiles/ desktop/ package.json pnpm-lock.yaml lock - desktop-packages-pending pnpm-workspace.yaml desktop-runtime-state.json node_modules/ @@ -61,7 +54,7 @@ Electron 拥有 `.dsh/profiles/desktop` 保留 profile。[内置运行时决策] storages/ ``` -`.dsh/profiles/desktop` 是唯一活动桌面 profile。其可执行包归属及允许解析的目录遵循[内置运行时决策](2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md)。插件包内容使用 `.dsh/desktop/pnpm/store`。 +`.dsh/profiles/desktop` 是唯一活动桌面 profile。其可执行包归属及允许解析的目录遵循[内置运行时决策](2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md)。pnpm 根据正常配置选择 store 和缓存。 ## 安装与解析 @@ -81,13 +74,13 @@ Electron 更新只使用一个 `electron-updater` 发布流和签名 `electron-b ## 安全与发布策略 -核心 dsh 和私有 Desktop Host 只来自签名应用的资源树。插件安装接受桌面策略允许的 registry 包规格,不接受原始 pnpm 命令。激活前要求精确版本、锁文件完整性、经过审查的 `allowBuilds` 集合和仅限用户访问的目录权限。 +核心 dsh 和私有 Desktop Host 只来自签名应用的资源树。插件安装把包规格交给 pnpm,包括本地和远程来源,但不接受原始 pnpm 命令。pnpm 负责依赖解析和 profile 的 `allowBuilds` 策略;Host 加载已启用的 bundle。 -Electron 发布产物必须签名;macOS 产物必须公证。发布自动化必须通过明确的环境变量提供应用 ID、macOS Developer ID 限定名、预期 Team ID 与一套完整的 notarytool 凭据。配置加载会拒绝缺失或格式错误的标识符和不完整的公证凭据,macOS 打包还会强制签名,避免证书发现过程静默选择其他已安装身份或生成未签名发布。运行时准备会验证每个内嵌 Mach-O 文件的精确 Authority 与 Team ID,以及时间戳和 hardened-runtime 标记。签名后钩子会执行 Apple 的深度严格应用验证,并要求同一叶证书 Authority 与 Team ID 完全匹配,验证通过后才继续生成产物。Electron-builder 随后公证应用并钉票、签署 DMG。DMG 的 artifact-completion hook 会单独公证每个 DMG 并钉票,再要求其使用配置的身份、具备有效票据并通过 Gatekeeper;只有该 hook 成功,上传事件才会执行。macOS 更新使用签名 ZIP,因此 DMG 不生成 blockmap;否则钉票会让已经生成的 DMG blockmap 失效。自定义协议提供已安装的前端分发目录和活跃模块图点名的客户端文件,并拒绝路径穿越或访问这些根目录之外的内容。插件安装器 API 只对 Electron 拥有的管理 GUI 可用,不存在于浏览器应用或后端 RPC 中。 +Electron 发布产物必须签名;macOS 产物必须公证。发布自动化必须通过明确的环境变量提供应用 ID、macOS Developer ID 限定名、预期 Team ID 与一套完整的 notarytool 凭据。配置加载会拒绝缺失或格式错误的标识符和不完整的公证凭据,macOS 打包还会强制签名,避免证书发现过程静默选择其他已安装身份或生成未签名发布。运行时准备会验证每个内嵌 Mach-O 文件的精确 Authority 与 Team ID,以及时间戳和 hardened-runtime 标记。签名后钩子会执行 Apple 的深度严格应用验证,并要求同一叶证书 Authority 与 Team ID 完全匹配,验证通过后才继续生成产物。Electron-builder 随后公证应用并钉票、签署 DMG。DMG 的 artifact-completion hook 会单独公证每个 DMG 并钉票,再要求其使用配置的身份、具备有效票据并通过 Gatekeeper;只有该 hook 成功,上传事件才会执行。macOS 更新使用签名 ZIP,因此 DMG 不生成 blockmap;否则钉票会让已经生成的 DMG blockmap 失效。共享 Web server 负责前端与客户端模块响应。插件安装器 API 只对 Electron 拥有的管理 GUI 可用,不存在于浏览器应用或后端 RPC 中。 [固定版本的 osx-sign 补丁](../../../../patches/@electron__osx-sign@1.3.3.patch)在两种已发布模块构建中使用 `lstat`,因此 Framework 的文件和目录别名不会触发重复签名。选定的上游版本能够跳过这些别名前,仍需保留该补丁。PAK 文件由外层 bundle 签名记录完整性;逐个签名会增加串行时间戳请求,但不会增加资源完整性保护。Desktop 保留全部语言文件,只跳过其单独签名。可执行代码仍使用 Developer ID 签名、安全时间戳和 hardened runtime。[签名器遍历回归测试](../../../../apps/desktop/tests/macos-signing-walk.spec.ts)使用真实 Framework 别名执行已安装依赖;发布验收仍要求严格应用验证、公证和启动。 -Windows 发布打包通过 `/f` 向已配置且与 SafeNet 兼容的 SignTool 提供 `DSH_DESKTOP_WINDOWS_CER_FILE` 指定的公开 EV 叶证书,并通过必需的 `DSH_DESKTOP_WINDOWS_KEY_CONTAINER` 标识匹配的私钥。证书文件保留在源码仓库之外,私钥仍留在 USB Token 上。electron-builder hook 把每个产物交给采用 CRLF 的 `windows-sign.cmd`;该 CMD 只调用一次 SignTool,并指定 SafeNet `/kc "[{{PIN}}]=容器"` 值与 CSP、SHA-256 文件摘要和 DigiCert SHA-256 RFC 3161 时间戳。hook 不会改用其他 SignTool,也不会重试失败的请求。打包编排不会把任何 `DSH_DESKTOP_WINDOWS_*` 字段传给构建与 运行时准备子进程,只会把证书路径、SignTool 路径、密钥容器和 PIN 传入 electron-builder。签名器在已清理的 CMD 环境中只提供经过校验的签名字段;CMD 会禁用延迟展开,在 SignTool 启动前清除这些字段,并仅在 SignTool 必需的命令行中保留 PIN。所有对外诊断都会替换 PIN,而且只能允许专用构建账号和管理员检查该 runner。签名器会在企业 Code Integrity 检查 electron-builder 的临时 NSIS bootstrap 前先为该可执行文件签名;对于生成的可执行文件,只有证书表条目指向文件末尾之外时,才会在最终签名前清除该条目。SignTool、证书、容器、PIN、Token 或签名不可用时,打包会在产生未签名产物前失败。自定义协议提供已安装的前端分发目录和活跃模块图点名的客户端文件,并拒绝路径穿越或访问这些根目录之外的内容。插件安装器 API 只对 Electron 持有的管理 GUI 可用,不存在于浏览器应用或后端 RPC 中。 +Windows 发布打包通过 `/f` 向已配置且与 SafeNet 兼容的 SignTool 提供 `DSH_DESKTOP_WINDOWS_CER_FILE` 指定的公开 EV 叶证书,并通过必需的 `DSH_DESKTOP_WINDOWS_KEY_CONTAINER` 标识匹配的私钥。证书文件保留在源码仓库之外,私钥仍留在 USB Token 上。electron-builder hook 把每个产物交给采用 CRLF 的 `windows-sign.cmd`;该 CMD 只调用一次 SignTool,并指定 SafeNet `/kc "[{{PIN}}]=容器"` 值与 CSP、SHA-256 文件摘要和 DigiCert SHA-256 RFC 3161 时间戳。hook 不会改用其他 SignTool,也不会重试失败的请求。打包编排不会把任何 `DSH_DESKTOP_WINDOWS_*` 字段传给构建与 运行时准备子进程,只会把证书路径、SignTool 路径、密钥容器和 PIN 传入 electron-builder。签名器在已清理的 CMD 环境中只提供经过校验的签名字段;CMD 会禁用延迟展开,在 SignTool 启动前清除这些字段,并仅在 SignTool 必需的命令行中保留 PIN。所有对外诊断都会替换 PIN,而且只能允许专用构建账号和管理员检查该 runner。签名器会在企业 Code Integrity 检查 electron-builder 的临时 NSIS bootstrap 前先为该可执行文件签名;对于生成的可执行文件,只有证书表条目指向文件末尾之外时,才会在最终签名前清除该条目。SignTool、证书、容器、PIN、Token 或签名不可用时,打包会在产生未签名产物前失败。共享 Web server 负责前端与客户端模块响应。插件安装器 API 只对 Electron 持有的管理 GUI 可用,不存在于浏览器应用或后端 RPC 中。 Windows 打包调用强制设置 `ELECTRON_BUILDER_7Z_FILTER=BCJ`。内置的 7-Zip 24.09 编码器会为 ARM64 PE 文件自动选择 ARM64 过滤器,但 `nsis-resources-3.4.1` 中的 NSIS 解码器会在解压时遗漏这些条目。使用实际 NSIS 插件的原生解压验证表明,自动过滤会丢失两个 `node-pty` ARM64 二进制文件,而 BCJ 可以逐字节还原二者。使用兼容的过滤器能够保留依赖内容与运行时完整性,无需删除特定架构的文件或削弱校验。 @@ -106,17 +99,17 @@ NSIS 先解压到私有的 `7z-out` 目录,再把文件复制到应用目录 | 表面 | 实现 | |---|---| | 壳 | `apps/desktop` 负责 Electron 窗口、受限 preload、自定义协议、子进程生命周期、项目事务、插件 GUI、更新协调和 electron-builder 配置。 | -| 已安装运行时 | 私有 `@deepseek-ai/dsh-desktop-host` 从活跃项目启动无端口桌面组合,并通过经过验证的分帧字节管道流式传输 API 与资源响应。 | +| 已安装运行时 | 私有 `@deepseek-ai/dsh-desktop-host` 调用共享 profile runner,并向 Electron 报告认证 Web URL。 | | 包状态 | 内置 Node.js 执行不可变核心资源;内置 pnpm 只修改 Desktop profile 中的外部插件依赖图。 | | 资格验证 | macOS 打包要求已配置的公司身份与公证凭据可用,在生成清单前验证每个原生运行时文件,验证完整应用签名,并要求应用和 DMG 都完成公证且通过 Gatekeeper。Windows 打包要求已配置的公开证书、SafeNet 私钥容器、Token Password 与 SignTool,并验证生成的每个签名。更新托管、跨上一版本的已安装产物测试和各平台 GUI 录制仍是发布环境门槛。 | -`dev:desktop` 会构建当前 workspace,把已构建 CLI 包、私有 Desktop Host 包及其依赖链接投影为一次性项目,使用隔离的 Harness home,打开 Main、Renderer 和 Host 调试器,并在不准备发布资源的情况下启动未打包 Electron。该模式的链接依赖图不是由 pnpm 安装的桌面项目,因此会禁用包修改。固定的 macOS arm64、macOS x64 与 Windows x64 打包命令会把同一目标传给运行时准备、dsh 准备和 electron-builder;每条命令还提供未封装安装器的变体,用于在生成安装器前验证发布路径。 +`dev:desktop` 会构建当前 workspace,把已构建 CLI 包、私有 Desktop Host 包及其依赖链接投影为一次性项目,使用隔离的 Harness home,打开 Main、Renderer 和 Host 调试器,并在不准备发布资源的情况下启动未打包 Electron。开发运行时为独立的插件 profile 提供工作区链接;插件管理和恢复使用与打包应用相同的流程。固定的 macOS arm64、macOS x64 与 Windows x64 打包命令会把同一目标传给运行时准备、dsh 准备和 electron-builder;每条命令还提供未封装安装器的变体,用于在生成安装器前验证发布路径。 ## 考虑过的替代方案 **使用 Electron 的 Node.js 执行 dsh。** 这可以减小包体积,但会让 dsh 耦合到 Electron 的 Node 补丁、fuse、原生 ABI、TLS 行为和进程生命周期。内置上游 Node.js 可以让 dsh 继续使用其受支持运行时。 -**通过 JSON IPC 以 Base64 承载 Fetch 消息体。** JSON IPC 可以只保留一种消息机制,但会膨胀每个请求与响应消息体、在两个进程中构造大字符串、在分派前缓冲完整请求,还会再次编码 RPC JSON 中已经表示为 Base64 的图片字节。原始分帧管道保留明确的带版本协议,同时不要求 Electron 与上游 Node.js 共享 V8 序列化行为。 +**通过 JSON IPC 以 Base64 承载 Fetch 消息体。** 这会膨胀请求与响应消息体、在两个进程中构造大字符串,并在分派前缓冲请求。原始分帧管道避免 Base64 膨胀,但仍需维护第二套传输;[薄壳决策](2026-09-10-desktop-web-wrapper.zh.md)选择已有的 Web HTTP 传输。 **把产品 Web UI 永久打包进 Electron。** 独立 UI 与后端更新需要新的版本化兼容计划。从同一个 dsh 包安装后端与 Web UI 可以保持当前发布绑定。 @@ -124,7 +117,7 @@ NSIS 先解压到私有的 `7z-out` 目录,再把文件复制到应用目录 **让桌面 profile 使用 CLI 管理的包或插件。** 任一产品都可能改变另一产品的依赖图、Cordis 版本、插件版本或原生模块。Desktop 拒绝通过 CLI profile 回退目录解析包。 -**分离核心与插件解析,却不明确共享包归属。** 这会允许宿主模块重复以及不可控的 peer 回退。[内置运行时决策](2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md)为分离的资源和 profile 目录提供明确链接及依赖验证。 +**分离核心与插件解析,却不提供共享包链接。** pnpm 未安装宿主 peer 包时,插件需要访问内置运行时。[内置运行时决策](2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md)通过明确链接提供 profile 缺失的包,同时保留 pnpm 安装的包。 **从 registry 包删除非目标 Mach-O 文件。** 架构裁剪可以节省少量 运行时空间,但包可能有意附带多个架构变体,调用方也可以观察安装后的文件集。签署每个实际携带的 Mach-O 对象,无需发明 Desktop 专属包布局就能满足公证要求。 @@ -139,7 +132,7 @@ NSIS 先解压到私有的 `7z-out` 目录,再把文件复制到应用目录 - 没有系统 Node.js 或 pnpm 的干净离线机器能够启动内置 dsh,无需安装核心依赖。 - 签名应用记录最终运行时文件清单;每个 macOS 原生文件都具有发布 Developer ID、安全时间戳和 hardened runtime,每个 Windows 产物都具有配置的硬件 EV 签名。 - `.dsh/profiles/desktop/node_modules` 能解析共享宿主链接和每个通过 GUI 安装的桌面插件。 -- 每个桌面 pnpm 操作都使用内置可执行文件和 `.dsh/desktop/pnpm/store`;不读取用户 `PATH`、配置、store 或 profile `node_modules`。 +- 每次 Desktop 包操作都使用内置 pnpm,并遵循用户的正常环境与 profile 配置。 - Electron-only GUI 安装、删除和更新普通 npm 插件包,而不暴露原始 pnpm 参数。 - 后端与浏览器应用不能修改桌面包。 - npm/CLI dsh 与 Electron 绝不从对方的 `node_modules` 解析或安装插件。 @@ -147,7 +140,7 @@ NSIS 先解压到私有的 `7z-out` 目录,再把文件复制到应用目录 - 包操作或 Host 失败后保留部分 profile 修改,并提供恢复控件;不承诺自动回滚 profile。 - 一个 Desktop 版本绑定 Electron 与 dsh;每次 dsh 更新都通过一个 Electron 更新弹窗交付,并产生一次用户可见的重启。 - 共享 `.dsh` 数据在迁移或修改前拒绝不兼容的读取方。 -- 不打开回环监听端口,沙箱渲染进程不能访问任意文件系统或 Electron API。 +- Web 应用负责 HTTP 认证与服务;沙箱渲染进程不能访问任意文件系统或 Electron API。 - Workspace 开发无需下载发布资源即可运行当前已构建代码,未封装安装器的应用验证仍保留生产安装路径。 - Windows 发布打包要求已验证的 SignTool、EV Token、匹配的公开叶证书、Token Password 和明确的密钥容器,绝不会回退到未签名产物或可导出的密钥文件。 - 目标更新只有在已完成签名的构建及其引用的每个产物通过发布校验后才能暴露新频道元数据;保留的历史产物继续供差分更新使用。 @@ -166,16 +159,16 @@ NSIS 先解压到私有的 `7z-out` 目录,再把文件复制到应用目录 ## 风险 -插件生命周期脚本会执行第三方代码。在 GUI 安装功能交付前,获准 registry、包策略、精确版本、完整性、`allowBuilds` 和诊断都需要安全评审。 +插件生命周期脚本会执行第三方代码。profile 的 `allowBuilds` 配置决定哪些构建获准执行。 -更新绑定的 dsh 可能使插件 peer dependency 或原生模块失效。校准会验证变化的依赖并重建原生包;失败后需要通过恢复 UI 显式修复。 +更新绑定的 dsh 可能使插件 peer 依赖或原生模块不兼容。已安装插件文件保留原位;加载失败需要通过恢复 UI 显式修复。 通过 npm 安装的 dsh 与桌面 dsh 可能在共享持久化数据时使用不同版本。每个共享 owner 都必须在读取、迁移或写入前执行格式版本与进程锁。 -中断的包操作保留未完成标记。已安装产物测试必须验证后续启动会重试锁定依赖的安装和获准的原生构建。 +包操作中断会保留部分变更。恢复操作重试实际 Host,或允许显式修复插件,不会自动重新安装包。 代码签名、公证和更新托管需要生产发布基础设施。只运行仓库测试不能完成这些认证。 ## 相关提案 -[内置运行时决策](2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md)取代本记录的离线 运行时准备与单项目包归属决策。发布身份、签名、无端口传输、进程归属及仅限 Electron 的包授权仍由本记录负责。 +[内置运行时决策](2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md)负责核心资源与外部插件依赖。[薄壳决策](2026-09-10-desktop-web-wrapper.zh.md)取代无端口传输与私有后端组合。发布身份、签名、进程归属及仅限 Electron 的包授权仍由本记录负责。 diff --git a/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.i18n.yaml index bd9e5a5bf2..098306b93a 100644 --- a/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.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-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 +2026-09-08-desktop-bundled-runtime-and-external-plugins.md: e36e67313b5319416dab0ce354d7e483d66d7900 +2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md: b0122ae97a79b33e26e653ba9a8b7f3756d1ff93 diff --git a/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.md b/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.md index 581a4ad311..e36e67313b 100644 --- a/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.md +++ b/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.md @@ -16,33 +16,33 @@ Separate package directories can load duplicate Cordis or service modules. Retai [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. +This note owns core resource storage and external plugin dependencies. The [packaging decision](2026-08-25-electron-desktop-packaging-and-updates.md) retains release identity, signing, process ownership, and Electron-only plugin authorization. The [thin-wrapper decision](2026-09-10-desktop-web-wrapper.md) owns shared Web boot and HTTP transport. ## 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. +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, inherits the user environment. 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. +Every first-party package in the dsh and private Host production closures is shared. The profile supplies missing packages through directory symlinks to those resources, or junctions on Windows; pnpm-installed packages take precedence. Links resolve to real host package directories under normal Node resolution. Host and plugin imports that resolve through these links 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. +External plugins use normal Node package resolution. Desktop does not recursively check peer versions, duplicate packages, linked packages, or ancestor dependency resolution. These checks duplicate package-manager and loader responsibilities and reject pnpm-supported installation sources. Shared host links remain available, but a plugin can resolve another installed copy; incompatible plugins may fail during Host startup and require recovery through the independent shell UI. 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. +The profile manifest records pnpm-installed 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 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. +First launch creates profile metadata and host links without running pnpm, preserving unrelated files. Compatible release changes or application relocation refresh links in place. Node version, platform, or architecture changes preserve installed plugins; pnpm and the loader report installation and compatibility failures. 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. +Dependency mutations use ordinary pnpm add and remove commands, including their configured lifecycle scripts. Installation sources and dependency resolution belong to pnpm. Bundle declarations select automatic activation; patch validation belongs to the bundle loader. Plain dependencies remain installed without activation. The bundled pnpm reads normal user and profile settings, including registry and build permissions. Desktop supplies no runtime build allowlist, strict-build setting, version-range restriction, or fixed profile identity. Unreadable package metadata does not prevent listing, disabling, or removing a dependency. Development uses the same manager against a separate plugin profile, with workspace packages supplied by the development runtime. -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. +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 explicit recovery. 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. +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. ## Alternatives considered @@ -58,4 +58,4 @@ Full runtime verification belongs to packaging. Startup reads the descriptor, ch 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. +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, runtime changes without automatic reinstalls, 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. diff --git a/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md b/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md index fbbb25a4a3..b0122ae97a 100644 --- a/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md @@ -16,33 +16,33 @@ Desktop 初始化时安装核心依赖图,会重复发布构建器已经完成 [运行时准备](../../../../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 的插件授权。没有现有记录被完全取代或归档。 +本记录负责核心资源存储与外部插件依赖。[打包决策](2026-08-25-electron-desktop-packaging-and-updates.zh.md)保留发布身份、签名、进程归属和仅限 Electron 的插件授权。[薄壳决策](2026-09-10-desktop-web-wrapper.zh.md)负责共享 Web 启动与 HTTP 传输。 ## 包归属 资源描述文件记录精确发布版本、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 包和外部插件目录保留各自的文件。源码调试导航由开发包提供。 +[桌面文件规则](../../../../apps/desktop/scripts/runtime-file-policy.ts)在生产 npm 依赖安装之后、原生签名或描述文件生成之前执行。npm 发布列表服务于库的使用者,可以包含声明、map、测试和原生构建输入,不能直接表示桌面进程需要哪些文件。桌面副本排除声明和已识别的 source map,因为 Host 执行 JavaScript 和生成的 Typert 产物,继承用户环境。已发布的 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 条件导出仍是不同入口;链接不能合并包的两套实现。 +dsh 与私有 Host 生产闭包中的每个第一方包都共享。profile 通过指向这些资源包的目录软链接提供缺失的包,在 Windows 上使用 junction;pnpm 安装的包优先。正常 Node 解析会把链接解析到实际宿主包目录。通过这些链接解析的宿主与插件导入对每个已解析导出共享同一模块实例。不同的 ESM 与 CommonJS 条件导出仍是不同入口;链接不能合并包的两套实现。 -外部插件把共享宿主包声明为 peer。普通依赖由插件拥有,可以不同于 dsh 使用的版本。验证拒绝已启用插件的不兼容 peer、共享包的嵌套或别名副本、私有包链接,以及通过 CLI 或其他祖先目录解析依赖。如果第三方包需要宿主范围的实例身份,必须明确加入运行时共享清单;版本号相同并不足够。 +外部插件使用正常的 Node 包解析。Desktop 不递归检查 peer 版本、重复包、链接包或祖先目录依赖解析。这些检查重复了包管理器和加载器的职责,并拒绝 pnpm 支持的安装来源。共享宿主链接仍然可用,但插件可以解析到另一个已安装副本;不兼容插件可能在 Host 启动时失败,需要通过独立的桌面壳 UI 恢复。如果第三方包需要宿主范围的实例身份,必须明确加入运行时共享清单;版本号相同并不足够。 -profile manifest 分别记录精确的已安装插件依赖和已启用 bundle 列表。停用插件会保留其包、锁文件条目和用户配置。共享链接是 Desktop 拥有的派生状态,独立于 pnpm 记录;包管理器操作不携带这些链接,随后 Desktop 重建并验证它们。 +profile manifest 分别记录pnpm 安装的依赖和已启用 bundle 列表。停用插件会保留其包、锁文件条目和用户配置。共享链接是 Desktop 拥有的派生状态,独立于 pnpm 记录;包管理器操作不携带这些链接,随后 Desktop 重建它们。 ## 事务与升级 -首次启动创建 profile 元数据和宿主链接,不运行 pnpm,并保留无关文件。兼容的发布变化或应用移动会直接刷新链接并验证已启用的 peer。Node 版本、平台或架构变化时,会重新安装锁定的插件依赖图并运行获准的原生构建。 +首次启动创建 profile 元数据和宿主链接,不运行 pnpm,并保留无关文件。兼容的发布变化或应用移动会直接刷新链接。Node 版本、平台或架构变化时保留已安装插件;安装和兼容性错误由 pnpm 与加载器报告。 共享包目录使用原生规范路径识别。Windows 启动器可能改变路径大小写而不移动应用;字符串相等判断会触发不必要的 profile 准备。profile 清理在移除真实目录前,显式解除每一个嵌套目录链接。Windows 夹具在 Electron 44 下复现了递归 `fs.rmSync` 沿嵌套 junction 删除目标文件,而内置上游 Node 24.17 会保留它们。因此清理验收包含真实 Electron 运行时;仅在 Node 下测试不能证明目标文件会保留。 -依赖修改先禁用脚本安装,验证插件依赖图和宿主链接,运行经过审查的待执行生命周期构建,再次验证。这允许已批准的原生依赖解析宿主 peer,同时阻止意外的重复宿主包进入启动过程。`allowBuilds` 策略保持明确;不受支持且需要构建的依赖会使事务失败。 +依赖修改使用普通的 pnpm add 和 remove 命令,并遵循其生命周期脚本配置。安装来源和依赖解析由 pnpm 负责。bundle 声明决定自动启用;patch 验证由 bundle 加载器负责。普通依赖安装后不自动启用。内置 pnpm 读取正常的用户和 profile 设置,包括 registry 和构建权限。Desktop 不提供运行时构建许可列表、严格构建设置、版本范围限制或固定 profile 身份。包元数据不可读时,仍可列出、禁用或删除依赖。开发模式使用同一管理器操作独立的插件 profile,工作区包由开发运行时提供。 -Desktop 在包修改前停止 Host,并等待 pnpm 退出后再重启它。[直接修改决策](2026-09-09-desktop-in-place-profile.zh.md)规定部分失败和持久重试状态的处理方式。记录的宿主链接用于识别自有目录,与包操作是否完成相互独立。 +Desktop 在包修改前停止 Host,并等待 pnpm 退出后再重启它。[直接修改决策](2026-09-09-desktop-in-place-profile.zh.md)规定部分失败和显式恢复的处理方式。记录的宿主链接用于识别自有目录,与包操作是否完成相互独立。 -[立即显示窗口决策](2026-09-09-desktop-immediate-window-and-direct-start.zh.md)规定实际 Host 启动和主窗口恢复。用户可以更新、删除、禁用或重新启用插件并重试启动。不兼容插件不会被静默删除或自动降级。每次后端启动都要求当前运行时标识。 +[立即显示窗口决策](2026-09-09-desktop-immediate-window-and-direct-start.zh.md)规定实际 Host 启动和主窗口恢复。用户可以更新、删除、禁用或重新启用插件并重试启动。不兼容插件不会被静默删除或自动降级。 ## 考虑过的替代方案 @@ -58,4 +58,4 @@ Desktop 在包修改前停止 Host,并等待 pnpm 退出后再重启它。[直 首次启动和兼容升级不安装核心包。元数据检查和后端加载仍需要启动时间;没有测量前,不声称发布启动延迟或下载体积改善。插件保留以宿主 API 和原生运行时兼容为条件,条件不满足时提供可见的恢复入口。 -[Desktop README](../../../../apps/desktop/README.zh.md)负责操作说明。定向测试覆盖真实 pnpm 安装与已批准构建、共享 ESM 实例身份、私有依赖版本、应用移动、停用插件、原生重建选择、激活失败和事务锁。签名安装产物升级、macOS 公证、Windows junction 与原生行为、发布体积与启动基准,以及真实模型 GUI 录制仍是发布环境验收要求;单元夹具不能替代这些验证。 +[Desktop README](../../../../apps/desktop/README.zh.md)负责操作说明。定向测试覆盖真实 pnpm 安装与已批准构建、共享 ESM 实例身份、私有依赖版本、应用移动、停用插件、运行时变化时保留插件、激活失败和事务锁。签名安装产物升级、macOS 公证、Windows junction 与原生行为、发布体积与启动基准,以及真实模型 GUI 录制仍是发布环境验收要求;单元夹具不能替代这些验证。 diff --git a/.agents/notes/implemented/architecture/2026-09-09-desktop-immediate-window-and-direct-start.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-09-desktop-immediate-window-and-direct-start.i18n.yaml index aa2dec8161..1aff37d978 100644 --- a/.agents/notes/implemented/architecture/2026-09-09-desktop-immediate-window-and-direct-start.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-09-desktop-immediate-window-and-direct-start.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-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 +2026-09-09-desktop-immediate-window-and-direct-start.md: a03f3f02de88db3bdc3362a75e82b6356e44c6b4 +2026-09-09-desktop-immediate-window-and-direct-start.zh.md: e82c6677577fa963df5f8b0a61cb21fa15e66bc7 diff --git a/.agents/notes/implemented/architecture/2026-09-09-desktop-immediate-window-and-direct-start.md b/.agents/notes/implemented/architecture/2026-09-09-desktop-immediate-window-and-direct-start.md index 1c2209c044..a03f3f02de 100644 --- a/.agents/notes/implemented/architecture/2026-09-09-desktop-immediate-window-and-direct-start.md +++ b/.agents/notes/implemented/architecture/2026-09-09-desktop-immediate-window-and-direct-start.md @@ -14,9 +14,9 @@ Waiting for backend readiness leaves users without a window during profile prepa 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. +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 with loaded runtime metadata and available resources, including in development mode. 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. +Desktop starts the actual Host through the [shared Web runner](2026-09-10-desktop-web-wrapper.md) after preparing the profile in place. Readiness supplies the authenticated URL loaded by the main window. Package mutations retain pnpm lifecycle scripts 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. diff --git a/.agents/notes/implemented/architecture/2026-09-09-desktop-immediate-window-and-direct-start.zh.md b/.agents/notes/implemented/architecture/2026-09-09-desktop-immediate-window-and-direct-start.zh.md index 49b08e4eee..e82c667757 100644 --- a/.agents/notes/implemented/architecture/2026-09-09-desktop-immediate-window-and-direct-start.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-09-desktop-immediate-window-and-direct-start.zh.md @@ -14,9 +14,9 @@ profile 修改与恢复遵循[直接修改 profile 决策](2026-09-09-desktop-in Electron 在 profile 校准或 Host 启动前创建带本地加载页的主窗口。该页面仅依赖已打包的壳资源,并通过自有 preload 接收 starting、ready 或 error 状态。就绪后在同一窗口加载产品 UI;启动失败时显示诊断和可用恢复操作。加载期间关闭窗口会取消后续启动工作,并等待正在启动的子进程退出。 -主窗口提供恢复操作,因为失败的 Host 无法提供自身控件。错误页保留诊断、重启和重装指导。只有已打包应用加载了运行时元数据且资源可用时,才提供禁用插件和重置 Desktop。重置会删除 profile 中除所持锁文件外的所有内容,不保留备份;共享产品数据和 Harness-home 环境文件保持完整。profile 目录保持原位,避免清理期间另一事务获取替代锁。preload 不可用时,独立恢复控件使用被拦截的表单导航。渲染进程崩溃会使导航缓存失效,以重新加载启动页。 +主窗口提供恢复操作,因为失败的 Host 无法提供自身控件。错误页保留诊断、重启和重装指导。加载了运行时元数据且资源可用时,包括开发模式,才提供禁用插件和重置 Desktop。重置会删除 profile 中除所持锁文件外的所有内容,不保留备份;共享产品数据和 Harness-home 环境文件保持完整。profile 目录保持原位,避免清理期间另一事务获取替代锁。preload 不可用时,独立恢复控件使用被拦截的表单导航。渲染进程崩溃会使导航缓存失效,以重新加载启动页。 -Desktop 直接准备 profile 后启动实际 Host,不另行启动健康检查后端。包修改保留依赖验证、获准生命周期构建、运行时标识检查和锁。失败后保留部分修改,供显式修复;不自动回滚 profile。 +Desktop 原位准备 profile 后,通过[共享 Web runner](2026-09-10-desktop-web-wrapper.zh.md)启动实际 Host。就绪消息提供主窗口加载的认证 URL。包变更保留 pnpm 生命周期脚本与锁。失败保留部分变更以供显式修复,不会自动回滚 profile。 本决策部分取代[打包决策](2026-08-25-electron-desktop-packaging-and-updates.zh.md)和[内置运行时决策](2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md)中的 staging 后端探针与延迟创建主窗口。这两份记录仍保留发布、签名、传输、资源归属与依赖事务的理由。完整运行时文件验证仍属于打包操作。 diff --git a/.agents/notes/implemented/architecture/2026-09-09-desktop-in-place-profile.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-09-desktop-in-place-profile.i18n.yaml index 071c6eb3c0..efab435b0d 100644 --- a/.agents/notes/implemented/architecture/2026-09-09-desktop-in-place-profile.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-09-desktop-in-place-profile.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-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 +2026-09-09-desktop-in-place-profile.md: e91ee4c04cfab07e70e222f34e92ece7766bf5b4 +2026-09-09-desktop-in-place-profile.zh.md: 6846b0fbf8f0ae8c44659735817c4e66d7abdf9d diff --git a/.agents/notes/implemented/architecture/2026-09-09-desktop-in-place-profile.md b/.agents/notes/implemented/architecture/2026-09-09-desktop-in-place-profile.md index 9a221bb334..e91ee4c04c 100644 --- a/.agents/notes/implemented/architecture/2026-09-09-desktop-in-place-profile.md +++ b/.agents/notes/implemented/architecture/2026-09-09-desktop-in-place-profile.md @@ -10,13 +10,13 @@ Staging preserves an old plugin installation but adds profile copying, directory ## 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. +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 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. +This supersedes staging and rollback in [the packaging decision](2026-08-25-electron-desktop-packaging-and-updates.md), [the bundled-runtime decision](2026-09-08-desktop-bundled-runtime-and-external-plugins.md), and [the immediate-window decision](2026-09-09-desktop-immediate-window-and-direct-start.md). Host boot follows the [thin-wrapper decision](2026-09-10-desktop-web-wrapper.md); release, module ownership, and window lifecycle remain separate decisions. -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. +Desktop delegates installation and lifecycle scripts to pnpm, without a pending-operation startup gate, frozen-lockfile reinstall, or automatic rebuild. Failed package operations preserve partial changes and leave disable, remove, reset, and startup retry available. The Host inherits the user environment, and profiles may use directory links. An unchanged legacy Desktop-generated pnpm configuration is replaced with the Web defaults; customized configuration remains user-owned. ## Alternatives considered diff --git a/.agents/notes/implemented/architecture/2026-09-09-desktop-in-place-profile.zh.md b/.agents/notes/implemented/architecture/2026-09-09-desktop-in-place-profile.zh.md index 53a744ae9e..6846b0fbf8 100644 --- a/.agents/notes/implemented/architecture/2026-09-09-desktop-in-place-profile.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-09-desktop-in-place-profile.zh.md @@ -10,13 +10,13 @@ staging 能保留旧插件安装,但增加 profile 复制、目录移动、恢 ## 决策 -Desktop 停止 Host 后直接修改当前 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)。其他发布、模块实例和窗口生命周期决策继续有效。 +本记录取代[打包决策](2026-08-25-electron-desktop-packaging-and-updates.zh.md)、[内置运行时决策](2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md)及[立即显示窗口决策](2026-09-09-desktop-immediate-window-and-direct-start.zh.md)中的暂存与回滚。Host 启动遵循[薄壳决策](2026-09-10-desktop-web-wrapper.zh.md);发布、模块归属与窗口生命周期仍由各自决策负责。 -持久的 `desktop-packages-pending` 标记先于包写入或原生运行时重建,仅在安装、获准构建和验证成功后删除。后续启动发现该标记时,会重新安装锁定的依赖图并重试待执行构建,即使记录的运行时元数据已经匹配。普通未变化的启动复用 profile,不扫描插件依赖图;包修改和运行时校准保留验证。 +Desktop 将安装和生命周期脚本交给 pnpm,不设置待完成操作启动门禁、不强制按锁文件重装,也不自动重建。包操作失败会保留部分变更,仍可禁用、删除、重置和重试启动。Host 继承用户环境,profile 可以使用目录链接。未经修改的旧版 Desktop 生成 pnpm 配置替换为 Web 默认值;自定义配置仍由用户管理。 ## 考虑过的替代方案 diff --git a/.agents/notes/implemented/architecture/2026-09-10-desktop-web-wrapper.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-10-desktop-web-wrapper.i18n.yaml new file mode 100644 index 0000000000..c1f7e4c099 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-10-desktop-web-wrapper.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-10-desktop-web-wrapper.md +2026-09-10-desktop-web-wrapper.md: 7a79f50763270058cd3a611f6b158209d138e6e3 +2026-09-10-desktop-web-wrapper.zh.md: b7c5b3ea7df00b89c59e26115342db2a05c3e837 diff --git a/.agents/notes/implemented/architecture/2026-09-10-desktop-web-wrapper.md b/.agents/notes/implemented/architecture/2026-09-10-desktop-web-wrapper.md new file mode 100644 index 0000000000..7a79f50763 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-10-desktop-web-wrapper.md @@ -0,0 +1,31 @@ +# Agent Note: Run Desktop through the shared Web application + +Status: implemented + +English | [中文](2026-09-10-desktop-web-wrapper.zh.md) + +## Problem + +Separate Desktop composition and request transport require their own configuration, module loading, streaming, and asset-serving behavior. Those implementations can omit Web features even when the renderer is shared. Desktop needs its own installation and native controls without maintaining a second application backend. + +## Decision + +The private Desktop Host invokes the CLI's shared profile runner against the independently owned Desktop profile. The complete Web composition owns authentication, HTTP routes, client assets, RPC, and response streaming. Electron loads the authenticated URL reported by the child. Child IPC carries readiness and shutdown; application requests travel directly over HTTP. + +The shared runner owns profile and Harness-home patches, proxy setup, telemetry defaults, module fallbacks, configuration reload, and application lifecycle. Desktop preserves Web defaults and user configuration. Native directory selection is a Desktop overlay with an observable UI purpose; shell windows, menus, plugin management, recovery, and updates remain Electron responsibilities. + +The [bundled-runtime decision](2026-09-08-desktop-bundled-runtime-and-external-plugins.md) retains separate runtime and plugin storage, bundled Node.js and pnpm, and explicit package ownership. The [in-place decision](2026-09-09-desktop-in-place-profile.md) retains package transactions and partial-failure recovery. The public CLI continues to reject the reserved Desktop profile. + +This partially supersedes the private composition and portless transport in the [packaging decision](2026-08-25-electron-desktop-packaging-and-updates.md). That design avoided listening ports and used framed byte pipes to avoid Base64 expansion and cross-version V8 serialization. Shared HTTP gives up the portless guarantee and assigns serving and authentication to the existing Web implementation. Release identity, signing, process ownership, and native shell features remain active decisions. + +## Alternatives considered + +**Maintain a second backend composition and carrier.** This permits a portless application, but every Web route, reload behavior, authentication change, and stream capability needs a Desktop implementation or explicit omission. Reintroduction requires a desktop product requirement that cannot use the Web implementation and justifies that continuing cost. + +**Merge CLI and Desktop plugin installations.** Shared boot code does not require shared executable dependencies. Separate installations allow independently qualified releases and plugin versions while their existing data owners govern shared sessions and settings. + +## Consequences + +Desktop inherits Web features through the same boot and serving path. HTTP listener ownership and authentication remain part of application startup, and Electron must load the ready URL instead of assuming a port or translating requests. The independent loading and recovery window remains available before the Web application starts. + +Verification requires shared-runner coverage, authenticated HTTP asset and API delivery, configuration reload, native directory selection, child shutdown, and recovery after plugin failure. Installed-platform and real-model GUI qualification remain distinct from unit tests; this note records no measured startup or transfer improvement. diff --git a/.agents/notes/implemented/architecture/2026-09-10-desktop-web-wrapper.zh.md b/.agents/notes/implemented/architecture/2026-09-10-desktop-web-wrapper.zh.md new file mode 100644 index 0000000000..b7c5b3ea7d --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-10-desktop-web-wrapper.zh.md @@ -0,0 +1,31 @@ +# Agent Note: 通过共享 Web 应用运行 Desktop + +Status: implemented + +[English](2026-09-10-desktop-web-wrapper.md) | 中文 + +## Problem + +独立的 Desktop 组合与请求传输需要分别维护配置、模块加载、流式响应与资源服务行为。即使共享渲染界面,这些实现也可能遗漏 Web 功能。Desktop 需要独立安装与原生控件,但不需要第二套应用后端。 + +## Decision + +私有 Desktop Host 针对独立归属的 Desktop profile 调用 CLI 的共享 profile runner。完整 Web 组合负责认证、HTTP 路由、客户端资源、RPC 与响应流。Electron 加载子进程报告的认证 URL。子进程 IPC 承载就绪与关闭;应用请求直接通过 HTTP 传输。 + +共享 runner 负责 profile 与 Harness-home patch、代理设置、遥测默认值、模块补全、配置重载及应用生命周期。Desktop 保留 Web 默认值与用户配置。原生目录选择是具有可见 UI 用途的 Desktop overlay;壳窗口、菜单、插件管理、恢复及更新仍由 Electron 负责。 + +[内置运行时决策](2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md)保留独立运行时与插件存储、内置 Node.js 和 pnpm,以及明确的包归属。[原位修改决策](2026-09-09-desktop-in-place-profile.zh.md)保留包事务与部分失败恢复。公开 CLI 继续拒绝保留的 Desktop profile。 + +本记录部分取代[打包决策](2026-08-25-electron-desktop-packaging-and-updates.zh.md)中的私有组合与无端口传输。该设计避免监听端口,并使用分帧字节管道避免 Base64 膨胀与跨版本 V8 序列化。共享 HTTP 放弃无端口保证,将服务与认证交给已有 Web 实现。发布身份、签名、进程归属及原生壳功能仍是有效决策。 + +## Alternatives considered + +**维护第二套后端组合与传输。** 这允许应用不监听端口,但每项 Web 路由、重载行为、认证变化和流式能力都需要 Desktop 实现或明确省略。只有无法使用 Web 实现、且足以承担持续维护成本的桌面产品需求,才支持重新引入这种方案。 + +**合并 CLI 与 Desktop 插件安装。** 共享启动代码不要求共享可执行依赖。独立安装允许分别验收发布与插件版本,共享会话和设置则仍由已有数据归属方负责。 + +## Consequences + +Desktop 通过相同启动与服务路径继承 Web 功能。HTTP 监听归属与认证仍属于应用启动,Electron 必须加载就绪 URL,而不是假设端口或转换请求。独立加载与恢复窗口在 Web 应用启动前仍可用。 + +验证需要覆盖共享 runner、认证 HTTP 资源与 API 传输、配置重载、原生目录选择、子进程关闭及插件失败恢复。安装后平台验收与真实模型 GUI 验收独立于单元测试;本记录不声称已测得启动或传输提升。 diff --git a/apps/cli/README.i18n.yaml b/apps/cli/README.i18n.yaml index cfded686cf..08ea5b5f8d 100644 --- a/apps/cli/README.i18n.yaml +++ b/apps/cli/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/cli/README.md -README.md: 2e74ef68cf0b8487083a2e2af0f5175c78ec5212 -README.zh.md: 553f28f3af78b18658701449678de80b086dbb15 +README.md: ea51b2cc9a4f87777f65ed330f40c032f0c5b44c +README.zh.md: c3369afe2ebee06cbd84171902e213df8761b7b8 diff --git a/apps/cli/README.md b/apps/cli/README.md index 2e74ef68cf..ea51b2cc9a 100644 --- a/apps/cli/README.md +++ b/apps/cli/README.md @@ -54,3 +54,5 @@ The [CLI behavior reference](reference/README.md) owns exact layer precedence, f ## Development Production runs require built package and frontend artifacts. From the repository root, run `pnpm run build` separately, then use `pnpm dsh ` to run the TypeScript entry and forward every argument; the [source-execution reference](reference/README.md#source-execution) owns the module-resolution contract. + +The `@deepseek-ai/dsh/profile-boot` export provides the shared profile lifecycle to the Desktop host. A resolved application profile supplies its own installation anchor and profile-local module fallback while retaining the Harness home patch, proxy environment, telemetry switch, patch reload, and bounded shutdown. diff --git a/apps/cli/README.zh.md b/apps/cli/README.zh.md index 553f28f3af..c3369afe2e 100644 --- a/apps/cli/README.zh.md +++ b/apps/cli/README.zh.md @@ -54,3 +54,5 @@ profile 目录包含一个 `package.json`,其中记录树外插件依赖,以 ## 开发 生产运行需要已构建的包与前端产物。请在仓库根目录单独运行 `pnpm run build`,然后使用 `pnpm dsh ` 运行 TypeScript 入口并转发所有参数;模块解析约定以[源码执行参考](reference/README.zh.md#source-execution)为准。 + +`@deepseek-ai/dsh/profile-boot` 导出向 Desktop Host 提供共享 profile 生命周期。已解析的应用 profile 指定自己的安装锚点和 profile 内模块补全,同时沿用 Harness home patch、代理环境、遥测开关、patch 热重载和有界关闭。 diff --git a/apps/cli/package.json b/apps/cli/package.json index d6324bd286..9336d7b4b4 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -15,7 +15,8 @@ "dsh": "lib/bin.js" }, "files": [ - "lib/*.js" + "lib/*.js", + "lib/types/*.d.ts" ], "dsh": { "configTrees": [ @@ -147,5 +148,12 @@ "@types/ws": "8.18.1", "execa": "^10.0.0", "ws": "8.21.0" + }, + "exports": { + "./profile-boot": { + "types": "./lib/types/profile-boot.d.ts", + "default": "./lib/profile-boot.js" + }, + "./lib/*": "./lib/*" } } diff --git a/apps/cli/src/profile-boot.ts b/apps/cli/src/profile-boot.ts index 0715efe1bb..3f2d127c0e 100644 --- a/apps/cli/src/profile-boot.ts +++ b/apps/cli/src/profile-boot.ts @@ -21,6 +21,7 @@ import { boot, composeEntries, healProfilesModuleFallback, + healIsolatedProfileModuleFallback, initProfile, installFailLoud, loadOptionalPatches, @@ -227,9 +228,12 @@ async function composeProfile( name: string, patchFiles: readonly string[], fromDefaultProfile?: string, + resolvedProfile?: ResolvedProfileRuntime, ): Promise { - const profile = prepareProfile(name, true, fromDefaultProfile) - await healProfilesModuleFallback({ installAnchor: INSTALL_ANCHOR, profile }) + const profile = resolvedProfile?.profile ?? prepareProfile(name, true, fromDefaultProfile) + if (resolvedProfile !== undefined) writeFileSync(join(profile.dir, PROFILE_ROOT_FILENAME), PROFILE_ROOT_CONFIG) + if (resolvedProfile === undefined) await healProfilesModuleFallback({ installAnchor: INSTALL_ANCHOR, profile }) + else healIsolatedProfileModuleFallback(resolvedProfile) const homePatches = loadOptionalPatches(NAME, homePatchPath()) ?? [] const overlays = patchFiles.flatMap(file => loadOverlayPatches(NAME, resolve(file))) const bundlePatches = profile.layers.flatMap(layer => layer.patches) @@ -243,12 +247,22 @@ async function composeProfile( return { profile, bundlePatches, homePatches, overlays: composedOverlays } } +/** An application-owned profile and its independent installation fallback. */ +export interface ResolvedProfileRuntime { + /** Profile already loaded from the application's own directory. */ + profile: Profile + /** Absolute package.json path of the application's dsh installation. */ + installAnchor: string +} + /** Options for {@link runProfile}. */ export interface RunProfileOptions { /** This run's frozen environment snapshot, provided before any entry mounts. */ environment: LaunchEnvironmentSnapshot /** The profile name to boot. */ profile: string + /** Loaded application profile; bypasses named profile initialization when supplied. */ + resolvedProfile?: ResolvedProfileRuntime | undefined /** Shipped template used once to initialize a missing profile. */ fromDefaultProfile?: string | undefined /** `--patch` overlay paths, in argv order. */ @@ -278,6 +292,7 @@ function suppressShutdownError(ctx: Context, signal: AbortSignal, error: unknown * mounted plugins (or to a one-shot runner the composition mounts). * @param options - environment snapshot, profile name, overlays, and the booted app's own arguments. * @returns the settled root context and the shutdown controller. + * @throws after disposing startup resources; a cleanup failure retains both errors in an AggregateError. */ export async function runProfile(options: RunProfileOptions): Promise<{ ctx: Context; shutdown: ProcessShutdown }> { // Before the first plugin mounts and before anything can issue a request: Node's fetch ignores the @@ -289,104 +304,119 @@ export async function runProfile(options: RunProfileOptions): Promise<{ ctx: Con (message) => { process.stderr.write(`${NAME}: ${message}\n`) }, ) - const composed = await composeProfile(options.profile, options.patchFiles, options.fromDefaultProfile) const app: { current?: Context } = {} - const appReady = createAppReady() - const shutdown = createProcessShutdown(async () => { - await app.current?.fiber.dispose() - await disposeProxy() - }) - const signalShutdown = new AbortController() - const interrupt = (code: number): void => { - signalShutdown.abort() - shutdown.interrupt(code) - } - // Signals own teardown throughout the startup window, not only after boot() - // settles: an inserted provider can publish before sibling rows finish mounting. - // SIGTERM is a supervisor's ordinary stop request and exits 0 on every - // surface — the launcher does not know whether the app considered its work - // complete; SIGINT is a user interrupt and reports 130. - process.on('SIGTERM', () => { interrupt(0) }) - process.on('SIGINT', () => { interrupt(130) }) - installFailLoud(NAME, process, async () => { - await app.current?.fiber.dispose() - }) - - const rootConfig = join(composed.profile.dir, PROFILE_ROOT_FILENAME) - // Recomposition for the live user layers: bundle layers below, overlays - // above, so a user edit can never displace them. Parsed app arguments are - // not in here at all — they live in app-provided services that survive a - // recomposition. BOTH - // user files are re-read per generation (the HMR watcher hands us only the - // changed file's patches, which one of the reads duplicates — fresh reads - // keep the two watchers from stitching in each other's stale copy). - // Fresh clones per generation: the include pushes `insert` rows into the - // mounted tree BY REFERENCE and later id-targeted patches mutate those - // objects in place. Reusing one parsed patch object across applications - // would bake a user override into the bundle's in-memory insert row, so - // removing the override could never revert the row to the bundle default. - const composeLive = (): PatchOptions[] => structuredClone([ - ...composed.bundlePatches, - ...loadOptionalPatches(NAME, composed.profile.patchPath) ?? [], - ...loadOptionalPatches(NAME, homePatchPath()) ?? [], - ...composed.overlays, - ]) - // Cloned for the same insert-aliasing reason as composeLive: the boot - // application must not mutate the objects later reloads recompose from. - const ctx = await boot(NAME, rootConfig, structuredClone(allPatches(composed)), (hostCtx) => { - app.current = hostCtx - // Before any config-tree entry mounts, so plugins resolve all launch-time - // environment values from the same immutable provenance snapshot. - hostCtx.provide(DSH_LAUNCH_ENVIRONMENT_KEY, options.environment) - // The command line and bounded exit request are launcher facts available - // to every app plugin that injects the argument snapshot. - provideCmdline(hostCtx, { - args: options.args, - exit: code => void shutdown.shutdown(code), - ready: appReady.service, - }) - }) - app.current = ctx - // A live-reload profile can dispose the whole tree while post-boot watcher - // setup is in flight — a signal or appExit. Loader presence and fiber state - // own liveness; the initial check skips a tree that already exited, and the - // catch below re-checks for an exit that landed mid-setup. Startup-frozen - // profiles apply every user layer above but install no HMR fallback or watcher. - if (composed.profile.patchReload === 'live' - && !signalShutdown.signal.aborted - && ctx.fiber.state === FiberState.ACTIVE - && ctx.get('loader') !== undefined) { - try { - // Config-only HMR for the live profile patch layer: dsh-base disables - // module reload by default, so when no profile explicitly enabled that - // service, mount a watch-only instance with no module roots — - // cordis.patch.yml edits stay live without replacing source modules. A - // silent skip would break the documented reload contract. HMR injects - // the timer service, which a bare custom profile may not mount either. - if (ctx.get('hmr') === undefined) { - if (ctx.get('timer') === undefined) { - await ctx.loader.create({ name: '@deepseek-ai/cordis-plugin-timer' }) - } - await ctx.loader.create({ name: '@deepseek-ai/cordis-plugin-hmr', config: { root: [] } }) - } - await watchUserPatches(ctx, { - binName: NAME, - filename: composed.profile.patchPath, - compose: composeLive, - }) - await watchUserPatches(ctx, { - binName: NAME, - filename: homePatchPath(), - compose: composeLive, - }) - } catch (error) { - suppressShutdownError(ctx, signalShutdown.signal, error) + let disposal: Promise | undefined + const dispose = (): Promise => disposal ??= (async () => { + const failures: unknown[] = [] + for (const release of [() => app.current?.fiber.dispose(), disposeProxy]) { + try { await release() } catch (error) { failures.push(error) } } + if (failures.length === 1) throw failures[0] + if (failures.length > 1) throw new AggregateError(failures, 'dsh: profile cleanup failed') + })() + try { + const composed = await composeProfile( + options.profile, options.patchFiles, options.fromDefaultProfile, options.resolvedProfile, + ) + const appReady = createAppReady() + const shutdown = createProcessShutdown(dispose) + const signalShutdown = new AbortController() + const interrupt = (code: number): void => { + signalShutdown.abort() + shutdown.interrupt(code) + } + // Signals own teardown throughout the startup window, not only after boot() + // settles: an inserted provider can publish before sibling rows finish mounting. + // SIGTERM is a supervisor's ordinary stop request and exits 0 on every + // surface — the launcher does not know whether the app considered its work + // complete; SIGINT is a user interrupt and reports 130. + process.on('SIGTERM', () => { interrupt(0) }) + process.on('SIGINT', () => { interrupt(130) }) + installFailLoud(NAME, process, async () => { + await app.current?.fiber.dispose() + }) + + const rootConfig = join(composed.profile.dir, PROFILE_ROOT_FILENAME) + // Recomposition for the live user layers: bundle layers below, overlays + // above, so a user edit can never displace them. Parsed app arguments are + // not in here at all — they live in app-provided services that survive a + // recomposition. BOTH + // user files are re-read per generation (the HMR watcher hands us only the + // changed file's patches, which one of the reads duplicates — fresh reads + // keep the two watchers from stitching in each other's stale copy). + // Fresh clones per generation: the include pushes `insert` rows into the + // mounted tree BY REFERENCE and later id-targeted patches mutate those + // objects in place. Reusing one parsed patch object across applications + // would bake a user override into the bundle's in-memory insert row, so + // removing the override could never revert the row to the bundle default. + const composeLive = (): PatchOptions[] => structuredClone([ + ...composed.bundlePatches, + ...loadOptionalPatches(NAME, composed.profile.patchPath) ?? [], + ...loadOptionalPatches(NAME, homePatchPath()) ?? [], + ...composed.overlays, + ]) + // Cloned for the same insert-aliasing reason as composeLive: the boot + // application must not mutate the objects later reloads recompose from. + const ctx = await boot(NAME, rootConfig, structuredClone(allPatches(composed)), (hostCtx) => { + app.current = hostCtx + // Before any config-tree entry mounts, so plugins resolve all launch-time + // environment values from the same immutable provenance snapshot. + hostCtx.provide(DSH_LAUNCH_ENVIRONMENT_KEY, options.environment) + // The command line and bounded exit request are launcher facts available + // to every app plugin that injects the argument snapshot. + provideCmdline(hostCtx, { + args: options.args, + exit: code => void shutdown.shutdown(code), + ready: appReady.service, + }) + }) + app.current = ctx + // A live-reload profile can dispose the whole tree while post-boot watcher + // setup is in flight — a signal or appExit. Loader presence and fiber state + // own liveness; the initial check skips a tree that already exited, and the + // catch below re-checks for an exit that landed mid-setup. Startup-frozen + // profiles apply every user layer above but install no HMR fallback or watcher. + if (composed.profile.patchReload === 'live' + && !signalShutdown.signal.aborted + && ctx.fiber.state === FiberState.ACTIVE + && ctx.get('loader') !== undefined) { + try { + // Config-only HMR for the live profile patch layer: dsh-base disables + // module reload by default, so when no profile explicitly enabled that + // service, mount a watch-only instance with no module roots — + // cordis.patch.yml edits stay live without replacing source modules. A + // silent skip would break the documented reload contract. HMR injects + // the timer service, which a bare custom profile may not mount either. + if (ctx.get('hmr') === undefined) { + if (ctx.get('timer') === undefined) { + await ctx.loader.create({ name: '@deepseek-ai/cordis-plugin-timer' }) + } + await ctx.loader.create({ name: '@deepseek-ai/cordis-plugin-hmr', config: { root: [] } }) + } + await watchUserPatches(ctx, { + binName: NAME, + filename: composed.profile.patchPath, + compose: composeLive, + }) + await watchUserPatches(ctx, { + binName: NAME, + filename: homePatchPath(), + compose: composeLive, + }) + } catch (error) { + suppressShutdownError(ctx, signalShutdown.signal, error) + } + } + if (!signalShutdown.signal.aborted + && ctx.fiber.state === FiberState.ACTIVE + && ctx.get('loader') !== undefined) { + appReady.commit() + } + return { ctx, shutdown } + } catch (error) { + try { await dispose() } catch (cleanupError) { + throw new AggregateError([error, cleanupError], 'dsh: profile startup and cleanup failed') + } + throw error } - if (!signalShutdown.signal.aborted - && ctx.fiber.state === FiberState.ACTIVE - && ctx.get('loader') !== undefined) { - appReady.commit() - } - return { ctx, shutdown } } diff --git a/apps/cli/tests/resolved-profile-boot.spec.ts b/apps/cli/tests/resolved-profile-boot.spec.ts new file mode 100644 index 0000000000..c3daa0be7c --- /dev/null +++ b/apps/cli/tests/resolved-profile-boot.spec.ts @@ -0,0 +1,156 @@ +/** Application-owned profiles share the named profile launch lifecycle. */ +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { Context } from '@deepseek-ai/cordis' +import { createLaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment' +import { boot, composeEntries, healIsolatedProfileModuleFallback, watchUserPatches, type Profile } from '@deepseek-ai/dsh-app-boot' +import { installProxyFromEnvironment } from '@deepseek-ai/dsh-http-proxy' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { runProfile } from '../src/profile-boot.ts' + +vi.mock('@deepseek-ai/dsh-app-boot', async importOriginal => ({ + ...await importOriginal(), + boot: vi.fn(), + healIsolatedProfileModuleFallback: vi.fn(), + installFailLoud: vi.fn(), + watchUserPatches: vi.fn(), +})) +vi.mock('@deepseek-ai/dsh-http-proxy', () => ({ installProxyFromEnvironment: vi.fn() })) + +const homes: string[] = [] +afterEach(() => { + vi.restoreAllMocks() + vi.unstubAllEnvs() + vi.clearAllMocks() + for (const home of homes.splice(0)) rmSync(home, { recursive: true, force: true }) +}) + +describe('runProfile with an application-owned profile', () => { + it.each(['composition', 'boot', 'watch', 'cleanup', 'tree-cleanup', 'both-cleanups'] as const)('releases startup resources after a %s failure', async (stage) => { + const home = mkdtempSync(join(tmpdir(), 'dsh-profile-startup-failure-')) + homes.push(home) + vi.stubEnv('DSH_HOME', home) + vi.spyOn(process, 'on').mockReturnValue(process) + const ctx = new Context() + ctx.provide('loader', { create: vi.fn() }) + ctx.provide('hmr', {}) + const dispose = vi.spyOn(ctx.fiber, 'dispose') + const failure = new Error('startup failed') + const cleanupFailure = new Error('proxy cleanup failed') + const treeCleanupFailure = new Error('tree cleanup failed') + if (stage === 'tree-cleanup' || stage === 'both-cleanups') dispose.mockRejectedValueOnce(treeCleanupFailure) + const disposeProxy = vi.fn().mockImplementation(() => stage === 'cleanup' || stage === 'both-cleanups' + ? Promise.reject(cleanupFailure) + : Promise.resolve()) + vi.mocked(installProxyFromEnvironment).mockResolvedValue(disposeProxy) + vi.mocked(boot).mockImplementation(async (_name, _root, _patches, setup) => { + await setup?.(ctx) + if (stage === 'boot') throw failure + return ctx + }) + if (stage === 'composition') vi.mocked(healIsolatedProfileModuleFallback).mockImplementationOnce(() => { throw failure }) + if (stage !== 'composition' && stage !== 'boot') vi.mocked(watchUserPatches).mockImplementationOnce(() => { throw failure }) + const profile: Profile = { + name: 'desktop', dir: home, patchPath: join(home, 'cordis.patch.yml'), + patchReload: 'live', patches: [], layers: [], + } + try { + const application = runProfile({ + environment: createLaunchEnvironmentSnapshot([]), profile: 'desktop', patchFiles: [], args: ['--no-open'], + resolvedProfile: { profile, installAnchor: join(home, 'runtime/package.json') }, + }) + if (stage === 'both-cleanups') { + await expect(application).rejects.toMatchObject({ errors: [failure, { errors: [treeCleanupFailure, cleanupFailure] }] }) + } else if (stage === 'tree-cleanup') { + await expect(application).rejects.toMatchObject({ errors: [failure, treeCleanupFailure] }) + } else if (stage === 'cleanup') { + await expect(application).rejects.toMatchObject({ errors: [failure, cleanupFailure] }) + } else { + await expect(application).rejects.toBe(failure) + } + expect(disposeProxy).toHaveBeenCalledOnce() + expect(dispose).toHaveBeenCalledTimes(stage === 'composition' ? 0 : 1) + } finally { + await ctx.fiber.dispose() + } + }) + + it.each(['live', 'startup'] as const)('uses shared layers, %s reload, environment, and shutdown', async (patchReload) => { + const home = mkdtempSync(join(tmpdir(), 'dsh-resolved-profile-')) + homes.push(home) + vi.stubEnv('DSH_HOME', home) + vi.stubEnv('DSH_TELEMETRY_DISABLED', '1') + vi.spyOn(process, 'on').mockReturnValue(process) + const oldExitCode = process.exitCode + const ctx = new Context() + // The real context supplies services; this test substitutes tree mounting and filesystem watchers. + ctx.provide('loader', { create: vi.fn() }) + ctx.provide('hmr', {}) + const dispose = vi.spyOn(ctx.fiber, 'dispose') + const disposeProxy = vi.fn().mockResolvedValue(undefined) + vi.mocked(installProxyFromEnvironment).mockResolvedValue(disposeProxy) + vi.mocked(boot).mockImplementation(async (_name, _root, _patches, setup) => { + await setup?.(ctx) + return ctx + }) + const homePatch = join(home, 'cordis.patch.yml') + const profilePatch = join(home, 'profile.patch.yml') + const overlay = join(home, 'desktop.patch.yml') + writeFileSync(homePatch, '- id: target\n config: { home: true, priority: home }\n') + writeFileSync(profilePatch, '- id: target\n config: { profile: true, priority: profile }\n') + writeFileSync(overlay, '- id: target\n config: { overlay: true, priority: overlay }\n') + writeFileSync(join(home, 'cordis.yml'), '- id: stale\n') + const profile: Profile = { + name: 'desktop', dir: home, patchPath: profilePatch, patchReload, + patches: [{ id: 'target', config: { profile: true, priority: 'profile' } }], + layers: [{ + packageName: 'test-bundle', packageDir: home, patchPath: join(home, 'bundle.yml'), + patches: [{ insert: [ + { id: 'target', name: 'target', config: { bundle: true, priority: 'bundle' } }, + { id: 'session-telemetry-otel', name: 'telemetry' }, + ] }], + }], + } + const environment = createLaunchEnvironmentSnapshot([{ source: 'process', values: { HTTPS_PROXY: 'http://localhost:8080' } }]) + const runtime = { profile, installAnchor: join(home, 'runtime/package.json') } + try { + const { shutdown } = await runProfile({ + environment, profile: 'desktop', resolvedProfile: runtime, + patchFiles: [overlay], args: ['--port', '0', '--no-open'], + }) + expect(installProxyFromEnvironment).toHaveBeenCalledWith(environment, expect.any(Function)) + expect(healIsolatedProfileModuleFallback).toHaveBeenCalledWith({ + profile, installAnchor: runtime.installAnchor, + }) + expect(readFileSync(join(home, 'cordis.yml'), 'utf8')).not.toContain('stale') + expect(ctx.cmdlineArgs!.get()).toEqual(['--port', '0', '--no-open']) + const ready = vi.fn() + ctx.appReady!.onReady(ready) + expect(ready).toHaveBeenCalledOnce() + const patches = vi.mocked(boot).mock.calls[0]![2]! + const rows = composeEntries([patches]) + expect(patches.slice(1, 4)).toEqual([ + { id: 'target', config: { profile: true, priority: 'profile' } }, + { id: 'target', config: { home: true, priority: 'home' } }, + { id: 'target', config: { overlay: true, priority: 'overlay' } }, + ]) + expect(rows.find(row => row.id === 'target')?.config).toEqual({ overlay: true, priority: 'overlay' }) + expect(rows.find(row => row.id === 'session-telemetry-otel')?.disabled).toBe(true) + if (patchReload === 'live') { + expect(vi.mocked(watchUserPatches).mock.calls.map(call => call[1].filename)).toEqual([profilePatch, homePatch]) + writeFileSync(homePatch, '- id: target\n config: { home: updated }\n') + const live = vi.mocked(watchUserPatches).mock.calls[0]![1].compose! + expect(live([])[2]).toMatchObject({ id: 'target', config: { home: 'updated' } }) + } else { + expect(watchUserPatches).not.toHaveBeenCalled() + } + await shutdown.shutdown(0) + expect(dispose).toHaveBeenCalledOnce() + expect(disposeProxy).toHaveBeenCalledOnce() + } finally { + await ctx.fiber.dispose() + process.exitCode = oldExitCode + } + }) +}) diff --git a/apps/cli/tsdown.config.ts b/apps/cli/tsdown.config.ts index cfb50e6af4..e85aadc6e8 100644 --- a/apps/cli/tsdown.config.ts +++ b/apps/cli/tsdown.config.ts @@ -1,13 +1,11 @@ import { defineConfig } from 'tsdown' /** - * The dsh CLI ships one entry: the `bin` referenced by package.json `bin`. - * The root tsdown builds only `lib/types/index.js`, so this override points at - * `lib/types/bin.js` instead; its reachable mode modules bundle with it. + * The dsh CLI ships its command and the profile lifecycle shared with Desktop. * Declarations come from `tsc -b` (dts: false), matching every package. */ export default defineConfig({ - entry: ['lib/types/bin.js'], + entry: ['lib/types/bin.js', 'lib/types/profile-boot.js'], outDir: 'lib', format: ['esm'], platform: 'node', diff --git a/apps/desktop-host/config/desktop.cordis.patch.yml b/apps/desktop-host/config/desktop.cordis.patch.yml index 92f4df6ddf..e60e284606 100644 --- a/apps/desktop-host/config/desktop.cordis.patch.yml +++ b/apps/desktop-host/config/desktop.cordis.patch.yml @@ -1,31 +1,8 @@ -# Electron reuses the browser composition without its network and browser-launch rows. - -- id: web-startup - disabled: true - -- id: webserver - disabled: true - -- id: web-runtime - disabled: true - -- id: client-hmr - disabled: true - -- id: open-in-app - disabled: true - -- id: ui-open-in-app - disabled: true +# Desktop uses the native directory picker in its embedded Web UI. - id: directory-picker disabled: true -- id: connection - inject: - - credentials - config: {} - - insert: - id: directory-picker-native name: '@deepseek-ai/dsh-host-directory-picker-native' diff --git a/apps/desktop-host/package.json b/apps/desktop-host/package.json index 670c35d5f2..6d82f1ff43 100644 --- a/apps/desktop-host/package.json +++ b/apps/desktop-host/package.json @@ -12,17 +12,11 @@ ], "dependencies": { "@deepseek-ai/cordis": "workspace:^", - "@deepseek-ai/cordis-plugin-include": "workspace:^", "@deepseek-ai/dsh": "workspace:^", - "@deepseek-ai/dsh-api-gateway": "workspace:^", "@deepseek-ai/dsh-app-boot": "workspace:^", "@deepseek-ai/dsh-client-connection": "workspace:^", - "@deepseek-ai/dsh-client-modules": "workspace:^", "@deepseek-ai/dsh-client-ui-directory-picker-native": "workspace:^", - "@deepseek-ai/dsh-cmdline": "workspace:^", "@deepseek-ai/dsh-host-directory-picker-native": "workspace:^", - "@deepseek-ai/dsh-host-webserver": "workspace:^", - "@deepseek-ai/dsh-launch-environment": "workspace:^", - "@deepseek-ai/dsh-web-frontend": "workspace:^" + "@deepseek-ai/dsh-host-webserver": "workspace:^" } } diff --git a/apps/desktop-host/src/index.ts b/apps/desktop-host/src/index.ts index 3abebfc3c6..fd8e84efff 100644 --- a/apps/desktop-host/src/index.ts +++ b/apps/desktop-host/src/index.ts @@ -1,591 +1,45 @@ -/** - * Electron child-process entry: boots the desktop project without a listening - * socket and carries API plus validated Web assets over framed byte pipes. - * @module @deepseek-ai/dsh-desktop-host - */ +/** Launch the Desktop profile through the Web application and report its URL to Electron. */ -import { createRequire } from 'node:module' -import { closeSync, createReadStream, createWriteStream, existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from 'node:fs' -import { once } from 'node:events' -import { readFile } from 'node:fs/promises' -import { dirname, extname, join, normalize, resolve, sep } from 'node:path' +import { join } from 'node:path' import { fileURLToPath } from 'node:url' -import type { Context } from '@deepseek-ai/cordis' -import type { PatchOptions } from '@deepseek-ai/cordis-plugin-include' -import { - boot, - composeEntries, - loadLayeredEnv, - loadProfileDirectory, - loadOverlayPatches, -} from '@deepseek-ai/dsh-app-boot' -import { provideCmdline } from '@deepseek-ai/dsh-cmdline' -import { DSH_LAUNCH_ENVIRONMENT_KEY } from '@deepseek-ai/dsh-launch-environment' -import type {} from '@deepseek-ai/dsh-api-gateway' -import type { ConnectionFetchHandler } from '@deepseek-ai/dsh-client-connection' -import type {} from '@deepseek-ai/dsh-client-modules' -import { renderIndexInjections, type IndexInjection } from '@deepseek-ai/dsh-host-webserver' -import { - DESKTOP_HOST_PROTOCOL_VERSION, - DESKTOP_PIPE_CHUNK_BYTES, - DESKTOP_REQUEST_PIPE_FD, - DESKTOP_RESPONSE_PIPE_FD, - DesktopHostRequestDecoder, - encodeDesktopResponseData, - encodeDesktopResponseEnd, - encodeDesktopResponseError, - encodeDesktopResponseStart, - type DesktopHostRequestFrame, -} from './wire.ts' - -export { DESKTOP_HOST_PROTOCOL_VERSION } from './wire.ts' - -/** One request forwarded from Electron's `dsh-app://` handler. */ -export interface DesktopHostFetchCommand { - readonly streamId: number - readonly request: { - readonly url: string - readonly method: string - readonly headers: readonly [string, string][] - } -} - -/** Commands accepted by the desktop child process. */ -export type DesktopHostCommand = { - readonly type: 'shutdown' -} - -/** Events emitted by the desktop child process. */ -export type DesktopHostEvent = { - readonly type: 'ready' - readonly protocolVersion: typeof DESKTOP_HOST_PROTOCOL_VERSION - readonly dshVersion: string -} | { - readonly type: 'fatal' - readonly message: string -} - -/** Controller returned to tests and the self-executing process entry. */ -export interface DesktopHostController { - /** Installed dsh version carried by this host. */ - readonly dshVersion: string - /** Dispatch one custom-protocol request and stream its response to the response pipe. */ - fetch(command: DesktopHostFetchCommand, body: ReadableStream | null): Promise - /** Abort one in-flight request. */ - cancel(streamId: number): void - /** Stop accepting messages and await complete host teardown. */ - dispose(): Promise -} - -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null -} - -function isDesktopHostCommand(message: unknown): message is DesktopHostCommand { - return typeof message === 'object' && message !== null && 'type' in message - && (message as Record).type === 'shutdown' -} - -interface PackageManifest { - readonly name?: string - readonly version?: string -} - -const DESKTOP_PATCH = fileURLToPath(new URL('../config/desktop.cordis.patch.yml', import.meta.url)) -const ROOT_CONFIG = '# Electron desktop composition root; package transactions own this file.\n[]\n' -const ROOT_CONFIG_FILENAME = 'desktop.cordis.yml' -const DESKTOP_STREAM_PATH = '/.dsh/remote-stream' - -const DESKTOP_TRANSPORT_SCRIPT = `globalThis.__DSH_TRANSPORT__={ - ownsHost:true, - async *openStream(endpoint,payload,signal){ - const response=await fetch(${JSON.stringify(DESKTOP_STREAM_PATH)},{ - method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({endpoint,payload}),signal - }) - if(!response.ok||response.body===null)throw new Error('desktop stream transport failed: HTTP '+response.status) - const reader=response.body.getReader(),decoder=new TextDecoder() - let pending='' - for(;;){ - const {done,value}=await reader.read() - pending+=decoder.decode(value,{stream:!done}) - let newline - while((newline=pending.indexOf('\\n'))!==-1){ - const line=pending.slice(0,newline);pending=pending.slice(newline+1) - if(line!=='')yield JSON.parse(line) - } - if(done)break - } - if(pending!=='')yield JSON.parse(pending) - } -}` - -const MIME: Readonly> = { - '.css': 'text/css; charset=utf-8', - '.html': 'text/html; charset=utf-8', - '.js': 'text/javascript; charset=utf-8', - '.json': 'application/json', - '.svg': 'image/svg+xml', - '.webmanifest': 'application/manifest+json', -} - -function readManifest(path: string): PackageManifest { - const value: unknown = JSON.parse(readFileSync(path, 'utf8')) - if (!isRecord(value)) throw new Error(`dsh desktop: ${path} must contain a package manifest`) - return { - ...(typeof value.name === 'string' ? { name: value.name } : {}), - ...(typeof value.version === 'string' ? { version: value.version } : {}), - } -} - -function packageManifestPath(projectDir: string, packageName: string): string { - const path = join(projectDir, 'node_modules', ...packageName.split('/'), 'package.json') - if (!existsSync(path)) throw new Error(`dsh desktop: installed package ${JSON.stringify(packageName)} has no manifest`) - return path -} - -function isProjectPath(projectDir: string, target: string): boolean { - const root = realpathSync(projectDir) - const path = realpathSync(target) - return path === root || path.startsWith(root + sep) -} - -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) && !isProjectPath(runtimeDir, layer.packageDir)) { - throw new Error(`dsh desktop: profile bundle ${JSON.stringify(layer.packageName)} resolved outside the Desktop runtime and profile`) - } - } - const layers = [ - ...profile.layers.map(layer => layer.patches), - profile.patches, - loadOverlayPatches('dsh desktop', DESKTOP_PATCH), - ] - const rows = new Map(composeEntries(layers).flatMap(row => typeof row.id === 'string' ? [[row.id, row] as const] : [])) - const agentPresets = rows.get('agent-presets') - if (agentPresets !== undefined) { - layers.push([{ - id: 'agent-presets', - config: { - ...(agentPresets.config ?? {}) as Record, - roots: [{ path: join(dshRoot, 'config', 'agent-presets'), trust: 'system' }], - }, - }]) - } - return layers.flat() -} - -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, 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 => { - const rows: IndexInjection[] = [{ kind: 'script', placement: 'head', text: DESKTOP_TRANSPORT_SCRIPT }] - ctx.emit('webserver/index-inject', rows) - const body = renderIndexInjections(await readFile(distIndex, 'utf8'), rows) - return new Response(body, { headers: { 'content-type': MIME['.html'] ?? 'text/html; charset=utf-8' } }) - } - return { - requestBodyMode: () => 'buffered', - async fetch(request): Promise { - if (request.method !== 'GET' && request.method !== 'HEAD') return new Response(null, { status: 405 }) - const url = new URL(request.url) - if (url.pathname.startsWith('/plugins/')) return ctx.clientModules.fetchBundle(request) - let pathname: string - try { - pathname = decodeURIComponent(url.pathname) - } catch { - return new Response(null, { status: 400 }) - } - if (pathname === '/' || pathname === '/index.html') return renderIndex() - const target = resolve(normalize(join(distRoot, pathname))) - if (target !== distRoot && !target.startsWith(distRoot + sep)) return new Response(null, { status: 403 }) - try { - const realTarget = realpathSync(target) - if (realTarget !== distRoot && !realTarget.startsWith(distRoot + sep)) return new Response(null, { status: 403 }) - return new Response(request.method === 'HEAD' ? null : await readFile(realTarget), { - headers: { 'content-type': MIME[extname(realTarget)] ?? 'application/octet-stream' }, - }) - } catch { - return renderIndex() - } - }, - } -} - -function remoteStreamHandler(ctx: Context): ConnectionFetchHandler { - return { - requestBodyMode: () => 'buffered', - async fetch(request): Promise { - if (request.method !== 'POST') return new Response(null, { status: 405 }) - const gateway = ctx.get('typertGateway') - if (gateway === undefined) return new Response('gateway unavailable', { status: 503 }) - let body: unknown - try { - body = await request.json() - } catch { - return new Response('body is not JSON', { status: 400 }) - } - if (!isRecord(body) || typeof body.endpoint !== 'string') { - return new Response('invalid stream request', { status: 400 }) - } - const abort = new AbortController() - const cancel = (): void => { abort.abort(request.signal.reason) } - request.signal.addEventListener('abort', cancel, { once: true }) - const encoder = new TextEncoder() - const stream = new ReadableStream({ - async start(controller) { - try { - const values = await gateway.wireStream.open(body.endpoint as string, body.payload, abort.signal) - for await (const value of values) { - controller.enqueue(encoder.encode(`${JSON.stringify(value)}\n`)) - } - controller.close() - } catch (error) { - controller.error(error) - } finally { - request.signal.removeEventListener('abort', cancel) - } - }, - cancel(reason) { - abort.abort(reason) - request.signal.removeEventListener('abort', cancel) - }, - }) - return new Response(stream, { headers: { 'content-type': 'application/x-ndjson' } }) - }, - } -} - -interface NodeRequestInit extends RequestInit { - readonly duplex?: 'half' -} - -/** - * 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, - options: { allowLinkedPackages?: boolean } = {}, -): Promise { - const absoluteProject = resolve(projectDir) - mkdirSync(absoluteProject, { recursive: true }) - const rootConfig = join(absoluteProject, ROOT_CONFIG_FILENAME) - writeFileSync(rootConfig, ROOT_CONFIG) - 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) => { - current = hostCtx - hostCtx.provide(DSH_LAUNCH_ENVIRONMENT_KEY, environment) - provideCmdline(hostCtx, { args: [], exit: () => {} }) - }) - current = ctx - const connection = ctx.get('connection') - const clientModules = ctx.get('clientModules') - const gateway = ctx.get('typertGateway') - if (connection === undefined || clientModules === undefined || gateway === undefined) { - await ctx.fiber.dispose() - throw new Error('dsh desktop: composition did not provide connection, typertGateway, and clientModules') - } - const api = connection.createSharedFetchHandler('/api') - const assets = assetHandler(ctx, resolve(runtimeDir)) - const streams = remoteStreamHandler(ctx) - const requests = new Map() - let disposing: Promise | undefined - - const dispose = async (): Promise => { - disposing ??= (async () => { - for (const controller of requests.values()) controller.abort() - requests.clear() - await current?.fiber.dispose() - current = undefined - })() - await disposing - } - - return { - dshVersion: dshVersion(resolve(runtimeDir)), - cancel(streamId) { - requests.get(streamId)?.abort() - }, - async fetch(command, body) { - if (disposing !== undefined) throw new Error('dsh desktop: host is disposing') - const controller = new AbortController() - requests.set(command.streamId, controller) - try { - const url = new URL(command.request.url) - const init: NodeRequestInit = { - method: command.request.method, - headers: new Headers(command.request.headers.map(([name, value]) => [name, value] as [string, string])), - ...(body === null ? {} : { body, duplex: 'half' }), - signal: controller.signal, - } - const request = new Request(url, init) - const response = url.pathname === DESKTOP_STREAM_PATH - ? await streams.fetch(request) - : url.pathname.startsWith('/api/') - ? await api.fetch(request) - : await assets.fetch(request) - await writeResponse(encodeDesktopResponseStart(command.streamId, { - status: response.status, - headers: [...response.headers.entries()], - hasBody: response.body !== null, - })) - if (response.body !== null) { - for await (const chunk of response.body) { - const bytes = Buffer.from(chunk) - for (let offset = 0; offset < bytes.byteLength; offset += DESKTOP_PIPE_CHUNK_BYTES) { - await writeResponse(encodeDesktopResponseData( - command.streamId, - bytes.subarray(offset, offset + DESKTOP_PIPE_CHUNK_BYTES), - )) - } - } - } - await writeResponse(encodeDesktopResponseEnd(command.streamId)) - } catch (error) { - if (!controller.signal.aborted) { - await writeResponse(encodeDesktopResponseError( - command.streamId, - error instanceof Error ? error.message : String(error), - )) - } - } finally { - requests.delete(command.streamId) - } - }, - dispose, - } -} +import { loadLayeredEnv, loadProfileDirectory } from '@deepseek-ai/dsh-app-boot' +import { runProfile } from '@deepseek-ai/dsh/profile-boot' +import type {} from '@deepseek-ai/dsh-client-connection' +import type {} from '@deepseek-ai/dsh-host-webserver' async function main(): Promise { - 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[4] - if (option !== undefined && option !== '--allow-linked-profile') { - throw new Error(`dsh desktop: unsupported internal option ${JSON.stringify(option)}`) - } - const requestPipe = createReadStream('', { fd: DESKTOP_REQUEST_PIPE_FD, autoClose: false }) - const responsePipe = createWriteStream('', { fd: DESKTOP_RESPONSE_PIPE_FD, autoClose: false }) - let responseWriteTail: Promise = Promise.resolve() - const writeResponse = (frame: Buffer): Promise => { - const write = responseWriteTail.then(async () => { - if (responsePipe.destroyed) throw new Error('dsh desktop: Electron response pipe is unavailable') - if (!responsePipe.write(frame)) await once(responsePipe, 'drain') - }) - responseWriteTail = write.catch(() => undefined) - return write - } - const send = (event: DesktopHostEvent): void => { - if (process.send === undefined || !process.connected) return - try { - process.send(event) - } catch (error) { - // A concurrent parent disconnect owns teardown; only that closed-channel - // condition is safe to discard while streamed responses unwind. - if ((error as NodeJS.ErrnoException).code !== 'ERR_IPC_CHANNEL_CLOSED') throw error - } - } - const controller = await runDesktopHost(runtimeDir, projectDir, writeResponse, { allowLinkedPackages: option !== undefined }) - send({ - type: 'ready', - protocolVersion: DESKTOP_HOST_PROTOCOL_VERSION, - dshVersion: controller.dshVersion, + const runtimeDir = process.argv[2] as string + const projectDir = process.argv[3] as string + const installAnchor = join(runtimeDir, 'node_modules', '@deepseek-ai', 'dsh', 'package.json') + const profile = loadProfileDirectory('dsh', projectDir, installAnchor) + const application = runProfile({ + environment: loadLayeredEnv('dsh'), + profile: 'desktop', + resolvedProfile: { profile, installAnchor }, + patchFiles: [fileURLToPath(new URL('../config/desktop.cordis.patch.yml', import.meta.url))], + args: ['--no-open'], }) - const decoder = new DesktopHostRequestDecoder() - const requestBodies = new Map>() - const blockedRequests = new Set() - const discardedRequestBodies = new Set() - const runs = new Set>() - let lastStreamId = 0 - let requestedExitCode = 0 - let stopping: Promise | undefined - - const resumeRequestPipe = (): void => { - if (blockedRequests.size === 0) requestPipe.resume() + const stop = async (): Promise => { + // Startup failure is reported by main; shutdown only owns a tree that booted. + const running = await application.catch(() => undefined) + await running?.shutdown.shutdown(0) + if (process.connected) process.disconnect() } - - const stop = (exitCode = 0): Promise => { - requestedExitCode = Math.max(requestedExitCode, exitCode) - stopping ??= (async () => { - requestPipe.pause() - requestPipe.removeAllListeners('data') - const stopped = new Error('dsh desktop: Host is stopping') - for (const body of requestBodies.values()) body.error(stopped) - requestBodies.clear() - blockedRequests.clear() - discardedRequestBodies.clear() - requestPipe.destroy() - closeSync(DESKTOP_REQUEST_PIPE_FD) - await controller.dispose() - await Promise.allSettled([...runs]) - await responseWriteTail.catch(() => undefined) - if (!responsePipe.destroyed) { - await new Promise((resolvePromise) => { responsePipe.end(resolvePromise) }) - responsePipe.destroy() - } - closeSync(DESKTOP_RESPONSE_PIPE_FD) - if (process.connected) process.disconnect() - process.exitCode = requestedExitCode - })() - return stopping - } - - const failTransport = (error: unknown): void => { - const message = error instanceof Error ? error.message : String(error) - send({ type: 'fatal', message }) - void stop(1) - } - - const beginRequest = (frame: Extract): void => { - if (frame.streamId <= lastStreamId) { - throw new Error(`dsh desktop: Electron reused or reordered request stream ${String(frame.streamId)}`) - } - lastStreamId = frame.streamId - let body: ReadableStream | null = null - if (frame.hasBody) { - body = new ReadableStream({ - start(controllerOfBody) { - requestBodies.set(frame.streamId, controllerOfBody) - }, - pull() { - blockedRequests.delete(frame.streamId) - resumeRequestPipe() - }, - cancel() { - requestBodies.delete(frame.streamId) - blockedRequests.delete(frame.streamId) - controller.cancel(frame.streamId) - resumeRequestPipe() - }, - }) - } - const run = controller.fetch({ - streamId: frame.streamId, - request: { - url: frame.url, - method: frame.method, - headers: frame.headers, - }, - }, body) - runs.add(run) - void run.catch(failTransport).finally(() => { - runs.delete(run) - const openBody = requestBodies.get(frame.streamId) - if (openBody === undefined) return - openBody.error(new Error('dsh desktop: response completed before the request body ended')) - requestBodies.delete(frame.streamId) - blockedRequests.delete(frame.streamId) - discardedRequestBodies.add(frame.streamId) - resumeRequestPipe() - }) - } - - const handleRequestFrame = (frame: DesktopHostRequestFrame): void => { - switch (frame.type) { - case 'start': - beginRequest(frame) - return - case 'data': { - const body = requestBodies.get(frame.streamId) - if (body === undefined) { - if (discardedRequestBodies.has(frame.streamId)) return - throw new Error(`dsh desktop: Electron sent body data for inactive stream ${String(frame.streamId)}`) - } - body.enqueue(frame.data) - if ((body.desiredSize ?? 0) <= 0) { - blockedRequests.add(frame.streamId) - requestPipe.pause() - } - return - } - case 'end': { - const body = requestBodies.get(frame.streamId) - if (body === undefined) { - if (discardedRequestBodies.delete(frame.streamId)) return - throw new Error(`dsh desktop: Electron ended inactive body stream ${String(frame.streamId)}`) - } - body.close() - requestBodies.delete(frame.streamId) - blockedRequests.delete(frame.streamId) - resumeRequestPipe() - return - } - case 'cancel': { - if (frame.streamId > lastStreamId) { - throw new Error(`dsh desktop: Electron canceled unknown stream ${String(frame.streamId)}`) - } - const body = requestBodies.get(frame.streamId) - body?.error(new Error('dsh desktop: Electron canceled the request')) - requestBodies.delete(frame.streamId) - blockedRequests.delete(frame.streamId) - discardedRequestBodies.delete(frame.streamId) - controller.cancel(frame.streamId) - resumeRequestPipe() - return - } - default: - frame satisfies never - } - } - - requestPipe.on('data', (chunk: string | Buffer) => { - try { - for (const frame of decoder.push(Buffer.from(chunk))) handleRequestFrame(frame) - } catch (error) { - failTransport(error) - } - }) - requestPipe.once('end', () => { - if (stopping !== undefined) return - try { - decoder.finish() - failTransport(new Error('dsh desktop: Electron request pipe ended')) - } catch (error) { - failTransport(error) - } - }) - requestPipe.once('error', failTransport) - responsePipe.once('error', failTransport) - process.on('message', (message: unknown) => { - if (!isDesktopHostCommand(message)) { - send({ type: 'fatal', message: 'dsh desktop: invalid Electron IPC command' }) - void stop(1) - return - } - void stop() + process.on('message', (message: { type?: string } | null) => { + if (message?.type === 'shutdown') void stop() }) process.once('disconnect', () => { void stop() }) - process.once('SIGTERM', () => { void stop() }) - process.once('SIGINT', () => { void stop() }) + const { ctx } = await application + const url = ctx.connection.authenticatedUrl(`http://127.0.0.1:${String(ctx.webServer.port)}`) + process.send?.({ type: 'ready', url }) } if (import.meta.main) { main().catch((error: unknown) => { const message = error instanceof Error ? error.message : String(error) - if (process.send !== undefined) process.send({ type: 'fatal', message } satisfies DesktopHostEvent) - else process.stderr.write(`dsh desktop: ${message}\n`) + process.send?.({ type: 'fatal', message }) + console.error(error) process.exitCode = 1 + if (process.connected) process.disconnect() }) } diff --git a/apps/desktop-host/src/wire.ts b/apps/desktop-host/src/wire.ts deleted file mode 100644 index d5b2127c49..0000000000 --- a/apps/desktop-host/src/wire.ts +++ /dev/null @@ -1,184 +0,0 @@ -/** Framed request and response bytes for the Electron Desktop Host transport. */ - -/** Protocol version shared with the Electron shell. */ -export const DESKTOP_HOST_PROTOCOL_VERSION = 3 as const - -/** Child descriptor that receives Electron request frames. */ -export const DESKTOP_REQUEST_PIPE_FD = 3 - -/** Child descriptor that emits Host response frames. */ -export const DESKTOP_RESPONSE_PIPE_FD = 4 - -/** Maximum raw body bytes carried by one data frame. */ -export const DESKTOP_PIPE_CHUNK_BYTES = 64 * 1024 - -const FRAME_MAGIC = 0x44534833 -const FRAME_HEADER_BYTES = 13 -const MAX_CONTROL_PAYLOAD_BYTES = 1024 * 1024 - -const REQUEST_FRAME_START = 1 -const REQUEST_FRAME_DATA = 2 -const REQUEST_FRAME_END = 3 -const REQUEST_FRAME_CANCEL = 4 - -const RESPONSE_FRAME_START = 1 -const RESPONSE_FRAME_DATA = 2 -const RESPONSE_FRAME_END = 3 -const RESPONSE_FRAME_ERROR = 4 -type ResponseFrameType = typeof RESPONSE_FRAME_START | typeof RESPONSE_FRAME_DATA - | typeof RESPONSE_FRAME_END | typeof RESPONSE_FRAME_ERROR - -/** One validated request-pipe frame. */ -export type DesktopHostRequestFrame = { - readonly type: 'start' - readonly streamId: number - readonly url: string - readonly method: string - readonly headers: readonly [string, string][] - readonly hasBody: boolean -} | { - readonly type: 'data' - readonly streamId: number - readonly data: Buffer -} | { - readonly type: 'end' | 'cancel' - readonly streamId: number -} - -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null -} - -function isHeaders(value: unknown): value is readonly [string, string][] { - return Array.isArray(value) && value.every(header => Array.isArray(header) && header.length === 2 - && typeof header[0] === 'string' && typeof header[1] === 'string') -} - -function assertStreamId(streamId: number): void { - if (!Number.isInteger(streamId) || streamId < 1 || streamId > 0xffff_ffff) { - throw new Error(`dsh desktop: invalid pipe stream id ${String(streamId)}`) - } -} - -function encodeFrame(type: ResponseFrameType, streamId: number, payload: Buffer): Buffer { - assertStreamId(streamId) - const limit = type === RESPONSE_FRAME_DATA ? DESKTOP_PIPE_CHUNK_BYTES : MAX_CONTROL_PAYLOAD_BYTES - if (payload.byteLength > limit) { - throw new Error(`dsh desktop: response pipe frame exceeds the ${String(limit)}-byte limit`) - } - const frame = Buffer.allocUnsafe(FRAME_HEADER_BYTES + payload.byteLength) - frame.writeUInt32BE(FRAME_MAGIC, 0) - frame.writeUInt8(type, 4) - frame.writeUInt32BE(streamId, 5) - frame.writeUInt32BE(payload.byteLength, 9) - payload.copy(frame, FRAME_HEADER_BYTES) - return frame -} - -function encodeJsonFrame(type: ResponseFrameType, streamId: number, value: unknown): Buffer { - return encodeFrame(type, streamId, Buffer.from(JSON.stringify(value), 'utf8')) -} - -/** Encode response metadata before any body frames. */ -export function encodeDesktopResponseStart( - streamId: number, - response: { - readonly status: number - readonly headers: readonly [string, string][] - readonly hasBody: boolean - }, -): Buffer { - return encodeJsonFrame(RESPONSE_FRAME_START, streamId, response) -} - -/** Encode one bounded raw response-body chunk. */ -export function encodeDesktopResponseData(streamId: number, data: Uint8Array): Buffer { - return encodeFrame(RESPONSE_FRAME_DATA, streamId, Buffer.from(data)) -} - -/** Encode normal response completion. */ -export function encodeDesktopResponseEnd(streamId: number): Buffer { - return encodeFrame(RESPONSE_FRAME_END, streamId, Buffer.alloc(0)) -} - -/** Encode one response failure without exposing an Error object across processes. */ -export function encodeDesktopResponseError(streamId: number, message: string): Buffer { - return encodeJsonFrame(RESPONSE_FRAME_ERROR, streamId, { message }) -} - -/** Incrementally decode validated request frames from the Electron byte pipe. */ -export class DesktopHostRequestDecoder { - private buffer: Buffer = Buffer.alloc(0) - - /** - * Append bytes and return every complete request frame. - * @param chunk - next bytes read from the Electron request pipe. - * @returns complete frames in pipe order. - */ - push(chunk: Buffer): DesktopHostRequestFrame[] { - this.buffer = this.buffer.byteLength === 0 ? chunk : Buffer.concat([this.buffer, chunk]) - const frames: DesktopHostRequestFrame[] = [] - for (;;) { - const frame = this.next() - if (frame === undefined) return frames - frames.push(frame) - } - } - - /** Reject EOF that splits a frame. */ - finish(): void { - if (this.buffer.byteLength !== 0) throw new Error('dsh desktop: Electron request pipe ended inside a frame') - } - - private next(): DesktopHostRequestFrame | undefined { - if (this.buffer.byteLength < FRAME_HEADER_BYTES) return undefined - if (this.buffer.readUInt32BE(0) !== FRAME_MAGIC) throw new Error('dsh desktop: invalid Electron request frame marker') - const rawType = this.buffer.readUInt8(4) - const streamId = this.buffer.readUInt32BE(5) - const payloadLength = this.buffer.readUInt32BE(9) - assertStreamId(streamId) - const limit = rawType === REQUEST_FRAME_DATA ? DESKTOP_PIPE_CHUNK_BYTES : MAX_CONTROL_PAYLOAD_BYTES - if (payloadLength > limit) { - throw new Error(`dsh desktop: Electron request frame exceeds the ${String(limit)}-byte limit`) - } - const frameLength = FRAME_HEADER_BYTES + payloadLength - if (this.buffer.byteLength < frameLength) return undefined - const payload = this.buffer.subarray(FRAME_HEADER_BYTES, frameLength) - this.buffer = this.buffer.subarray(frameLength) - switch (rawType) { - case REQUEST_FRAME_START: - return this.parseStart(streamId, payload) - case REQUEST_FRAME_DATA: - return { type: 'data', streamId, data: payload } - case REQUEST_FRAME_END: - if (payloadLength !== 0) throw new Error('dsh desktop: Electron request end frame carried a payload') - return { type: 'end', streamId } - case REQUEST_FRAME_CANCEL: - if (payloadLength !== 0) throw new Error('dsh desktop: Electron request cancel frame carried a payload') - return { type: 'cancel', streamId } - default: - throw new Error(`dsh desktop: unknown Electron request frame type ${String(rawType)}`) - } - } - - private parseStart(streamId: number, payload: Buffer): DesktopHostRequestFrame { - let value: unknown - try { - value = JSON.parse(payload.toString('utf8')) as unknown - } catch (error) { - throw new Error(`dsh desktop: Electron request start payload is not JSON: ${error instanceof Error ? error.message : String(error)}`) - } - if (!isRecord(value) || typeof value.url !== 'string' || typeof value.method !== 'string' - || !isHeaders(value.headers) || typeof value.hasBody !== 'boolean') { - throw new Error('dsh desktop: invalid Electron request start payload') - } - return { - type: 'start', - streamId, - url: value.url, - method: value.method, - headers: value.headers, - hasBody: value.hasBody, - } - } -} diff --git a/apps/desktop-host/tsconfig.json b/apps/desktop-host/tsconfig.json index 192f76b926..c7e630f24c 100644 --- a/apps/desktop-host/tsconfig.json +++ b/apps/desktop-host/tsconfig.json @@ -4,16 +4,21 @@ "rootDir": "src", "outDir": "lib/types" }, - "include": ["src"], + "include": [ + "src" + ], "references": [ - { "path": "../../vendor/cordis" }, - { "path": "../../vendor/include" }, - { "path": "../../packages/api/gateway/tsconfig.host.json" }, - { "path": "../../packages/boot/app-boot" }, - { "path": "../../packages/boot/cmdline" }, - { "path": "../../packages/client/connection/tsconfig.host.json" }, - { "path": "../../packages/client/modules" }, - { "path": "../../packages/host/webserver" }, - { "path": "../../packages/util/launch-environment" } + { + "path": "../cli" + }, + { + "path": "../../packages/boot/app-boot" + }, + { + "path": "../../packages/client/connection/tsconfig.host.json" + }, + { + "path": "../../packages/host/webserver" + } ] } diff --git a/apps/desktop/README.i18n.yaml b/apps/desktop/README.i18n.yaml index 83d3b39d4e..5f5209bc2c 100644 --- a/apps/desktop/README.i18n.yaml +++ b/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: 62d592307161f202f156d66d91f5a4663c3facc1 -README.zh.md: ace1497876d8b60612b8b5adf1d3ee86f1beeaa4 +README.md: 135802f6b8b31e7d9dbedc4e75cb3626b9830fae +README.zh.md: a40419d58f38514a8ba4a9351c7ff1a0729d4092 diff --git a/apps/desktop/README.md b/apps/desktop/README.md index 62d5923071..135802f6b8 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -2,28 +2,28 @@ English | [中文](README.zh.md) -The desktop application is an Electron shell around the dsh Web UI. It opens no listening port: a bundled upstream Node.js child boots the installed dsh project, versioned framed byte pipes carry Fetch requests and streaming responses without an outer Base64 envelope, Node IPC carries lifecycle control, and `dsh-app://` serves the matching client assets. +The desktop application is an Electron shell around the complete dsh Web application. A bundled upstream Node.js child starts the shared profile runner, and Electron loads its authenticated HTTP URL. Web owns client assets, API routes, and response streaming; Node IPC carries child readiness and shutdown. ## Key technical decisions | Decision | Why | Direct consequence | |---|---|---| | Release identity | The shell API, Web client, backend, and plugin graph are qualified as one combination; independent versions would create untested combinations and ambiguous update availability. | Electron and `@deepseek-ai/dsh` always have the same exact version. A dsh upgrade is a Desktop release, even when the shell code is unchanged. | -| Runtime | Electron's Node.js carries Electron patches, fuses, ABI, and lifecycle constraints, while system runtimes and package-manager state are uncontrolled. | dsh runs under the bundled upstream Node.js and every package operation uses the bundled pnpm. Electron's Node.js, system Node.js, system pnpm, and user package-manager configuration are outside the execution path. | +| Runtime | Electron's Node.js carries Electron patches, fuses, ABI, and lifecycle constraints, while system runtimes and package-manager state are uncontrolled. | dsh runs under the bundled upstream Node.js and every package operation uses the bundled pnpm. Package-manager configuration and the Host environment follow the user's settings. | | Package sources | Core installation at startup adds work even when offline. | `extraResources/dsh` carries a complete production dependency tree; the profile installs only external plugins. | | Shared modules | Host APIs can depend on module identity. | Desktop links every bundled first-party package into the profile using directory symlinks, or Windows junctions; ordinary plugin dependencies remain local. | | State ownership | Sharing executable dependency graphs would let CLI and Desktop change each other's dsh, Cordis, plugin, or native-module versions, while two desktop processes could race on the same profile. | Electron acquires its process-lifetime single-instance lock before any profile access and exclusively owns `$DSH_HOME/profiles/desktop` plus its package-manager state. CLI and Desktop share supported product data under `$DSH_HOME`, but never executable packages, plugin activation, lockfiles, or `node_modules`. | -| Transport | A listening Web service adds port ownership, authentication, CORS, and exposure concerns; Electron and upstream Node.js also need an explicit cross-process protocol. | The application opens no Web port. `dsh-app://` carries Web assets and Fetch traffic; framed byte pipes carry bounded request and response chunks with backpressure, while Node IPC carries only child lifecycle control. | +| Transport | Reusing Web serving and authentication keeps application behavior in one implementation. | Electron loads the Host’s authenticated HTTP URL directly; child IPC carries lifecycle messages, and the local shell protocol serves startup and management pages. | | Plugin changes | Package installation and Host startup can fail. | Desktop stops the Host and modifies the current profile directly. Failures retain partial changes for explicit repair; there is no automatic profile rollback. | | Updates | Independent shell and dsh updates would recreate version splits, while unchanged shell blocks should not require a complete transfer. | The Electron shell, matching dsh runtime, Node.js, and pnpm form one signed update unit. Platform update artifacts may reuse unchanged blocks, but runtime version selection never splits from the Desktop release. | -The [Electron packaging and update Agent Note](../../.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md) owns the rationale, alternatives, security constraints, and release qualification requirements behind these decisions. +The [thin-wrapper decision](../../.agents/notes/implemented/architecture/2026-09-10-desktop-web-wrapper.md) owns shared Web behavior and Desktop adapters. The [Electron packaging and update decision](../../.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md) owns release identity, signing, and update qualification. ## Installation ownership -Electron owns `$DSH_HOME/profiles/desktop`. Its `dependencies` contains only installed external plugins at exact versions; `dsh.profile.bundles` contains the built-in bundles followed by enabled plugins. The signed application supplies dsh, the private Desktop Host, and their production packages from `resources/dsh`. Shared package links resolve to those actual directories. Both host and plugins execute in the same bundled upstream Node process, with normal realpath resolution; Desktop does not enable `--preserve-symlinks`. The CLI cannot boot or mutate this profile. +Electron owns `$DSH_HOME/profiles/desktop`. Its `dependencies` contains packages installed by pnpm; `dsh.profile.bundles` contains the built-in bundles followed by enabled plugins. The signed application supplies dsh, the private Desktop Host, and their production packages from `resources/dsh`. Shared package links resolve to those actual directories. Both host and plugins execute in the same bundled upstream Node process, with normal realpath resolution; Desktop does not enable `--preserve-symlinks`. The CLI cannot boot or mutate this profile. -The local startup page exposes startup status and available recovery actions; the loaded dsh renderer receives only the desktop protocol marker. The separate plugin window receives structured list, install, remove, update, and update-check operations; neither renderer receives filesystem access, raw Electron IPC, a shell, or arbitrary pnpm arguments. +The local startup page exposes startup status and available recovery actions. The product renderer uses the Web application’s HTTP APIs. The separate plugin window receives structured list, install, remove, update, and update-check operations; neither renderer receives filesystem access, raw Electron IPC, a shell, or arbitrary pnpm arguments. Electron chooses typed English or Chinese shell copy from its application locale and falls back to English. Menus, native dialogs, the startup page, and the plugin-management renderer use the same locale payload; the repository Client UI i18n gate checks these desktop sources. @@ -32,16 +32,16 @@ Electron chooses typed English or Chinese shell copy from its application locale The signed `resources/dsh/desktop-runtime.json` binds the shell version, bundled Node version, platform, architecture, shared package versions, and final file inventory. Startup reads the metadata and checks shared package records. Release schema, shell version, target compatibility, and file integrity are verified during packaging. Core packages are never copied into profile storage or installed by pnpm at first launch. 1. The main window displays a local loading page before profile preparation or backend startup. A fresh profile creates its manifest and shared package links while preserving unrelated files, then starts the actual backend once. Unchanged startups reuse the profile without scanning installed plugin manifests. -2. A compatible application upgrade refreshes shared links in the current profile and checks enabled plugins’ peer requirements. Plugin files, configuration, versions, and lockfile remain in place; pnpm does not run. -3. A changed bundled Node version, platform, or architecture reinstalls the locked plugin graph with scripts disabled, validates and links host packages, then runs approved pending builds and validates again. -4. Plugin add, update, and remove operations use bundled pnpm and Desktop-owned package-manager state. Reserved host packages must be peers; nested copies and aliases of shared packages fail validation. Ordinary plugin dependencies must resolve inside the profile. -5. Plugin changes stop the backend before modifying the current profile. Successful preparation starts the Host. Package or Host startup failures retain modified files and report the error. Unfinished package operations retain a marker so the next launch retries the locked installation and pending builds. Desktop creates no staging directories, activation journals, or rollback copies. +2. A compatible application upgrade refreshes shared links in the current profile without checking plugin peer requirements. Plugin files, configuration, versions, and lockfile remain in place; pnpm does not run. +3. Changes to bundled Node, platform, or architecture preserve installed plugins. Native incompatibilities surface during loading and can be repaired through pnpm. +4. Plugin add, update, and remove operations use bundled pnpm with its normal user and profile configuration. Desktop does not override the registry, npmrc, cache, or store, and new profiles add no build allowlist or strict-build setting. Update versions and ranges pass to pnpm. Package specs pass to pnpm, including local directories, Git, tarballs, and aliases. Relative paths resolve from the Desktop profile directory. Packages declaring `dsh.bundle.patch` activate as bundles; ordinary dependencies remain installed without activation. Desktop does not scan plugin dependency graphs or validate patch files before Host startup. Custom profile metadata and bundle order are retained. Unreadable installed metadata does not block listing, disabling, or removing dependencies; the list uses the dependency spec when the installed version is unavailable. +5. Plugin changes stop the backend before modifying the current profile. Successful preparation starts the Host. Package or Host startup failures retain modified files and report the error. Desktop creates no staging directories, activation journals, or rollback copies. -The loading page does not depend on the Host. Errors offer restart and reinstallation guidance. Disabling plugins and resetting Desktop are offered only when packaged application resources support profile recovery; development and early initialization failures expose restart alone. The plugin manager remains available through the application menu. Runtime identity is checked before any backend starts; plugin changes have no automatic rollback. +The loading page does not depend on the Host. Errors offer restart and reinstallation guidance. Disabling plugins and resetting Desktop are offered when runtime resources support profile recovery, including development mode; early initialization failures expose restart alone. The plugin manager remains available through the application menu. Plugin changes have no automatic rollback. Reset deletes every entry in `$DSH_HOME/profiles/desktop` except the held transaction lock, then initializes the built-in profile. It removes Desktop configuration and installed third-party packages without a backup. Shared tasks, settings, and the Harness-home `.env` are untouched. Shell resource and preload failures use a self-contained document with the available recovery actions and diagnostics; its controls do not require preload. -Package transactions hold `$DSH_HOME/profiles/desktop/lock` exclusively through pnpm process exit. Reset preserves the directory and its lock until initialization and Host startup finish. Shared links use directory symlinks on macOS/Linux and junctions on Windows; cleanup removes links without deleting their targets. Canonical filesystem paths identify shared packages, so Windows path casing alone does not trigger profile activation. Native builds follow the profile’s reviewed `allowBuilds` list; installing a new build-requiring package without approval in that list fails the transaction. +Package transactions hold `$DSH_HOME/profiles/desktop/lock` exclusively through pnpm process exit. Reset preserves the directory and its lock until initialization and Host startup finish. Shared links use directory symlinks on macOS/Linux and junctions on Windows; cleanup removes links without deleting their targets. Canonical filesystem paths identify shared packages, so Windows path casing alone does not trigger profile activation. Native builds follow pnpm’s configured build policy. Release preparation owns its separate build-time allowlist. ## Develop @@ -59,7 +59,7 @@ After an explicit build, `start:desktop` reconstructs the disposable project and pnpm run start:desktop ``` -Workspace development runs the current CLI and private Desktop Host packages under the invoking Node.js and disables desktop package mutations. Its explicitly linked disposable profile is the only mode allowed to resolve bundles outside its own directory. Use an unpacked application to exercise the bundled Node.js, bundled pnpm, bundled dsh resources, plugin installation and repair paths. +Workspace development runs the current CLI and private Desktop Host packages under the invoking Node.js. Plugin management and recovery use `$DSH_HOME/profiles/desktop`, separate from the disposable workspace runtime. Development and packaged profiles both use normal bundle resolution, including linked packages. Use an unpacked application to exercise the bundled Node.js, bundled pnpm, bundled dsh resources, plugin installation and repair paths. ## Package @@ -196,5 +196,5 @@ An unpackaged Electron process uses `.desktop-build/development/project` under i - The Web "Open In..." action is disabled in Desktop because its host plugin requires HTTP routes; Desktop does not provide a `webServer`. - Release signing, notarization, update hosting, and previous-version installed-artifact qualification require the production release environment. -- Desktop plugins with dependency lifecycle scripts are rejected unless their package appears in the desktop project's reviewed `allowBuilds` policy. -- The desktop shell shares sessions, settings, credentials, workspaces, and storage under `$DSH_HOME` with CLI dsh, while executable packages, plugin activation, lockfiles, and package-manager state remain separate. +- Dependency lifecycle scripts follow pnpm’s build permissions; Desktop provides no separate approval dialog. +- The desktop shell shares sessions, settings, credentials, workspaces, and storage under `$DSH_HOME` with CLI dsh, while executable packages, plugin activation, and lockfiles remain separate. diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index ace1497876..a40419d58f 100644 --- a/apps/desktop/README.zh.md +++ b/apps/desktop/README.zh.md @@ -2,28 +2,28 @@ [English](README.md) | 中文 -桌面应用是包裹 dsh Web UI 的 Electron 壳。它不打开监听端口:内置的上游 Node.js 子进程启动已安装的 dsh 项目,带版本的分帧字节管道在没有外层 Base64 信封的情况下承载 Fetch 请求与流式响应,Node IPC 承载生命周期控制,`dsh-app://` 则提供与后端版本匹配的客户端资源。 +桌面应用是完整 dsh Web 应用外的一层 Electron 壳。内置上游 Node.js 子进程启动共享 profile runner,Electron 加载其带认证的 HTTP URL。Web 负责客户端资源、API 路由与响应流;Node IPC 承载子进程就绪与关闭。 ## 关键技术决策 | 决策 | 原因 | 直接结果 | |---|---|---| | 发布身份 | 桌面壳 API、Web 客户端、后端与插件依赖图作为一个组合完成验证;独立版本会产生未经验证的组合,并让更新可用性含糊不清。 | Electron 与 `@deepseek-ai/dsh` 始终使用同一精确版本。即使桌面壳代码不变,升级 dsh 也必须发布新 Desktop 版本。 | -| 运行时 | Electron 的 Node.js 带有 Electron 补丁、fuse、ABI 与生命周期约束,而系统运行时和包管理器状态不可控。 | dsh 通过内置的上游 Node.js 运行,所有包操作都使用内置 pnpm。Electron 的 Node.js、系统 Node.js、系统 pnpm 与用户的包管理器配置都不进入执行路径。 | +| 运行时 | Electron 的 Node.js 带有 Electron 补丁、fuse、ABI 与生命周期约束,而系统运行时和包管理器状态不可控。 | dsh 通过内置的上游 Node.js 运行,所有包操作都使用内置 pnpm。包管理器配置和 Host 环境遵循用户设置。 | | 包来源 | 即使离线,启动时安装核心依赖也会增加开销。 | `extraResources/dsh` 携带完整生产依赖树;profile 只安装外部插件。 | | 共享模块 | 宿主 API 可能依赖模块实例身份。 | Desktop 用目录软链接或 Windows junction 把每个内置第一方包连接到 profile;普通插件依赖保留在本地。 | | 状态归属 | 共享可执行依赖图会让 CLI(命令行界面)与 Desktop 相互改变 dsh、Cordis、插件或原生模块版本,而两个桌面进程还可能争用同一个 profile。 | Electron 在访问任何 profile 前获取进程生命周期单实例锁,并独占 `$DSH_HOME/profiles/desktop` 及其包管理器状态。CLI 与 Desktop 共享 `$DSH_HOME` 下受支持的产品数据,但绝不共享可执行包、插件激活、锁文件或 `node_modules`。 | -| 通信 | 监听 Web 服务会引入端口归属、认证、CORS 与暴露风险;Electron 与上游 Node.js 之间也需要明确的跨进程协议。 | 应用不打开 Web 端口。`dsh-app://` 承载 Web 资源和 Fetch 流量;分帧字节管道以背压传输有界请求与响应分块,Node IPC 只承载子进程生命周期控制。 | +| 传输 | 复用 Web 服务与认证,让应用行为由同一份实现负责。 | Electron 直接加载 Host 的认证 HTTP URL;子进程 IPC 承载生命周期消息,本地壳协议提供启动和管理页面。 | | 插件变更 | 包安装和 Host 启动可能失败。 | Desktop 停止 Host 后直接修改当前 profile。失败保留部分修改供用户修复,不自动回滚 profile。 | | 更新 | 桌面壳与 dsh 独立更新会重新产生版本分裂,而桌面壳未变化的数据块不应强制完整传输。 | Electron 壳、匹配的 dsh 运行时、Node.js 与 pnpm 组成一个已签名更新单元。平台更新产物可以复用未变化的数据块,但运行时版本选择绝不脱离 Desktop 发布。 | -[Electron 打包与更新 Agent Note](../../.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md) 记录了这些决策背后的理由、替代方案、安全约束和发布验证要求。 +[薄壳决策](../../.agents/notes/implemented/architecture/2026-09-10-desktop-web-wrapper.zh.md)负责共享 Web 行为与 Desktop 适配。[Electron 打包与更新决策](../../.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md)负责发布身份、签名及更新验收。 ## 安装归属 -Electron 拥有 `$DSH_HOME/profiles/desktop`。其 `dependencies` 只包含已安装外部插件的精确版本;`dsh.profile.bundles` 包含内置 bundle,后接已启用插件。签名应用从 `resources/dsh` 提供 dsh、私有 Desktop Host 及其生产依赖。共享包链接解析到这些实际目录。宿主与插件在同一个内置上游 Node 进程中执行,使用正常的 realpath 解析;Desktop 不启用 `--preserve-symlinks`。CLI 不能启动或修改此 profile。 +Electron 拥有 `$DSH_HOME/profiles/desktop`。其 `dependencies` 包含 pnpm 安装的包;`dsh.profile.bundles` 包含内置 bundle,后接已启用插件。签名应用从 `resources/dsh` 提供 dsh、私有 Desktop Host 及其生产依赖。共享包链接解析到这些实际目录。宿主与插件在同一个内置上游 Node 进程中执行,使用正常的 realpath 解析;Desktop 不启用 `--preserve-symlinks`。CLI 不能启动或修改此 profile。 -本地启动页提供启动状态和可用恢复操作;加载后的 dsh 渲染进程仅接收桌面协议标记。独立插件窗口接收结构化的列表、安装、删除、更新和更新检查操作;两个渲染进程都无法访问文件系统、原始 Electron IPC、shell 或任意 pnpm 参数。 +本地启动页面展示启动状态及可用恢复操作。产品渲染进程使用 Web 应用的 HTTP API。独立插件窗口接收结构化的列表、安装、移除、更新和检查更新操作;两个渲染进程都不会获得文件系统、原始 Electron IPC、shell 或任意 pnpm 参数访问权。 Electron 根据应用 locale 选择类型化的英文或中文桌面壳文案,并以英文作为 fallback。菜单、原生对话框、启动页与插件管理渲染进程使用同一 locale 数据;仓库的 Client UI i18n gate 会检查这些桌面源文件。 @@ -32,16 +32,16 @@ Electron 根据应用 locale 选择类型化的英文或中文桌面壳文案, 签名资源中的 `resources/dsh/desktop-runtime.json` 绑定 shell 版本、内置 Node 版本、平台、架构、共享包版本和最终文件清单。启动读取元数据,并检查共享包记录。发布 schema、shell 版本、目标兼容性和文件完整性在打包时验证。首次启动不会把核心包复制到 profile 存储或通过 pnpm 安装核心包。 1. 主窗口在 profile 准备或后端启动前显示本地加载页。新 profile 创建清单和共享包链接,保留无关文件,然后启动一次实际后端。未变化的启动复用 profile,不扫描已安装插件的清单。 -2. 兼容的应用升级在当前 profile 中刷新共享链接,并检查已启用插件的 peer 要求。插件文件、配置、版本和锁文件留在原处;不运行 pnpm。 -3. 内置 Node 版本、平台或架构变化时,禁用脚本重新安装锁定的插件依赖图,验证并链接宿主包,然后运行已批准的待执行构建并再次验证。 -4. 插件添加、更新和删除使用内置 pnpm 及 Desktop 独有的包管理器状态。保留的宿主包必须声明为 peer;共享包的嵌套副本和别名会被验证拒绝。普通插件依赖必须解析到 profile 内部。 -5. 插件变更在直接修改当前 profile 前停止后端。准备成功后启动 Host。包操作或 Host 启动失败会保留已修改文件并报告错误。未完成的包操作保留标记,使下次启动重试锁定依赖的安装和待执行构建。Desktop 不创建 staging 目录、激活日志或回滚副本。 +2. 兼容的应用升级在当前 profile 中刷新共享链接,不检查插件的 peer 要求。插件文件、配置、版本和锁文件留在原处;不运行 pnpm。 +3. 内置 Node 版本、平台或架构变化时保留已安装插件。原生兼容性问题在加载时报错,可通过 pnpm 修复。 +4. 插件添加、更新和删除使用内置 pnpm 及其正常的用户和 profile 配置。Desktop 不覆盖 registry、npmrc、缓存或 store,新 profile 不添加构建许可列表或严格构建设置。更新版本及范围交给 pnpm。包规格交给 pnpm,包括本地目录、Git、tarball 和别名。相对路径从 Desktop profile 目录解析。声明 `dsh.bundle.patch` 的包作为 bundle 启用;普通依赖安装后不自动启用。Desktop 不扫描插件依赖图,也不在 Host 启动前验证 patch 文件。自定义 profile 元数据和 bundle 顺序会保留。已安装元数据不可读时,仍能列出、禁用和删除依赖;无法读取已安装版本时,列表使用依赖规格。 +5. 插件变更在直接修改当前 profile 前停止后端。准备成功后启动 Host。包操作或 Host 启动失败会保留已修改文件并报告错误。Desktop 不创建 staging 目录、激活日志或回滚副本。 -加载页不依赖 Host。错误页提供重启和重装指导。只有已打包应用的资源支持 profile 恢复时,才提供禁用插件和重置 Desktop;开发模式和早期初始化失败只提供重启。应用菜单仍提供插件管理器入口。每次后端启动前都会检查运行时标识;插件修改不自动回滚。 +加载页不依赖 Host。错误页提供重启和重装指导。运行时资源支持 profile 恢复时,即可禁用插件和重置 Desktop,包括开发模式;早期初始化失败只提供重启。应用菜单仍提供插件管理器入口。插件修改不自动回滚。 重置删除 `$DSH_HOME/profiles/desktop` 中除所持事务锁外的所有条目,然后初始化内置 profile。它删除 Desktop 配置和已安装第三方包,不保留备份。共享任务、设置和 Harness-home `.env` 保持不变。壳资源和 preload 失败时使用独立文档显示可用恢复操作和诊断;其控件不依赖 preload。 -包事务独占持有 `$DSH_HOME/profiles/desktop/lock`,直到 pnpm 进程退出。重置保留目录及其锁,直到初始化和 Host 启动完成。共享链接在 macOS/Linux 使用目录软链接,在 Windows 使用 junction;清理只移除链接,不删除其目标。共享包使用文件系统的规范路径识别,因此 Windows 路径大小写变化不会单独触发 profile 激活。原生构建遵循 profile 中经过审查的 `allowBuilds` 列表;新安装的包如果需要构建但未在列表中获准,事务会失败。 +包事务独占持有 `$DSH_HOME/profiles/desktop/lock`,直到 pnpm 进程退出。重置保留目录及其锁,直到初始化和 Host 启动完成。共享链接在 macOS/Linux 使用目录软链接,在 Windows 使用 junction;清理只移除链接,不删除其目标。共享包使用文件系统的规范路径识别,因此 Windows 路径大小写变化不会单独触发 profile 激活。原生构建遵循 pnpm 的构建配置。发布准备阶段拥有独立的构建许可列表。 ## 开发 @@ -59,7 +59,7 @@ pnpm run dev:desktop pnpm run start:desktop ``` -Workspace 开发使用调用命令的 Node.js 运行当前 CLI 与私有 Desktop Host 包,并禁用桌面包修改;只有该模式明确链接的一次性 profile 可以从自身目录外解析 bundle。需要验证内置 Node.js、内置 pnpm、内置 dsh 资源、插件安装和修复时,应运行未封装安装器的应用目录。 +Workspace 开发使用调用命令的 Node.js 运行当前 CLI 与私有 Desktop Host 包,插件管理和恢复使用 `$DSH_HOME/profiles/desktop`,与一次性工作区运行时分离。开发与打包 profile 都使用正常的 bundle 解析,包括链接包。需要验证内置 Node.js、内置 pnpm、内置 dsh 资源、插件安装和修复时,应运行未封装安装器的应用目录。 ## 打包 @@ -196,5 +196,5 @@ pnpm run prepare:desktop - Desktop 禁用 Web 的「在本地应用中打开…」操作,因为其 Host 插件依赖 HTTP 路由,而 Desktop 不提供 `webServer`。 - 发布签名、公证、更新托管和跨上一版本的已安装产物验证需要生产发布环境。 -- 依赖包含 lifecycle script 的桌面插件,只有其包名进入桌面项目经过评审的 `allowBuilds` 策略后才能安装。 -- 桌面壳与 CLI dsh 共享 `$DSH_HOME` 下的会话、设置、凭据、工作区和存储,但可执行包、插件激活、锁文件与包管理器状态彼此隔离。 +- 依赖的生命周期脚本遵循 pnpm 的构建权限;Desktop 不提供单独的审批对话框。 +- 桌面壳与 CLI dsh 共享 `$DSH_HOME` 下的会话、设置、凭据、工作区和存储,但可执行包、插件激活和锁文件彼此隔离。 diff --git a/apps/desktop/scripts/development-project.ts b/apps/desktop/scripts/development-project.ts index 275373fffe..eddd683161 100644 --- a/apps/desktop/scripts/development-project.ts +++ b/apps/desktop/scripts/development-project.ts @@ -10,10 +10,12 @@ import { rmSync, symlinkSync, unlinkSync, + writeFileSync, } from 'node:fs' import { dirname, join } from 'node:path' import { createDevelopmentProjectMetadata } from '../src/project-manager.ts' import type { DesktopRelease } from '../src/release.ts' +import { DESKTOP_RUNTIME_FILE, type DesktopRuntimeDescriptor } from '../src/runtime-tree.ts' interface PackageManifest { readonly name?: string @@ -62,7 +64,8 @@ function linkDirectory(source: string, destination: string): void { symlinkSync(realpathSync(source), destination, process.platform === 'win32' ? 'junction' : 'dir') } -function mirrorDependencyLinks(sourceRoot: string, destinationRoot: string): void { +function mirrorDependencyLinks(sourceRoot: string, destinationRoot: string): string[] { + const names: string[] = [] for (const entry of readdirSync(sourceRoot, { withFileTypes: true })) { if (entry.name === '.bin') continue const source = join(sourceRoot, entry.name) @@ -71,11 +74,16 @@ function mirrorDependencyLinks(sourceRoot: string, destinationRoot: string): voi for (const scoped of readdirSync(source, { withFileTypes: true })) { if (!scoped.isDirectory() && !scoped.isSymbolicLink()) continue linkDirectory(join(source, scoped.name), join(destinationRoot, entry.name, scoped.name)) + names.push(`${entry.name}/${scoped.name}`) } continue } - if (entry.isDirectory() || entry.isSymbolicLink()) linkDirectory(source, join(destinationRoot, entry.name)) + if (entry.isDirectory() || entry.isSymbolicLink()) { + linkDirectory(source, join(destinationRoot, entry.name)) + names.push(entry.name) + } } + return names } /** @@ -109,12 +117,19 @@ export function prepareDevelopmentProject(options: DevelopmentProjectOptions): s createDevelopmentProjectMetadata(options.projectDir, options.release) const destinationModules = join(options.projectDir, 'node_modules') mkdirSync(destinationModules, { recursive: true }) - mirrorDependencyLinks(options.dependencyDir, destinationModules) + const names = mirrorDependencyLinks(options.dependencyDir, destinationModules) const dshLink = join(destinationModules, '@deepseek-ai', 'dsh') removeOwnedPath(dshLink) linkDirectory(options.cliDir, dshLink) const hostLink = join(destinationModules, '@deepseek-ai', 'dsh-desktop-host') removeOwnedPath(hostLink) linkDirectory(options.hostDir, hostLink) + const sharedPackages = [...new Set([...names, '@deepseek-ai/dsh', '@deepseek-ai/dsh-desktop-host'])].flatMap((name) => { + const manifest = readManifest(join(destinationModules, name, 'package.json')) + return typeof manifest.version === 'string' ? [{ name, version: manifest.version, path: `node_modules/${name}` }] : [] + }) + const runtime: DesktopRuntimeDescriptor = { schemaVersion: 1, release: options.release, + platform: process.platform, arch: process.arch, sharedPackages, files: [] } + writeFileSync(join(options.projectDir, DESKTOP_RUNTIME_FILE), `${JSON.stringify(runtime, undefined, 2)}\n`) return options.projectDir } diff --git a/apps/desktop/scripts/smoke-runtime.ts b/apps/desktop/scripts/smoke-runtime.ts index 4b4103e534..9a0f79113d 100644 --- a/apps/desktop/scripts/smoke-runtime.ts +++ b/apps/desktop/scripts/smoke-runtime.ts @@ -5,7 +5,7 @@ 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 { linkDesktopHostPackages } from '../src/profile-packages.ts' import type { DesktopRuntimeDescriptor } from '../src/runtime-tree.ts' /** @@ -33,9 +33,11 @@ export async function smokeDesktopRuntime(root: string, node: string, runtime: D 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') + ctx.effect(() => ctx.webServer.register({ kind: 'exact', path: '/desktop-smoke', + handler(_request, response) { response.end('plugin route ready') } })) } `) - writeFileSync(join(plugin, 'bundle.yml'), '- insert:\n - id: desktop-runtime-smoke-plugin\n name: desktop-runtime-smoke-plugin\n') + writeFileSync(join(plugin, 'bundle.yml'), '- insert:\n - id: desktop-runtime-smoke-plugin\n name: desktop-runtime-smoke-plugin\n inject: [webServer]\n') const manifest = JSON.parse(readFileSync(join(profile, 'package.json'), 'utf8')) as { dependencies: Record dsh: { profile: { bundles: string[] } } @@ -43,14 +45,17 @@ export function apply(ctx) { manifest.dependencies[pluginName] = '1.0.0' manifest.dsh.profile.bundles.push(pluginName) writeFileSync(join(profile, 'package.json'), JSON.stringify(manifest)) + writeFileSync(join(profile, 'cordis.patch.yml'), '- id: webserver\n config:\n host: 127.0.0.1\n port: 0\n') 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/')) + const login = await fetch(ready.url, { redirect: 'manual' }) + const cookie = login.headers.getSetCookie().map(value => value.split(';')[0]).join('; ') + const response = await fetch(new URL('/', ready.url), { headers: { cookie } }) if (response.status !== 200 || !(await response.text()).includes(' void - readonly reject: (error: Error) => void - responseStarted: boolean - uploadOpen: boolean - controller?: ReadableStreamDefaultController - requestReader?: ReadableStreamDefaultReader - removeAbort?: () => void +interface ReadyEvent { + readonly type: 'ready' + readonly url: string } +interface FatalEvent { + readonly type: 'fatal' + readonly message: string +} + +type DesktopHostEvent = ReadyEvent | FatalEvent + function isDesktopHostEvent(message: unknown): message is DesktopHostEvent { if (typeof message !== 'object' || message === null || !('type' in message)) return false const candidate = message as Record switch (candidate.type) { case 'ready': - return candidate.protocolVersion === DESKTOP_HOST_PROTOCOL_VERSION && typeof candidate.dshVersion === 'string' + return typeof candidate.url === 'string' case 'fatal': return typeof candidate.message === 'string' default: @@ -42,10 +28,6 @@ function isDesktopHostEvent(message: unknown): message is DesktopHostEvent { } } -function errorOf(reason: unknown, fallback: string): Error { - return reason instanceof Error ? reason : new Error(fallback) -} - async function exitsWithin(exit: Promise, milliseconds: number): Promise { let timer: ReturnType | undefined const timeout = new Promise((resolve) => { @@ -59,22 +41,14 @@ async function exitsWithin(exit: Promise, milliseconds: number): Promise = Promise.resolve() - private nextStreamId = 1 - private readonly pending = new Map() - private readonly blockedResponses = new Set() private readyResolve!: (ready: DesktopHostReady) => void private readyReject!: (error: Error) => void private readonly readyPromise = new Promise((resolve, reject) => { @@ -84,14 +58,15 @@ export class DesktopHostProcess { private exitPromise: Promise | undefined private stderr = '' private failureReported = false + private stopping = false /** - * @param node - absolute bundled upstream Node.js executable. - * @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. + * @param node - Absolute bundled upstream Node.js executable. + * @param runtimeDir - Immutable packages carried by the current application. + * @param projectDir - Desktop plugin profile and child working directory. + * @param inspectPort - Optional loopback inspector port for workspace development. + * @param environment - Environment inherited by the Host and its plugin subprocesses. + * @param onFailure - Receives the first unexpected child failure, including after readiness. */ constructor( private readonly node: string, @@ -102,7 +77,10 @@ export class DesktopHostProcess { private readonly onFailure?: (error: Error) => void, ) {} - /** Start the child once and resolve only after its complete composition is active. */ + /** + * Start this child once and await its Web application URL. + * @returns Ready facts supplied by the child after application startup. + */ async start(): Promise { if (this.child !== undefined) return this.readyPromise const entry = join(this.runtimeDir, 'node_modules', '@deepseek-ai', 'dsh-desktop-host', 'lib', 'index.js') @@ -111,44 +89,23 @@ export class DesktopHostProcess { entry, this.runtimeDir, this.projectDir, - ...(this.inspectPort === undefined ? [] : ['--allow-linked-profile']), ], { cwd: this.projectDir, - 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'], + env: this.environment, + stdio: ['ignore', 'pipe', 'pipe', 'ipc'], }) - const requestPipe = child.stdio[DESKTOP_REQUEST_PIPE_FD] - const responsePipe = child.stdio[DESKTOP_RESPONSE_PIPE_FD] - if (!(requestPipe instanceof Writable) || !(responsePipe instanceof Readable)) { - child.kill('SIGTERM') - throw new Error('dsh desktop host did not expose the required byte pipes and IPC channel') - } this.child = child - this.requestPipe = requestPipe - this.responsePipe = responsePipe child.stderr?.setEncoding('utf8') child.stderr?.on('data', (chunk: string) => { this.stderr += chunk }) child.stdout?.pipe(process.stdout) - responsePipe.on('data', (chunk: Buffer) => { this.acceptResponseBytes(chunk) }) - responsePipe.once('end', () => { - try { - this.responseDecoder.finish() - this.fail(new Error('dsh desktop host response pipe ended')) - } catch (error) { - this.fail(errorOf(error, 'dsh desktop host response pipe failed')) - } - }) - requestPipe.once('error', (error) => { this.fail(error) }) - responsePipe.once('error', (error) => { this.fail(error) }) child.on('message', (message: unknown) => { if (!isDesktopHostEvent(message)) { this.fail(new Error('dsh desktop host sent an invalid IPC event')) child.kill('SIGTERM') return } - this.handleMessage(message) + if (message.type === 'ready') this.readyResolve({ url: message.url }) + else this.fail(new Error(message.message)) }) child.once('error', (error) => { this.fail(error) }) this.exitPromise = new Promise((resolve) => { @@ -162,58 +119,12 @@ export class DesktopHostProcess { return this.readyPromise } - /** Forward one `dsh-app://app` request to the child without buffering its body. */ - async fetch(request: Request): Promise { - await this.start() - const child = this.child - if (child === undefined || !child.connected || this.requestPipe === undefined) { - throw new Error('dsh desktop host is unavailable') - } - if (this.nextStreamId > 0xffff_ffff) throw new Error('dsh desktop host exhausted its request stream ids') - const streamId = this.nextStreamId++ - const method = request.method.toUpperCase() - const hasBody = method !== 'GET' && method !== 'HEAD' && request.body !== null - return new Promise((resolve, reject) => { - const pending: PendingResponse = { - resolve, - reject, - responseStarted: false, - uploadOpen: hasBody, - } - const abort = (): void => { - if (!this.pending.has(streamId)) return - const error = errorOf(request.signal.reason, 'request aborted') - pending.uploadOpen = false - void pending.requestReader?.cancel(error).catch(() => undefined) - this.enqueueRequestFrame(encodeDesktopRequestCancel(streamId)).catch((pipeError: unknown) => { - this.fail(errorOf(pipeError, 'dsh desktop request pipe failed')) - }) - if (pending.controller === undefined) pending.reject(error) - else pending.controller.error(error) - this.finishPending(streamId, false) - } - if (request.signal.aborted) { - reject(errorOf(request.signal.reason, 'request aborted')) - return - } - request.signal.addEventListener('abort', abort, { once: true }) - pending.removeAbort = () => { request.signal.removeEventListener('abort', abort) } - this.pending.set(streamId, pending) - this.pumpRequest(streamId, request, hasBody).catch((error: unknown) => { - this.failPending(streamId, errorOf(error, 'dsh desktop request upload failed')) - }) - }) - } - - /** Request graceful teardown, then wait for child exit. */ + /** Request graceful teardown and await exit, escalating termination when needed. */ async stop(): Promise { const child = this.child if (child === undefined) return - this.blockedResponses.clear() - this.responsePipe?.resume() - if (child.connected) this.send({ type: 'shutdown' }) - // Closing the parent-owned write end releases the Host's pending Windows pipe read. - this.requestPipe?.destroy() + this.stopping = true + if (child.connected) child.send({ type: 'shutdown' }, (error) => { if (error !== null) this.fail(error) }) const exited = this.exitPromise ?? Promise.resolve() if (!await exitsWithin(exited, 10_000)) child.kill('SIGTERM') if (!await exitsWithin(exited, 5_000)) { @@ -223,205 +134,15 @@ export class DesktopHostProcess { } } this.child = undefined - this.requestPipe = undefined - this.responsePipe = undefined - } - - private async pumpRequest(streamId: number, request: Request, hasBody: boolean): Promise { - await this.enqueueRequestFrame(encodeDesktopRequestStart(streamId, { - url: request.url, - method: request.method.toUpperCase(), - headers: [...request.headers.entries()], - hasBody, - })) - if (!hasBody) return - const body = request.body - if (body === null) throw new Error('dsh desktop request body disappeared before upload') - const reader = body.getReader() - const pending = this.pending.get(streamId) - if (pending === undefined) { - await reader.cancel() - return - } - pending.requestReader = reader - try { - for (;;) { - const next = await reader.read() - if (next.done) break - for (let offset = 0; offset < next.value.byteLength; offset += DESKTOP_PIPE_CHUNK_BYTES) { - if (!this.pending.has(streamId)) return - await this.enqueueRequestFrame(encodeDesktopRequestData( - streamId, - next.value.subarray(offset, offset + DESKTOP_PIPE_CHUNK_BYTES), - )) - } - } - const live = this.pending.get(streamId) - if (live !== undefined) { - await this.enqueueRequestFrame(encodeDesktopRequestEnd(streamId)) - live.uploadOpen = false - } - } finally { - reader.releaseLock() - const live = this.pending.get(streamId) - if (live?.requestReader === reader) delete live.requestReader - } - } - - private enqueueRequestFrame(frame: Buffer): Promise { - const write = this.requestWriteTail.then(async () => { - const pipe = this.requestPipe - if (pipe === undefined || pipe.destroyed) throw new Error('dsh desktop host request pipe is unavailable') - if (!pipe.write(frame)) await once(pipe, 'drain') - }) - this.requestWriteTail = write.catch(() => undefined) - return write - } - - 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, (error) => { if (error !== null) this.fail(error) }) - } - - private acceptResponseBytes(chunk: Buffer): void { - try { - for (const frame of this.responseDecoder.push(chunk)) this.handleResponseFrame(frame) - } catch (error) { - this.fail(errorOf(error, 'dsh desktop host response pipe failed')) - this.child?.kill('SIGTERM') - } - } - - private handleResponseFrame(frame: DesktopHostResponseFrame): void { - const pending = this.pending.get(frame.streamId) - if (pending === undefined) { - if (frame.streamId >= this.nextStreamId) { - throw new Error(`dsh desktop host responded for unknown stream ${String(frame.streamId)}`) - } - return - } - switch (frame.type) { - case 'start': { - if (pending.responseStarted) throw new Error(`dsh desktop host started stream ${String(frame.streamId)} twice`) - pending.responseStarted = true - let body: ReadableStream | null = null - if (frame.hasBody) { - body = new ReadableStream({ - start: (controller) => { pending.controller = controller }, - pull: () => { - this.blockedResponses.delete(frame.streamId) - this.resumeResponsePipe() - }, - cancel: (reason) => { this.cancelResponse(frame.streamId, reason) }, - }) - } - pending.resolve(new Response(body, { - status: frame.status, - headers: new Headers(frame.headers.map(([name, value]) => [name, value] as [string, string])), - })) - return - } - case 'data': { - const controller = pending.controller - if (!pending.responseStarted || controller === undefined) { - throw new Error(`dsh desktop host sent body data before a body start for stream ${String(frame.streamId)}`) - } - controller.enqueue(frame.data) - if ((controller.desiredSize ?? 0) <= 0) { - this.blockedResponses.add(frame.streamId) - this.responsePipe?.pause() - } - return - } - case 'end': - if (!pending.responseStarted) { - throw new Error(`dsh desktop host ended stream ${String(frame.streamId)} before its response start`) - } - pending.controller?.close() - this.finishPending(frame.streamId, true) - return - case 'error': - this.failPending(frame.streamId, new Error(frame.message)) - return - default: - frame satisfies never - } - } - - private cancelResponse(streamId: number, reason: unknown): void { - const pending = this.pending.get(streamId) - if (pending === undefined) return - pending.uploadOpen = false - void pending.requestReader?.cancel(reason).catch(() => undefined) - this.enqueueRequestFrame(encodeDesktopRequestCancel(streamId)).catch((error: unknown) => { - this.fail(errorOf(error, 'dsh desktop request pipe failed')) - }) - this.finishPending(streamId, false) - } - - private failPending(streamId: number, error: Error): void { - const pending = this.pending.get(streamId) - if (pending === undefined) return - pending.uploadOpen = false - void pending.requestReader?.cancel(error).catch(() => undefined) - if (pending.controller === undefined) pending.reject(error) - else pending.controller.error(error) - this.enqueueRequestFrame(encodeDesktopRequestCancel(streamId)).catch((pipeError: unknown) => { - this.fail(errorOf(pipeError, 'dsh desktop request pipe failed')) - }) - this.finishPending(streamId, false) - } - - private finishPending(streamId: number, cancelOpenUpload: boolean): void { - const pending = this.pending.get(streamId) - if (pending === undefined) return - if (cancelOpenUpload && pending.uploadOpen) { - pending.uploadOpen = false - void pending.requestReader?.cancel().catch(() => undefined) - this.enqueueRequestFrame(encodeDesktopRequestCancel(streamId)).catch((error: unknown) => { - this.fail(errorOf(error, 'dsh desktop request pipe failed')) - }) - } - pending.removeAbort?.() - this.pending.delete(streamId) - this.blockedResponses.delete(streamId) - this.resumeResponsePipe() - } - - private resumeResponsePipe(): void { - if (this.blockedResponses.size === 0) this.responsePipe?.resume() - } - - private handleMessage(message: DesktopHostEvent): void { - switch (message.type) { - case 'ready': - this.readyResolve(message) - return - case 'fatal': - this.fail(new Error(message.message)) - return - default: - message satisfies never - } } private fail(error: Error): void { this.readyReject(error) - if (!this.failureReported) { + if (!this.failureReported && !this.stopping) { 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) - else pending.controller.error(error) - pending.removeAbort?.() - } - this.pending.clear() - this.blockedResponses.clear() - this.responsePipe?.resume() } } diff --git a/apps/desktop/src/host-protocol.ts b/apps/desktop/src/host-protocol.ts index d057d6d16d..8aae3c6c4e 100644 --- a/apps/desktop/src/host-protocol.ts +++ b/apps/desktop/src/host-protocol.ts @@ -1,215 +1,4 @@ -/** Versioned control messages and framed byte transport for the Desktop Host child. */ +/** Release metadata for the Desktop Host lifecycle protocol. */ /** Protocol version implemented by the Electron shell and installed dsh Host. */ -export const DESKTOP_HOST_PROTOCOL_VERSION = 3 as const - -/** Child descriptor Electron writes request frames to. */ -export const DESKTOP_REQUEST_PIPE_FD = 3 - -/** Child descriptor Electron reads response frames from. */ -export const DESKTOP_RESPONSE_PIPE_FD = 4 - -/** Child descriptor reserved for Node's lifecycle IPC channel. */ -export const DESKTOP_CONTROL_IPC_FD = 5 - -/** Maximum raw body bytes carried by one data frame. */ -export const DESKTOP_PIPE_CHUNK_BYTES = 64 * 1024 - -const FRAME_MAGIC = 0x44534833 -const FRAME_HEADER_BYTES = 13 -const MAX_CONTROL_PAYLOAD_BYTES = 1024 * 1024 - -const REQUEST_FRAME_START = 1 -const REQUEST_FRAME_DATA = 2 -const REQUEST_FRAME_END = 3 -const REQUEST_FRAME_CANCEL = 4 -type RequestFrameType = typeof REQUEST_FRAME_START | typeof REQUEST_FRAME_DATA - | typeof REQUEST_FRAME_END | typeof REQUEST_FRAME_CANCEL - -const RESPONSE_FRAME_START = 1 -const RESPONSE_FRAME_DATA = 2 -const RESPONSE_FRAME_END = 3 -const RESPONSE_FRAME_ERROR = 4 - -/** Metadata that precedes one optional request body on the request pipe. */ -export interface DesktopHostRequestStart { - readonly url: string - readonly method: string - readonly headers: readonly [string, string][] - readonly hasBody: boolean -} - -/** Commands retained on Node IPC because they do not carry Fetch payload bytes. */ -export type DesktopHostCommand = { - readonly type: 'shutdown' -} - -/** Lifecycle events retained on Node IPC. */ -export type DesktopHostEvent = { - readonly type: 'ready' - readonly protocolVersion: typeof DESKTOP_HOST_PROTOCOL_VERSION - readonly dshVersion: string -} | { - readonly type: 'fatal' - readonly message: string -} - -/** One decoded response-pipe frame. */ -export type DesktopHostResponseFrame = { - readonly type: 'start' - readonly streamId: number - readonly status: number - readonly headers: readonly [string, string][] - readonly hasBody: boolean -} | { - readonly type: 'data' - readonly streamId: number - readonly data: Buffer -} | { - readonly type: 'end' - readonly streamId: number -} | { - readonly type: 'error' - readonly streamId: number - readonly message: string -} - -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null -} - -function isHeaders(value: unknown): value is readonly [string, string][] { - return Array.isArray(value) && value.every(header => Array.isArray(header) && header.length === 2 - && typeof header[0] === 'string' && typeof header[1] === 'string') -} - -function assertStreamId(streamId: number): void { - if (!Number.isInteger(streamId) || streamId < 1 || streamId > 0xffff_ffff) { - throw new Error(`dsh desktop: invalid pipe stream id ${String(streamId)}`) - } -} - -function encodeFrame(type: RequestFrameType, streamId: number, payload: Buffer): Buffer { - assertStreamId(streamId) - const limit = type === REQUEST_FRAME_DATA ? DESKTOP_PIPE_CHUNK_BYTES : MAX_CONTROL_PAYLOAD_BYTES - if (payload.byteLength > limit) { - throw new Error(`dsh desktop: request pipe frame exceeds the ${String(limit)}-byte limit`) - } - const frame = Buffer.allocUnsafe(FRAME_HEADER_BYTES + payload.byteLength) - frame.writeUInt32BE(FRAME_MAGIC, 0) - frame.writeUInt8(type, 4) - frame.writeUInt32BE(streamId, 5) - frame.writeUInt32BE(payload.byteLength, 9) - payload.copy(frame, FRAME_HEADER_BYTES) - return frame -} - -function encodeJsonFrame(type: RequestFrameType, streamId: number, value: unknown): Buffer { - return encodeFrame(type, streamId, Buffer.from(JSON.stringify(value), 'utf8')) -} - -/** Encode the metadata opening one request stream. */ -export function encodeDesktopRequestStart(streamId: number, request: DesktopHostRequestStart): Buffer { - return encodeJsonFrame(REQUEST_FRAME_START, streamId, request) -} - -/** Encode one bounded raw request-body chunk. */ -export function encodeDesktopRequestData(streamId: number, data: Uint8Array): Buffer { - return encodeFrame(REQUEST_FRAME_DATA, streamId, Buffer.from(data)) -} - -/** Encode normal request-body completion. */ -export function encodeDesktopRequestEnd(streamId: number): Buffer { - return encodeFrame(REQUEST_FRAME_END, streamId, Buffer.alloc(0)) -} - -/** Encode cancellation of one request and its response. */ -export function encodeDesktopRequestCancel(streamId: number): Buffer { - return encodeFrame(REQUEST_FRAME_CANCEL, streamId, Buffer.alloc(0)) -} - -/** Incrementally decode validated response frames from the Host byte pipe. */ -export class DesktopHostResponseDecoder { - private buffer: Buffer = Buffer.alloc(0) - - /** - * Append bytes and return every complete response frame. - * @param chunk - next bytes read from the Host response pipe. - * @returns complete frames in pipe order. - */ - push(chunk: Buffer): DesktopHostResponseFrame[] { - this.buffer = this.buffer.byteLength === 0 ? chunk : Buffer.concat([this.buffer, chunk]) - const frames: DesktopHostResponseFrame[] = [] - for (;;) { - const frame = this.next() - if (frame === undefined) return frames - frames.push(frame) - } - } - - /** Reject EOF that splits a frame. */ - finish(): void { - if (this.buffer.byteLength !== 0) throw new Error('dsh desktop: Host response pipe ended inside a frame') - } - - private next(): DesktopHostResponseFrame | undefined { - if (this.buffer.byteLength < FRAME_HEADER_BYTES) return undefined - if (this.buffer.readUInt32BE(0) !== FRAME_MAGIC) throw new Error('dsh desktop: invalid Host response frame marker') - const rawType = this.buffer.readUInt8(4) - const streamId = this.buffer.readUInt32BE(5) - const payloadLength = this.buffer.readUInt32BE(9) - assertStreamId(streamId) - const limit = rawType === RESPONSE_FRAME_DATA ? DESKTOP_PIPE_CHUNK_BYTES : MAX_CONTROL_PAYLOAD_BYTES - if (payloadLength > limit) { - throw new Error(`dsh desktop: Host response frame exceeds the ${String(limit)}-byte limit`) - } - const frameLength = FRAME_HEADER_BYTES + payloadLength - if (this.buffer.byteLength < frameLength) return undefined - const payload = this.buffer.subarray(FRAME_HEADER_BYTES, frameLength) - this.buffer = this.buffer.subarray(frameLength) - switch (rawType) { - case RESPONSE_FRAME_START: - return this.parseStart(streamId, payload) - case RESPONSE_FRAME_DATA: - return { type: 'data', streamId, data: payload } - case RESPONSE_FRAME_END: - if (payloadLength !== 0) throw new Error('dsh desktop: Host response end frame carried a payload') - return { type: 'end', streamId } - case RESPONSE_FRAME_ERROR: - return this.parseError(streamId, payload) - default: - throw new Error(`dsh desktop: unknown Host response frame type ${String(rawType)}`) - } - } - - private parseStart(streamId: number, payload: Buffer): DesktopHostResponseFrame { - const value = this.parseJson(payload, 'start') - if (!isRecord(value) || !Number.isInteger(value.status) || (value.status as number) < 100 - || (value.status as number) > 599 || !isHeaders(value.headers) || typeof value.hasBody !== 'boolean') { - throw new Error('dsh desktop: invalid Host response start payload') - } - return { - type: 'start', - streamId, - status: value.status as number, - headers: value.headers, - hasBody: value.hasBody, - } - } - - private parseError(streamId: number, payload: Buffer): DesktopHostResponseFrame { - const value = this.parseJson(payload, 'error') - if (!isRecord(value) || typeof value.message !== 'string') { - throw new Error('dsh desktop: invalid Host response error payload') - } - return { type: 'error', streamId, message: value.message } - } - - private parseJson(payload: Buffer, subject: string): unknown { - try { - return JSON.parse(payload.toString('utf8')) as unknown - } catch (error) { - throw new Error(`dsh desktop: Host response ${subject} payload is not JSON: ${error instanceof Error ? error.message : String(error)}`) - } - } -} +export const DESKTOP_HOST_PROTOCOL_VERSION = 4 as const diff --git a/apps/desktop/src/locale.ts b/apps/desktop/src/locale.ts index e2e4d9e6c3..f8a324820c 100644 --- a/apps/desktop/src/locale.ts +++ b/apps/desktop/src/locale.ts @@ -12,7 +12,6 @@ export const en = { 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…', updateCheckFailedTitle: 'Update Check Failed', unknownError: 'Unknown error', @@ -66,7 +65,6 @@ export const zh = { resetConfiguration: '重置 Desktop 并重试', disableThirdPartyPlugins: '禁用全部第三方插件并重试', pluginsMenu: '桌面插件…', - pluginsMenuPackagedOnly: '桌面插件…(打包应用中可用)', checkUpdatesMenu: '检查更新…', updateCheckFailedTitle: '更新检查失败', unknownError: '未知错误', diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index a73a6223a5..f186fdfc5a 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -10,6 +10,7 @@ import { ipcMain, Menu, protocol, + shell, type IpcMainInvokeEvent, } from 'electron' import { resolveDesktopPaths } from './paths.ts' @@ -72,8 +73,10 @@ function runtimeResources(): RuntimeResources { const node = (development ? process.env.DSH_DESKTOP_NODE_BINARY : undefined) ?? 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 dsh = (development ? process.env.DSH_DESKTOP_DSH_DIR : undefined) ?? join(process.resourcesPath, 'dsh') + ?? (development ? join(app.getAppPath(), 'node_modules', 'pnpm', 'bin', 'pnpm.mjs') + : join(process.resourcesPath, 'runtime', 'pnpm', 'bin', 'pnpm.mjs')) + const dsh = (development ? process.env.DSH_DESKTOP_DSH_DIR : undefined) + ?? (development ? join(app.getAppPath(), '.desktop-build', 'development', 'project') : join(process.resourcesPath, 'dsh')) return { node, pnpm, dsh } } @@ -102,9 +105,18 @@ function createWindow(preload: string, show = false): BrowserWindow { webSecurity: true, }, }) - window.webContents.setWindowOpenHandler(() => ({ action: 'deny' })) + window.webContents.setWindowOpenHandler(({ url }) => { + if (['http:', 'https:'].includes(new URL(url).protocol)) void shell.openExternal(url) + return { action: 'deny' } + }) window.webContents.on('will-navigate', (event, url) => { - if (new URL(url).protocol !== `${SCHEME}:`) event.preventDefault() + const destination = new URL(url) + const current = new URL(window.webContents.getURL()) + if (destination.protocol !== `${SCHEME}:` + && !(destination.protocol === 'http:' && destination.origin === current.origin)) { + event.preventDefault() + if (['http:', 'https:'].includes(destination.protocol)) void shell.openExternal(url) + } const page = emergencyPages.get(window) if (page === undefined || page.busy || window.webContents.getURL() !== page.url) return const action = new URL(url) @@ -150,10 +162,10 @@ async function serveShellAsset(request: Request): Promise { async function main(): Promise { const resources = runtimeResources() const paths = resolveDesktopPaths() - const development = app.isPackaged ? undefined : join(app.getAppPath(), '.desktop-build', 'development', 'project') - const activeProject = development ?? paths.profile + const development = !app.isPackaged + const activeProject = paths.profile const manager = new DesktopProjectManager(paths, resources) - profileRecoveryAvailable = () => development === undefined && manager.canRecoverProfile() + profileRecoveryAvailable = () => manager.canRecoverProfile() let pageError: Extract | undefined let quitting = false let startup: Promise | undefined @@ -166,7 +178,7 @@ async function main(): Promise { 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 applicationUrl = startupUrl let navigation: { window: BrowserWindow; url: string; promise: Promise } | undefined let emergencyDocument = false @@ -201,14 +213,15 @@ async function main(): Promise { } } 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, + const hostInspectPort = developmentHostInspectPort(development) + const host = new DesktopHostProcess(resources.node, resources.dsh, activeProject, hostInspectPort, process.env, onFailure) return { - start: () => host.start(), + start: async () => { + const ready = await host.start() + applicationUrl = ready.url + }, stop: () => host.stop(), - fetch: (request: Request) => host.fetch(request), } }, (state) => { if (state.phase === 'starting' && !emergencyDocument) pageError = undefined @@ -260,9 +273,7 @@ async function main(): Promise { pageError = undefined await navigateMain(startupUrl) await backend.start(async () => { - if (development === undefined) { - await manager.applyRelease() - } + await manager.applyRelease() }) if (backend.host !== undefined) await navigateMain(applicationUrl) })().catch(async (error: unknown) => { @@ -289,17 +300,11 @@ async function main(): Promise { } return response }) - if (url.hostname !== 'app') return Promise.resolve(new Response(null, { status: 404 })) - const active = backend.host - if (active === undefined) return Promise.resolve(new Response('backend unavailable', { status: 503 })) - return active.fetch(request) + return Promise.resolve(new Response(null, { status: 404 })) }) const mutate = async (event: IpcMainInvokeEvent, mutation: Parameters[0]): Promise => { assertDesktopSender(event, ['shell']) - if (development !== undefined) { - throw new Error('dsh desktop: plugin package changes require a packaged application') - } await startup?.catch(() => undefined) pageError = undefined await navigateMain(startupUrl) @@ -317,7 +322,6 @@ async function main(): Promise { }) ipcMain.handle(DESKTOP_IPC.pluginsList, (event) => { assertDesktopSender(event, ['shell']) - if (development !== undefined) return [] return manager.listPlugins() }) ipcMain.handle(DESKTOP_IPC.pluginsAdd, (event, spec: unknown) => { @@ -358,7 +362,6 @@ async function main(): Promise { }) 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') @@ -438,9 +441,8 @@ async function main(): Promise { label: process.platform === 'darwin' ? app.name : messages.application, submenu: [ { - label: development === undefined ? messages.pluginsMenu : messages.pluginsMenuPackagedOnly, + label: messages.pluginsMenu, accelerator: 'CmdOrCtrl+,', - enabled: development === undefined, click: openPluginWindow, }, { label: messages.checkUpdatesMenu, click: () => { void checkAndPrompt(true) } }, @@ -496,7 +498,7 @@ async function main(): Promise { // 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') { + if (mainWindow !== undefined && development && process.env.DSH_DESKTOP_OPEN_DEVTOOLS !== '0') { mainWindow.webContents.openDevTools({ mode: 'detach' }) } publishUpdate(updateState) diff --git a/apps/desktop/src/paths.ts b/apps/desktop/src/paths.ts index 5727e5c013..cf03e38c36 100644 --- a/apps/desktop/src/paths.ts +++ b/apps/desktop/src/paths.ts @@ -5,17 +5,8 @@ import { resolveDshHome } from '@deepseek-ai/dsh-home-paths' /** Stable desktop installation paths under the shared Harness home. */ export interface DesktopPaths { - readonly root: string readonly profile: string readonly lock: string - readonly pnpm: { - readonly root: string - readonly store: string - readonly cache: string - readonly state: string - readonly config: string - readonly home: string - } } /** @@ -24,19 +15,8 @@ export interface DesktopPaths { * @returns immutable desktop path set. */ export function resolveDesktopPaths(dshHome: string = resolveDshHome()): DesktopPaths { - const root = join(dshHome, 'desktop') - const pnpm = join(root, 'pnpm') return { - root, profile: join(dshHome, 'profiles', 'desktop'), lock: join(dshHome, 'profiles', 'desktop', 'lock'), - pnpm: { - root: pnpm, - store: join(pnpm, 'store'), - cache: join(pnpm, 'cache'), - state: join(pnpm, 'state'), - config: join(pnpm, 'config'), - home: join(pnpm, 'home'), - }, } } diff --git a/apps/desktop/src/profile-packages.ts b/apps/desktop/src/profile-packages.ts index 1cb907ffa7..0273e6a15d 100644 --- a/apps/desktop/src/profile-packages.ts +++ b/apps/desktop/src/profile-packages.ts @@ -1,10 +1,8 @@ -/** Desktop-owned host links and validation of the external plugin dependency graph. */ +/** Desktop-owned host links and applied runtime identity. */ 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 { existsSync, lstatSync, mkdirSync, readFileSync, readlinkSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs' +import { dirname, isAbsolute, join, resolve } from 'node:path' import { desktopRuntimeId, runtimePath, type DesktopRuntimeDescriptor } from './runtime-tree.ts' /** Applied runtime identity and the only links Desktop may replace. */ @@ -41,11 +39,6 @@ function stat(path: string): ReturnType | 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. @@ -93,24 +86,25 @@ export function unlinkDesktopHostPackages(profile: string): void { 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}`) + continue } unlinkSync(path) } } /** - * Bind an external profile to this application's real package directories. + * Supply missing profile packages from 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) })) + const links = runtime.sharedPackages + .filter(entry => stat(join(profile, 'node_modules', entry.name)) === undefined) + .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') } @@ -119,120 +113,3 @@ export function linkDesktopHostPackages(profile: string, root: string, runtime: 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> - readonly optionalDependencies: Readonly> - readonly peerDependencies: Readonly> - readonly optionalPeers: ReadonlySet -} - -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 => { - 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 - } - const optionalPeers = new Set() - 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() - 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() - 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) - } -} diff --git a/apps/desktop/src/project-manager.ts b/apps/desktop/src/project-manager.ts index a91c6af6b2..4cec30cc62 100644 --- a/apps/desktop/src/project-manager.ts +++ b/apps/desktop/src/project-manager.ts @@ -1,6 +1,5 @@ -/** In-place owner of the reserved desktop profile and its private pnpm state. */ +/** In-place owner of the desktop profile and its pnpm operations. */ -import { valid } from 'semver' import { spawn } from 'node:child_process' import { existsSync, @@ -17,7 +16,7 @@ import { writeFileSync, writeSync, } from 'node:fs' -import { delimiter, dirname, join, resolve, sep } from 'node:path' +import { delimiter, dirname, join } from 'node:path' import { DESKTOP_HOST_PACKAGE, desktopCorePackageOverrides, @@ -29,21 +28,20 @@ import type { DesktopRelease } from './release.ts' import { desktopRuntimeId, readDesktopRuntime, type DesktopRuntimeDescriptor } from './runtime-tree.ts' import { desktopPluginLockHash, linkDesktopHostPackages, readDesktopProfileState, - unlinkDesktopHostPackages, validateDesktopPluginGraph, type DesktopProfileState, + unlinkDesktopHostPackages, } from './profile-packages.ts' /** Desktop plugin record derived from the installed profile. */ export interface DesktopPluginRecord { readonly name: string + /** Installed version, or the dependency spec when installed metadata is unavailable. */ readonly version: string readonly enabled: boolean } /** Installed desktop project manifest slice. */ interface DesktopProjectManifest { - readonly name: string - readonly private: true - readonly version: string + readonly [key: string]: unknown readonly dependencies: Record readonly dsh: { readonly profile: { @@ -79,11 +77,8 @@ const PROJECT_NAME = '@deepseek-ai/dsh-desktop-runtime' const DSH_PACKAGE = '@deepseek-ai/dsh' const CORE_BUILD_PACKAGE = '@deepseek-ai/dsh-subprocess-local' const DESKTOP_PROFILE_BUNDLES = ['@deepseek-ai/dsh-base', '@deepseek-ai/dsh-web-app'] as const -const WORKSPACE_SETTINGS = 'nodeLinker: hoisted\nautoInstallPeers: false\nstrictDepBuilds: true\n' -const PACKAGE_NAME_PATTERN = /^(?:@[a-z0-9][a-z0-9._~-]*\/[a-z0-9][a-z0-9._~-]*|[a-z0-9][a-z0-9._~-]*)$/u -const VERSION_PATTERN = /^[0-9A-Za-z][0-9A-Za-z.+_-]*$/u +const WORKSPACE_SETTINGS = 'nodeLinker: hoisted\nautoInstallPeers: false\n' const MAX_PNPM_DIAGNOSTIC_BYTES = 64 * 1024 -const DESKTOP_REGISTRY = 'https://registry.npmjs.org/' function errorOf(reason: unknown, fallback: string): Error { return reason instanceof Error ? reason : new Error(fallback) @@ -102,6 +97,7 @@ function workspaceFile(overrides: Readonly> = {}): string const overrideSection = entries.length === 0 ? '' : `overrides:\n${entries.map(([name, spec]) => ` ${JSON.stringify(name)}: ${JSON.stringify(spec)}`).join('\n')}\n` + if (entries.length === 0) return `packages:\n - .\n\n${WORKSPACE_SETTINGS}` const coreBuildSpec = overrides[CORE_BUILD_PACKAGE] const coreBuildKey = coreBuildSpec === undefined ? CORE_BUILD_PACKAGE @@ -109,113 +105,61 @@ function workspaceFile(overrides: Readonly> = {}): 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 migrateProfileSettings(projectDir: string): void { + const path = join(projectDir, 'pnpm-workspace.yaml') + if (!existsSync(path)) return + const legacy = `packages:\n - .\n\n${WORKSPACE_SETTINGS}strictDepBuilds: true\nallowBuilds:\n node-pty: true\n koffi: true\n fs-ext: true\n "${CORE_BUILD_PACKAGE}": true\n '@google/genai': false\n protobufjs: false\n node-addon-require-builtin: false\n` + if (readFileSync(path, 'utf8').replaceAll('\r\n', '\n') === legacy) { + writeFileSync(path, workspaceFile()) + } +} + function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null -} - -function assertPackageName(name: string): void { - if (!PACKAGE_NAME_PATTERN.test(name)) throw new Error(`desktop project: invalid npm package name ${JSON.stringify(name)}`) -} - -function assertVersion(version: string): void { - if (!VERSION_PATTERN.test(version)) throw new Error(`desktop project: invalid exact version ${JSON.stringify(version)}`) -} - -/** - * Validate one registry package spec and return its package name. - * @param spec - npm registry name with an optional version or tag. - * @returns Requested package name. - */ -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)}`) - } - if (spec.startsWith('@')) { - const slash = spec.indexOf('/') - if (slash === -1) throw new Error(`desktop project: invalid scoped package spec ${JSON.stringify(spec)}`) - const versionAt = spec.indexOf('@', slash) - const name = versionAt === -1 ? spec : spec.slice(0, versionAt) - assertPackageName(name) - if (versionAt !== -1) assertVersion(spec.slice(versionAt + 1)) - return name - } - const versionAt = spec.indexOf('@') - const name = versionAt === -1 ? spec : spec.slice(0, versionAt) - assertPackageName(name) - if (versionAt !== -1) assertVersion(spec.slice(versionAt + 1)) - return name + return typeof value === 'object' && value !== null && !Array.isArray(value) } 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' || (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, 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 + if (!isRecord(value)) throw new Error(`desktop project: ${path} must hold a JSON object`) + const manifest = value as { dependencies?: Record; dsh?: { profile?: { bundles?: string[] } } } + return { ...value, dependencies: manifest.dependencies ?? {}, + dsh: { ...manifest.dsh, profile: { ...manifest.dsh?.profile, bundles: manifest.dsh?.profile?.bundles ?? [] } } } } -function profilePluginNames(projectDir: string): readonly string[] { - const bundles = projectManifest(projectDir).dsh.profile.bundles - if (!DESKTOP_PROFILE_BUNDLES.every((bundle, index) => bundles[index] === bundle)) { - throw new Error('desktop project: profile must begin with the built-in desktop bundle list') +function installedManifest(projectDir: string, name: string): Record | undefined { + let value: unknown + try { + value = readJson(join(projectDir, 'node_modules', name, 'package.json')) + } catch { + // Unreadable installed metadata must not prevent listing or removing a dependency. + return undefined } - const plugins = bundles.slice(DESKTOP_PROFILE_BUNDLES.length) - if (new Set(bundles).size !== bundles.length) { - throw new Error('desktop project: profile bundle list contains a duplicate package') - } - for (const plugin of plugins) assertPackageName(plugin) - return plugins + return isRecord(value) ? value : undefined } function pluginRecords(projectDir: string): readonly DesktopPluginRecord[] { - return Object.keys(projectManifest(projectDir).dependencies).sort().map(name => inspectPlugin(projectDir, name)) + const manifest = projectManifest(projectDir) + return Object.entries(manifest.dependencies).sort(([left], [right]) => left.localeCompare(right)).map(([name, spec]) => { + const installed = installedManifest(projectDir, name) + return { name, version: typeof installed?.version === 'string' ? installed.version : spec, + enabled: manifest.dsh.profile.bundles.includes(name) } + }) } -function writeProfilePlugins(projectDir: string, plugins: readonly DesktopPluginRecord[]): void { +function writeProfileBundles(projectDir: string, bundles: readonly string[]): void { const manifest = projectManifest(projectDir) writeJson(join(projectDir, 'package.json'), { ...manifest, - dsh: { - ...manifest.dsh, - profile: { - ...manifest.dsh.profile, - bundles: [...DESKTOP_PROFILE_BUNDLES, ...plugins.filter(plugin => plugin.enabled).map(plugin => plugin.name)], - }, - }, - } satisfies DesktopProjectManifest) + dsh: { ...manifest.dsh, profile: { ...manifest.dsh.profile, bundles } }, + }) } -function inspectPlugin(projectDir: string, requestedName: string): DesktopPluginRecord { - const manifestPath = join(projectDir, 'node_modules', ...requestedName.split('/'), 'package.json') - if (!existsSync(manifestPath)) { - throw new Error(`desktop project: installed package ${JSON.stringify(requestedName)} has no manifest`) - } - const manifest = readJson(manifestPath) - if (!isRecord(manifest) || manifest.name !== requestedName || typeof manifest.version !== 'string') { - throw new Error(`desktop project: installed package ${JSON.stringify(requestedName)} has inconsistent name or version`) - } - const dsh = manifest.dsh +function exportsPatch(projectDir: string, name: string): boolean { + const manifest = installedManifest(projectDir, name) + const dsh = manifest?.dsh const bundle = isRecord(dsh) ? dsh.bundle : undefined - const patch = isRecord(bundle) ? bundle.patch : undefined - if (typeof patch !== 'string' || patch === '') { - throw new Error(`desktop project: ${requestedName}@${manifest.version} does not declare dsh.bundle.patch`) - } - const packageDir = dirname(manifestPath) - const patchPath = resolve(packageDir, patch) - 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, enabled: profilePluginNames(projectDir).includes(requestedName) } + return isRecord(bundle) && bundle.patch !== undefined } /** Desktop npm project manager with direct writes and no rollback. */ @@ -271,21 +215,11 @@ export class DesktopProjectManager { return state.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') - } - } - /** @returns Whether application resources support profile recovery. */ canRecoverProfile(): boolean { return this.descriptor !== undefined && existsSync(this.runtime.node) && existsSync(this.runtime.dsh) } - 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 @@ -297,27 +231,25 @@ export class DesktopProjectManager { } private prepareProfile(projectDir: string): void { - const runtime = this.currentRuntime() - linkDesktopHostPackages(projectDir, this.runtime.dsh, runtime) - validateDesktopPluginGraph(projectDir, this.runtime.dsh, runtime, profilePluginNames(projectDir)) + linkDesktopHostPackages(projectDir, this.runtime.dsh, this.currentRuntime()) } /** Read release metadata and reconcile its external profile without installing core packages. */ async applyRelease(): Promise { - return this.withLock(async () => { + return this.withLock(() => { const target = this.readRuntime() this.descriptor = target + migrateProfileSettings(this.paths.profile) const previous = readDesktopProfileState(this.paths.profile) - if (!existsSync(this.pendingPackages) && previous?.runtimeId === desktopRuntimeId(target) + if (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 } - if (previous === undefined) createPluginProfile(this.paths.profile) - await this.reconcileProfile(this.paths.profile, previous) + if (!existsSync(join(this.paths.profile, 'package.json'))) createPluginProfile(this.paths.profile) + this.prepareProfile(this.paths.profile) return true }) } @@ -338,7 +270,6 @@ export class DesktopProjectManager { await hooks.afterChange() return } - const previous = readDesktopProfileState(this.paths.profile) const packagesChanged = mutation.type !== 'plugin-toggle' if (packagesChanged) unlinkDesktopHostPackages(this.paths.profile) try { @@ -346,124 +277,49 @@ export class DesktopProjectManager { } finally { if (packagesChanged) linkDesktopHostPackages(this.paths.profile, this.runtime.dsh, this.currentRuntime()) } - await this.reconcileProfile(this.paths.profile, previous, packagesChanged) await hooks.afterChange() }) } - private async reconcileProfile(projectDir: string, previous: DesktopProfileState | undefined, packagesChanged = false): Promise { - 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 { - this.prepareProfile(projectDir) - await this.runPnpm(projectDir, ['rebuild', '--pending']) - this.prepareProfile(projectDir) - unlinkSync(this.pendingPackages) - } - private async applyMutation(projectDir: string, mutation: Exclude): Promise { + const before = projectManifest(projectDir) + const bundles = before.dsh.profile.bundles switch (mutation.type) { - case 'plugin-add': { - const requestedName = packageNameFromSpec(mutation.spec) - if (this.currentRuntime().sharedPackages.some(entry => entry.name === requestedName)) { - throw new Error(`desktop project: cannot install host-owned package ${requestedName}`) + case 'plugin-add': + case 'plugin-update': { + const dependencies = new Set(Object.keys(before.dependencies)) + const disabled = new Set([...dependencies].filter(name => !bundles.includes(name) && exportsPatch(projectDir, name))) + const spec = mutation.type === 'plugin-add' ? mutation.spec : `${mutation.name}@${mutation.version}` + await this.runPnpm(projectDir, ['add', '--', spec]) + const after = projectManifest(projectDir) + const installed = new Set(Object.keys(after.dependencies)) + const active = bundles.filter(name => !(dependencies.has(name) || installed.has(name)) + || (installed.has(name) && exportsPatch(projectDir, name))) + for (const name of installed) { + if (!active.includes(name) && !disabled.has(name) && exportsPatch(projectDir, name)) active.push(name) } - 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, - [...current, installed].sort((left, right) => left.name.localeCompare(right.name)), - ) + writeProfileBundles(projectDir, active) return } - case 'plugin-remove': { - assertPackageName(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, '--config.ignore-scripts=true']) - writeProfilePlugins(projectDir, remaining) + case 'plugin-remove': + await this.runPnpm(projectDir, ['remove', '--', mutation.name]) + writeProfileBundles(projectDir, bundles.filter(name => name !== mutation.name)) return - } - case 'plugin-update': - assertPackageName(mutation.name) - assertVersion(mutation.version) - 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', '--ignore-scripts']) - { - const installed = inspectPlugin(projectDir, mutation.name) - writeProfilePlugins( - projectDir, - pluginRecords(projectDir).map(plugin => plugin.name === installed.name ? installed : plugin), - ) - } + case 'plugin-toggle': + writeProfileBundles(projectDir, mutation.enabled + ? bundles.includes(mutation.name) ? bundles : [...bundles, mutation.name] + : bundles.filter(name => name !== mutation.name)) 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 async runPnpm(projectDir: string, args: readonly string[]): Promise { - const [command, ...commandArgs] = args - if (command === undefined) throw new Error('desktop project: pnpm command is required') - for (const path of [this.paths.root, this.paths.pnpm.store, this.paths.pnpm.cache, - this.paths.pnpm.state, this.paths.pnpm.config, this.paths.pnpm.home]) { - mkdirSync(path, { recursive: true, mode: 0o700 }) - } - 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]) => ( - name !== 'NODE_OPTIONS' && name !== 'NODE_PATH' && !/^DSH_DESKTOP_/u.test(name) && !/^(?:npm|pnpm|corepack)_/iu.test(name) - ))) - writeFileSync(this.pendingPackages, '') await new Promise((settle, reject) => { - const child = spawn(this.runtime.node, [ - this.runtime.pnpm, - `--config.registry=${DESKTOP_REGISTRY}`, - `--config.store-dir=${this.paths.pnpm.store}`, - '--config.enable-global-virtual-store=false', - `--config.userconfig=${npmrc}`, - command, - ...commandArgs, - ], { + const child = spawn(this.runtime.node, [this.runtime.pnpm, ...args], { cwd: projectDir, - env: { - ...inherited, - COREPACK_HOME: this.paths.pnpm.home, - NPM_CONFIG_REGISTRY: DESKTOP_REGISTRY, - NPM_CONFIG_STORE_DIR: this.paths.pnpm.store, - NPM_CONFIG_USERCONFIG: npmrc, - PATH: `${dirname(this.runtime.node)}${delimiter}${process.env.PATH ?? ''}`, - PNPM_HOME: this.paths.pnpm.home, - XDG_CACHE_HOME: this.paths.pnpm.cache, - XDG_CONFIG_HOME: this.paths.pnpm.config, - XDG_STATE_HOME: this.paths.pnpm.state, - }, + env: { ...process.env, PATH: `${dirname(this.runtime.node)}${delimiter}${process.env.PATH ?? ''}` }, stdio: ['ignore', 'pipe', 'pipe'], }) let failure: Error | undefined @@ -519,9 +375,8 @@ export class DesktopProjectManager { fsyncSync(descriptor) } - private async withLock(operation: () => Promise): Promise { + private async withLock(operation: () => T | Promise): Promise { 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) diff --git a/apps/desktop/tests/development-project.spec.ts b/apps/desktop/tests/development-project.spec.ts index dbdfa09347..22663180be 100644 --- a/apps/desktop/tests/development-project.spec.ts +++ b/apps/desktop/tests/development-project.spec.ts @@ -4,6 +4,9 @@ import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' import { prepareDevelopmentProject } from '../scripts/development-project.ts' import { DESKTOP_HOST_PROTOCOL_VERSION } from '../src/host-protocol.ts' +import { DesktopProjectManager } from '../src/project-manager.ts' +import { resolveDesktopPaths } from '../src/paths.ts' +import { writePackage } from './runtime-fixture.ts' import type { DesktopRelease } from '../src/release.ts' const roots: string[] = [] @@ -29,7 +32,7 @@ afterEach(() => { }) describe('desktop development project', () => { - it('projects the built dsh and Desktop Host applications with their dependency graph', () => { + it('manages development plugins without modifying the linked workspace packages', async () => { const root = temporaryRoot() const cli = join(root, 'apps', 'cli') const host = join(root, 'apps', 'desktop-host') @@ -65,6 +68,21 @@ describe('desktop development project', () => { } expect(manifest.dependencies['@deepseek-ai/dsh']).toBe('1.2.3') expect(manifest.dependencies['@deepseek-ai/dsh-desktop-host']).toBe('1.2.3') + const manager = new DesktopProjectManager(resolveDesktopPaths(join(root, 'home')), { + node: process.execPath, pnpm: join(import.meta.dirname, '../node_modules/pnpm/bin/pnpm.mjs'), dsh: project, + }) + const hooks = { beforeChange: async () => {}, afterChange: async () => {} } + await manager.applyRelease() + const local = writePackage(join(root, 'packages'), 'development-plugin', { dsh: { bundle: { patch: 'bundle.yml' } } }) + writeFileSync(join(local, 'bundle.yml'), '[]\n') + await manager.mutate({ type: 'plugin-add', spec: `file:${local}` }, hooks) + expect(manager.listPlugins()).toEqual([{ name: 'development-plugin', version: '1.0.0', enabled: true }]) + await manager.mutate({ type: 'plugin-remove', name: 'development-plugin' }, hooks) + expect(manager.listPlugins()).toEqual([]) + await manager.resetConfiguration(hooks) + expect(readFileSync(join(cli, 'package.json'), 'utf8')).toBe('{"name":"@deepseek-ai/dsh","version":"1.2.3"}\n') + expect(readFileSync(join(host, 'lib', 'index.js'), 'utf8')).toBe('') + }) it('rejects a CLI package from another release', () => { diff --git a/apps/desktop/tests/host-process.spec.ts b/apps/desktop/tests/host-process.spec.ts index f41650c26e..3d02a75349 100644 --- a/apps/desktop/tests/host-process.spec.ts +++ b/apps/desktop/tests/host-process.spec.ts @@ -1,261 +1,130 @@ -import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs' +import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' import { DesktopHostProcess } from '../src/host-process.ts' const roots: string[] = [] +const hosts: DesktopHostProcess[] = [] -const HOST_WIRE = ` -import { closeSync, createReadStream, createWriteStream } from 'node:fs' -const requestPipe = createReadStream('', { fd: 3, autoClose: false }) -const responsePipe = createWriteStream('', { fd: 4, autoClose: false }) -const MAGIC = 0x44534833 -const HEADER = 13 -function responseFrame(type, streamId, payload = Buffer.alloc(0)) { - const frame = Buffer.allocUnsafe(HEADER + payload.length) - frame.writeUInt32BE(MAGIC, 0) - frame.writeUInt8(type, 4) - frame.writeUInt32BE(streamId, 5) - frame.writeUInt32BE(payload.length, 9) - payload.copy(frame, HEADER) - return frame -} -function responseStart(streamId, options = {}) { - const value = { status: options.status ?? 200, headers: options.headers ?? [], hasBody: options.hasBody ?? true } - responsePipe.write(responseFrame(1, streamId, Buffer.from(JSON.stringify(value)))) -} -function responseData(streamId, data) { - responsePipe.write(responseFrame(2, streamId, Buffer.from(data))) -} -function responseEnd(streamId) { responsePipe.write(responseFrame(3, streamId)) } -function responseError(streamId, message) { - responsePipe.write(responseFrame(4, streamId, Buffer.from(JSON.stringify({ message })))) -} -let requestBuffer = Buffer.alloc(0) -requestPipe.on('data', chunk => { - requestBuffer = requestBuffer.length === 0 ? chunk : Buffer.concat([requestBuffer, chunk]) - while (requestBuffer.length >= HEADER) { - if (requestBuffer.readUInt32BE(0) !== MAGIC) throw new Error('invalid request marker') - const type = requestBuffer.readUInt8(4) - const streamId = requestBuffer.readUInt32BE(5) - const length = requestBuffer.readUInt32BE(9) - if (requestBuffer.length < HEADER + length) return - const payload = requestBuffer.subarray(HEADER, HEADER + length) - requestBuffer = requestBuffer.subarray(HEADER + length) - onRequestFrame({ type, streamId, payload }) +const HTTP_HOST = ` +import { createServer } from 'node:http' +import { writeFileSync } from 'node:fs' +import { join } from 'node:path' +const server = createServer((request, response) => { + if (request.url === '/fatal') { + process.send({ type: 'fatal', message: 'plugin unavailable' }) + response.end('reported') + return } + if (request.url === '/crash') { + response.end('exiting', () => { + process.stderr.write('plugin crashed', () => process.exit(7)) + }) + return + } + response.setHeader('content-type', 'application/json') + response.end(JSON.stringify({runtime: process.argv[2], profile: process.argv[3], cwd: process.cwd(), nodePath: process.env.NODE_PATH, registry: process.env.NPM_CONFIG_REGISTRY, nodeOptions: process.env.NODE_OPTIONS})) +}) +server.listen(0, '127.0.0.1', () => { + process.send({ type: 'ready', url: 'http://127.0.0.1:' + server.address().port + '/?token=fixture' }) }) process.on('message', message => { - if (message.type === 'shutdown') { - requestPipe.destroy() - closeSync(3) - responsePipe.end(() => { - responsePipe.destroy() - closeSync(4) - process.disconnect() - process.exitCode = 0 - }) - } + if (message.type !== 'shutdown') return + server.close(() => { + writeFileSync(join(process.argv[3], 'stopped'), '') + process.disconnect() + }) + server.closeAllConnections() }) ` -function projectWithHost(source: string): string { +function projectWithHost(source = HTTP_HOST): string { const project = mkdtempSync(join(tmpdir(), 'dsh-desktop-host-test-')) roots.push(project) const packageRoot = join(project, 'node_modules', '@deepseek-ai', 'dsh-desktop-host') mkdirSync(join(packageRoot, 'lib'), { recursive: true }) writeFileSync(join(packageRoot, 'package.json'), '{"name":"@deepseek-ai/dsh-desktop-host","type":"module"}\n') - writeFileSync(join(packageRoot, 'lib', 'index.js'), `${HOST_WIRE}\n${source}`) + writeFileSync(join(packageRoot, 'lib', 'index.js'), source) return project } -afterEach(() => { +function hostProcess( + runtime: string, profile = runtime, onFailure?: (error: Error) => void, environment = process.env, +): DesktopHostProcess { + const host = new DesktopHostProcess(process.execPath, runtime, profile, undefined, environment, onFailure) + hosts.push(host) + return host +} + +afterEach(async () => { + await Promise.all(hosts.splice(0).map(host => host.stop())) for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) }) 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' }) -} -`) + it('returns the Web authentication URL and waits for graceful shutdown', async () => { + const runtime = projectWithHost() 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() } + const host = hostProcess(runtime, runtime, failure) + const ready = await host.start() + expect(new URL(ready.url).searchParams.get('token')).toBe('fixture') + expect(await host.start()).toEqual(ready) + expect((await fetch(ready.url)).status).toBe(200) + await host.stop() + expect(existsSync(join(runtime, 'stopped'))).toBe(true) + await expect(fetch(ready.url)).rejects.toThrow() + expect(failure).not.toHaveBeenCalled() + }) + + it('reports a fatal event after readiness once', async () => { + const runtime = projectWithHost() + const failure = vi.fn() + const host = hostProcess(runtime, runtime, failure) + const { url } = await host.start() + await fetch(new URL('/fatal', url)) + await expect.poll(() => failure.mock.calls.length).toBe(1) + await host.stop() + expect(failure).toHaveBeenCalledTimes(1) + expect(failure).toHaveBeenCalledWith(new Error('plugin unavailable')) + }) + + it('reports a child crash after readiness with its stderr diagnostic', async () => { + const runtime = projectWithHost() + const failure = vi.fn() + const host = hostProcess(runtime, runtime, failure) + const { url } = await host.start() + await fetch(new URL('/crash', url)) + await expect.poll(() => failure.mock.calls.length).toBe(1) + expect(failure).toHaveBeenCalledWith(new Error('dsh desktop host exited with 7: plugin crashed')) }) it('settles teardown when the executable cannot be spawned', async () => { - const runtime = projectWithHost('function onRequestFrame() {}') + const runtime = projectWithHost() const host = new DesktopHostProcess(join(runtime, 'missing-node'), runtime, runtime) - try { await expect(host.start()).rejects.toThrow() } finally { await host.stop() } + hosts.push(host) + await expect(host.start()).rejects.toThrow() + 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) -} -`) + it('loads the resource entry with a separate profile and inherits runtime and package-manager configuration', async () => { + const runtime = projectWithHost() 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', + const host = hostProcess(runtime, profile, undefined, { + ...process.env, NODE_OPTIONS: '--no-warnings', NODE_PATH: '/custom', NPM_CONFIG_REGISTRY: 'https://registry.example.test/', }) - 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() } + const { url } = await host.start() + const response = await fetch(url) + expect(await response.json()).toEqual({ runtime, profile, cwd: realpathSync(profile), nodePath: '/custom', registry: 'https://registry.example.test/', nodeOptions: '--no-warnings' }) }) - it('carries raw request and response bytes and shuts the child down cleanly', async () => { - const project = projectWithHost(` -const bodies = new Map() -process.send({ type: 'ready', protocolVersion: 3, dshVersion: process.env.NODE_OPTIONS ?? 'clean' }) -function onRequestFrame(frame) { - if (frame.type === 1) { - const request = JSON.parse(frame.payload) - bodies.set(frame.streamId, Buffer.alloc(0)) - if (!request.hasBody) answer(frame.streamId) - } else if (frame.type === 2) { - bodies.set(frame.streamId, Buffer.concat([bodies.get(frame.streamId), frame.payload])) - } else if (frame.type === 3) { - answer(frame.streamId) - } -} -function answer(streamId) { - responseStart(streamId, { headers: [['content-type', 'text/plain']] }) - responseData(streamId, Buffer.concat([Buffer.from('desktop:'), bodies.get(streamId)])) - responseEnd(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, 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' })) - expect(response.status).toBe(200) - await expect(response.text()).resolves.toBe('desktop:request') - await expect(host.stop()).resolves.toBeUndefined() - } finally { - if (previous === undefined) delete process.env.NODE_OPTIONS - else process.env.NODE_OPTIONS = previous - await host.stop().catch(() => undefined) - } - }) - - it('streams a large binary response in bounded raw frames', async () => { - const size = 2 * 1024 * 1024 - const project = projectWithHost(` -process.send({ type: 'ready', protocolVersion: 3, dshVersion: 'large-response' }) -function onRequestFrame(frame) { - if (frame.type !== 1) return - responseStart(frame.streamId) - const bytes = Buffer.alloc(${String(64 * 1024)}, 97) - for (let offset = 0; offset < ${String(size)}; offset += bytes.length) responseData(frame.streamId, bytes) - responseEnd(frame.streamId) -} -`) - 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()) - expect(body).toHaveLength(size) - expect(body[0]).toBe(97) - expect(body.at(-1)).toBe(97) - } finally { - await host.stop().catch(() => undefined) - } - }) - - it('stops an unfinished upload when the Host completes its response early', async () => { - const project = projectWithHost(` -process.send({ type: 'ready', protocolVersion: 3, dshVersion: 'early-response' }) -function onRequestFrame(frame) { - if (frame.type !== 2) return - responseStart(frame.streamId) - responseData(frame.streamId, 'accepted') - responseEnd(frame.streamId) -} -`) - let canceled = false - const body = new ReadableStream({ - start(controller) { controller.enqueue(Buffer.from('first')) }, - cancel() { canceled = true }, - }) - const host = new DesktopHostProcess(process.execPath, project, project) - try { - const request = new Request('dsh-app://app/early', { - method: 'POST', - body, - duplex: 'half', - } as RequestInit & { duplex: 'half' }) - const response = await host.fetch(request) - await expect(response.text()).resolves.toBe('accepted') - await expect.poll(() => canceled).toBe(true) - } finally { - await host.stop().catch(() => undefined) - } - }) - - it('ignores a response end that arrives after the renderer cancels its stream', async () => { - const project = projectWithHost(` -process.send({ type: 'ready', protocolVersion: 3, dshVersion: 'cancel-race' }) -const urls = new Map() -function onRequestFrame(frame) { - if (frame.type === 1) { - const request = JSON.parse(frame.payload) - urls.set(frame.streamId, request.url) - responseStart(frame.streamId) - if (request.url.endsWith('/after')) { - responseData(frame.streamId, 'alive') - responseEnd(frame.streamId) - } - } else if (frame.type === 4 && urls.get(frame.streamId).endsWith('/cancel')) { - responseEnd(frame.streamId) - } -} -`) - const host = new DesktopHostProcess(process.execPath, project, project) - try { - const canceled = await host.fetch(new Request('dsh-app://app/cancel')) - await canceled.body?.cancel() - await new Promise(resolve => setTimeout(resolve, 25)) - const after = await host.fetch(new Request('dsh-app://app/after')) - await expect(after.text()).resolves.toBe('alive') - } finally { - await host.stop().catch(() => undefined) - } - }) - - it('rejects invalid response framing and a clean exit before readiness', async () => { - const invalid = new DesktopHostProcess(process.execPath, projectWithHost(` -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) - - const earlyExit = new DesktopHostProcess(process.execPath, projectWithHost(` -function onRequestFrame() {} -process.exit(0) -`), projectWithHost('')) - await expect(earlyExit.start()).rejects.toThrow(/response pipe ended/u) + it.each([ + ["process.send({ type: 'fatal', message: 'startup failed' }); process.disconnect()", 'startup failed'], + ["process.send({ type: 'ready', url: 4 })", 'invalid IPC event'], + ['process.exit(0)', 'host stopped'], + ])('rejects startup when the child fails before readiness: %s', async (source, message) => { + const host = hostProcess(projectWithHost(source)) + await expect(host.start()).rejects.toThrow(message) }) }) diff --git a/apps/desktop/tests/host-protocol.spec.ts b/apps/desktop/tests/host-protocol.spec.ts deleted file mode 100644 index b0455f2c6f..0000000000 --- a/apps/desktop/tests/host-protocol.spec.ts +++ /dev/null @@ -1,98 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - DesktopHostRequestDecoder, - encodeDesktopResponseData, - encodeDesktopResponseEnd, - encodeDesktopResponseError, - encodeDesktopResponseStart, -} from '../../desktop-host/src/wire.ts' -import { - DesktopHostResponseDecoder, - encodeDesktopRequestCancel, - encodeDesktopRequestData, - encodeDesktopRequestEnd, - encodeDesktopRequestStart, -} from '../src/host-protocol.ts' - -function decodeInPieces(bytes: Buffer, push: (chunk: Buffer) => readonly T[]): T[] { - const values: T[] = [] - for (let offset = 0; offset < bytes.byteLength; offset += 7) { - values.push(...push(bytes.subarray(offset, offset + 7))) - } - return values -} - -describe('desktop Host pipe protocol', () => { - it('keeps Electron request frames compatible with the installed Host decoder', () => { - const decoder = new DesktopHostRequestDecoder() - const bytes = Buffer.concat([ - encodeDesktopRequestStart(7, { - url: 'dsh-app://app/api/session', - method: 'POST', - headers: [['content-type', 'application/json']], - hasBody: true, - }), - encodeDesktopRequestData(7, Buffer.from('{"ok":true}')), - encodeDesktopRequestEnd(7), - encodeDesktopRequestCancel(7), - ]) - - expect(decodeInPieces(bytes, chunk => decoder.push(chunk))).toEqual([ - { - type: 'start', - streamId: 7, - url: 'dsh-app://app/api/session', - method: 'POST', - headers: [['content-type', 'application/json']], - hasBody: true, - }, - { type: 'data', streamId: 7, data: Buffer.from('{"ok":true}') }, - { type: 'end', streamId: 7 }, - { type: 'cancel', streamId: 7 }, - ]) - expect(() => { decoder.finish() }).not.toThrow() - }) - - it('keeps Host response frames compatible with the Electron decoder', () => { - const decoder = new DesktopHostResponseDecoder() - const bytes = Buffer.concat([ - encodeDesktopResponseStart(9, { - status: 201, - headers: [['content-type', 'application/octet-stream']], - hasBody: true, - }), - encodeDesktopResponseData(9, Buffer.from([0, 1, 2, 255])), - encodeDesktopResponseEnd(9), - encodeDesktopResponseError(10, 'failed'), - ]) - - expect(decodeInPieces(bytes, chunk => decoder.push(chunk))).toEqual([ - { - type: 'start', - streamId: 9, - status: 201, - headers: [['content-type', 'application/octet-stream']], - hasBody: true, - }, - { type: 'data', streamId: 9, data: Buffer.from([0, 1, 2, 255]) }, - { type: 'end', streamId: 9 }, - { type: 'error', streamId: 10, message: 'failed' }, - ]) - expect(() => { decoder.finish() }).not.toThrow() - }) - - it('rejects a corrupt marker and truncated EOF on both directions', () => { - const request = new DesktopHostRequestDecoder() - const response = new DesktopHostResponseDecoder() - expect(() => request.push(Buffer.alloc(13))).toThrow(/request frame marker/u) - expect(() => response.push(Buffer.alloc(13))).toThrow(/response frame marker/u) - - const partialRequest = new DesktopHostRequestDecoder() - partialRequest.push(encodeDesktopRequestEnd(1).subarray(0, 5)) - expect(() => { partialRequest.finish() }).toThrow(/ended inside a frame/u) - - const partialResponse = new DesktopHostResponseDecoder() - partialResponse.push(encodeDesktopResponseEnd(1).subarray(0, 5)) - expect(() => { partialResponse.finish() }).toThrow(/ended inside a frame/u) - }) -}) diff --git a/apps/desktop/tests/main-startup.spec.ts b/apps/desktop/tests/main-startup.spec.ts index 2b2e47d66d..92189f9b02 100644 --- a/apps/desktop/tests/main-startup.spec.ts +++ b/apps/desktop/tests/main-startup.spec.ts @@ -39,22 +39,26 @@ const harness = await vi.hoisted(async () => { isMinimized() { return false } async loadURL(url: string) { this.urls.push(url) - if (url === 'dsh-app://app/index.html') navigated.resolve() + if (url.startsWith('http://')) navigated.resolve() } static getAllWindows() { return windows.filter(window => !window.destroyed) } close() { this.destroyed = true; this.emit('closed') } } class FakeHost { + url = 'http://127.0.0.1:3080/?token=test' readonly ready = deferred() readonly exited = deferred() readonly stopping = deferred() - readonly start = vi.fn(() => { hostStarted.resolve(); return this.ready.promise }) + readonly start = vi.fn(() => { hostStarted.resolve(); return this.ready.promise.then(() => ({ url: this.url })) }) 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) } + constructor( + readonly node: string, readonly runtime: string, readonly profile: string, + readonly inspectPort?: number, readonly environment?: NodeJS.ProcessEnv, readonly onFailure?: (error: Error) => void, + ) { hosts.push(this) } } const app = Object.assign(new EventEmitter(), { isPackaged: true, @@ -75,8 +79,8 @@ const harness = await vi.hoisted(async () => { return { windows, hosts, handlers, app, FakeWindow, FakeHost, dialog: { showErrorBox: vi.fn(), showMessageBox: vi.fn() }, + openExternal: 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 }, @@ -98,6 +102,7 @@ vi.mock('electron', () => ({ app: harness.app, BrowserWindow: harness.FakeWindow, dialog: harness.dialog, + shell: { openExternal: harness.openExternal }, ipcMain: { handle: (channel: string, handler: (event: { senderFrame: { url: string } }) => unknown) => { harness.handlers.set(channel, handler) }, }, @@ -108,7 +113,6 @@ vi.mock('../src/paths.ts', () => ({ resolveDesktopPaths: () => ({ profile: 'desk 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; afterChange(): Promise }) { await hooks.beforeChange() @@ -155,6 +159,61 @@ afterEach(async () => { }) describe('desktop main startup', () => { + it('navigates to each Host authentication URL when retry replaces a failed backend', async () => { + await import('../src/main.ts') + await harness.preparing.promise + harness.prepared.resolve() + await harness.hostStarted.promise + const first = harness.hosts[0]! + first.url = 'http://127.0.0.1:40001/?token=first' + first.ready.resolve() + await harness.navigated.promise + const window = harness.windows[0]! + expect(window.urls.at(-1)).toBe(first.url) + await Promise.resolve(invoke(DESKTOP_IPC.backendRetry)) + first.onFailure!(new Error('backend exited')) + await harness.errorPublished.promise + await first.stopping.promise + first.exited.resolve() + const nextStarted = harness.nextHostStart() + const retry = Promise.resolve(invoke(DESKTOP_IPC.backendRetry)) + await nextStarted + const replacement = harness.hosts[1]! + replacement.url = 'http://127.0.0.1:40002/?token=replacement' + replacement.ready.resolve() + await retry + expect(harness.windows).toHaveLength(1) + expect(window.urls).toEqual([ + 'dsh-app://shell/startup.html', first.url, 'dsh-app://shell/startup.html', replacement.url, + ]) + expect(harness.openExternal).not.toHaveBeenCalled() + }) + + it('opens message links externally while retaining same-origin application navigation', 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 window = harness.windows[0]! + const openWindow = window.webContents.setWindowOpenHandler.mock.calls[0]![0] as + (details: { url: string }) => { action: string } + const source = 'https://example.com/source?q=reference' + expect(openWindow({ url: source })).toEqual({ action: 'deny' }) + expect(harness.openExternal).toHaveBeenCalledWith(source) + harness.openExternal.mockClear() + const external = { preventDefault: vi.fn() } + window.webContents.emit('will-navigate', external, 'https://example.com/document') + expect(external.preventDefault).toHaveBeenCalledOnce() + expect(harness.openExternal).toHaveBeenCalledWith('https://example.com/document') + harness.openExternal.mockClear() + const internal = { preventDefault: vi.fn() } + window.webContents.emit('will-navigate', internal, 'http://127.0.0.1:3080/session/task-1') + expect(internal.preventDefault).not.toHaveBeenCalled() + expect(harness.openExternal).not.toHaveBeenCalled() + }) + it('exits with a diagnostic when both initialization and emergency navigation fail', async () => { const exited = Promise.withResolvers() vi.spyOn(harness.app, 'getLocale').mockImplementationOnce(() => { throw new Error('locale unavailable') }) @@ -210,7 +269,7 @@ describe('desktop main startup', () => { harness.hosts[1]!.ready.resolve() await harness.navigated.promise expect(event.preventDefault).toHaveBeenCalled() - expect(window.urls.at(-1)).toBe('dsh-app://app/index.html') + expect(window.urls.at(-1)).toBe('http://127.0.0.1:3080/?token=test') }) it('allows a full profile reset for an unclassified startup failure', async () => { @@ -245,7 +304,8 @@ describe('desktop main startup', () => { expect(harness.dialog.showErrorBox).not.toHaveBeenCalled() }) - it('offers plugin recovery and disables plugins before restarting in the same window', async () => { + it.each([true, false])('offers plugin recovery and disables plugins in packaged=%s mode', async (packaged) => { + harness.app.isPackaged = packaged harness.pluginsEnabled = true await import('../src/main.ts') await harness.preparing.promise @@ -297,7 +357,6 @@ describe('desktop main startup', () => { 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'), @@ -305,18 +364,20 @@ describe('desktop main startup', () => { }) 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(window.urls).toEqual(['dsh-app://shell/startup.html', 'http://127.0.0.1:3080/?token=test']) expect(invoke(DESKTOP_IPC.backendStatus)).toEqual({ phase: 'ready' }) }) - it('starts the unpackaged Host from the application development directory', async () => { + it('prepares an independent plugin profile for the unpackaged Host', async () => { harness.app.isPackaged = false + vi.stubEnv('DSH_DESKTOP_DSH_DIR', undefined) await import('../src/main.ts') + await harness.preparing.promise + harness.prepared.resolve() 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() + expect(harness.hosts[0]).toMatchObject({ node: 'test-node', runtime: project, profile: 'desktop-test-profile' }) + expect(harness.applyRelease).toHaveBeenCalledOnce() harness.hosts[0]!.ready.resolve() await harness.navigated.promise expect(harness.dialog.showErrorBox).not.toHaveBeenCalled() @@ -342,7 +403,7 @@ describe('desktop main startup', () => { 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.windows[0]!.urls.at(-1)).toBe('http://127.0.0.1:3080/?token=test') expect(harness.dialog.showErrorBox).not.toHaveBeenCalled() }) diff --git a/apps/desktop/tests/plugin-pnpm.spec.ts b/apps/desktop/tests/plugin-pnpm.spec.ts index 351387160e..37233e541c 100644 --- a/apps/desktop/tests/plugin-pnpm.spec.ts +++ b/apps/desktop/tests/plugin-pnpm.spec.ts @@ -1,7 +1,7 @@ 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 { existsSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { pathToFileURL } from 'node:url' @@ -11,7 +11,7 @@ import { DesktopProjectManager, type DesktopProjectHooks } from '../src/project- 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 () => { +it('installs a real pnpm graph and executes scripts approved by user configuration', async () => { const root = realpathSync(mkdtempSync(join(tmpdir(), 'desktop-real-pnpm-'))) const server = createServer() const archives = new Map() @@ -21,7 +21,7 @@ it('installs a real pnpm graph, then executes approved scripts with the shared h ? { 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")}))') + writeFileSync(join(path, 'install.cjs'), 'require("node:fs").writeFileSync("built.json", JSON.stringify({node:process.execPath}))') const tarball = join(root, `${name}.tgz`) await c({ file: tarball, cwd: join(path, '..'), gzip: true }, [name]) archives.set(name, readFileSync(tarball)) @@ -43,20 +43,21 @@ it('installs a real pnpm graph, then executes approved scripts with the shared h }) 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 pnpm = join(import.meta.dirname, '../node_modules/pnpm/bin/pnpm.mjs') const manager = new DesktopProjectManager(resolveDesktopPaths(join(root, '.dsh')), { node: process.execPath, pnpm, dsh }) const hooks: DesktopProjectHooks = { beforeChange: async () => {}, afterChange: async () => {} } await manager.applyRelease() + writeFileSync(join(manager.paths.profile, '.npmrc'), `registry=${origin}\n`) + writeFileSync(join(manager.paths.profile, 'pnpm-workspace.yaml'), `packages:\n - .\nnodeLinker: hoisted\nautoInstallPeers: false\nstoreDir: ${JSON.stringify(join(root, 'store'))}\nallowBuilds:\n node-pty: true\n`) 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 } + const built = JSON.parse(readFileSync(join(manager.paths.profile, 'node_modules/node-pty/built.json'), 'utf8')) as { node: 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-update', name: 'fixture-plugin', version: '^1.0.0' }, hooks) + expect(manager.listPlugins()[0]?.version).toBe('1.0.0') await manager.mutate({ type: 'plugin-remove', name: 'fixture-plugin' }, hooks) expect(manager.listPlugins()).toEqual([]) } finally { @@ -70,3 +71,33 @@ it('installs a real pnpm graph, then executes approved scripts with the shared h rmSync(root, { recursive: true, force: true }) } }, 30_000) + +it.each(['directory', 'file', 'tarball', 'plain'] as const)('installs a %s source through pnpm', async (source) => { + const root = realpathSync(mkdtempSync(join(tmpdir(), 'desktop-local-pnpm-'))) + try { + const dsh = join(root, 'dsh') + runtimeFixture(dsh) + const packageDir = writePackage(join(root, 'local packages'), 'local-plugin', { + ...(source === 'plain' ? {} : { dsh: { bundle: { patch: 'missing.yml' } } }), + peerDependencies: { '@deepseek-ai/cordis': '^999.0.0' }, + }) + const tarball = join(root, 'local-plugin.tgz') + await c({ file: tarball, cwd: join(packageDir, '..'), gzip: true }, ['local-plugin']) + const spec = source === 'directory' ? packageDir : source === 'file' ? `file:${packageDir}` : tarball + const manager = new DesktopProjectManager(resolveDesktopPaths(join(root, '.dsh')), { + node: process.execPath, pnpm: join(import.meta.dirname, '../node_modules/pnpm/bin/pnpm.mjs'), dsh, + }) + const hooks: DesktopProjectHooks = { beforeChange: async () => {}, afterChange: async () => {} } + await manager.applyRelease() + await manager.mutate({ type: 'plugin-add', spec }, hooks) + expect(manager.listPlugins()).toEqual([{ name: 'local-plugin', version: '1.0.0', enabled: source !== 'plain' }]) + expect(existsSync(join(manager.paths.profile, 'node_modules/local-plugin/missing.yml'))).toBe(false) + await manager.mutate({ type: 'plugins-disable-all' }, hooks) + expect(manager.listPlugins()[0]?.enabled).toBe(false) + await manager.mutate({ type: 'plugin-remove', name: 'local-plugin' }, hooks) + expect(manager.listPlugins()).toEqual([]) + expect(existsSync(join(packageDir, 'package.json'))).toBe(true) + } finally { + rmSync(root, { recursive: true, force: true }) + } +}, 30_000) diff --git a/apps/desktop/tests/profile-packages.spec.ts b/apps/desktop/tests/profile-packages.spec.ts index d419c962f2..752312b3c8 100644 --- a/apps/desktop/tests/profile-packages.spec.ts +++ b/apps/desktop/tests/profile-packages.spec.ts @@ -1,11 +1,11 @@ import { execFileSync } from 'node:child_process' -import { mkdtempSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs' +import { existsSync, mkdtempSync, rmSync, 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 { linkDesktopHostPackages, unlinkDesktopHostPackages } from '../src/profile-packages.ts' import { runtimeFixture, writePackage } from './runtime-fixture.ts' const roots: string[] = [] @@ -22,57 +22,27 @@ function fixture() { 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() + const { dsh, 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', () => { +it('preserves a pnpm package that replaced a managed link', () => { 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) + expect(() =>{ unlinkDesktopHostPackages(profile) }).not.toThrow() + expect(existsSync(join(profile, 'node_modules/@deepseek-ai/cordis/package.json'))).toBe(true) }) diff --git a/apps/desktop/tests/project-manager.spec.ts b/apps/desktop/tests/project-manager.spec.ts index c618e69393..b40a7860aa 100644 --- a/apps/desktop/tests/project-manager.spec.ts +++ b/apps/desktop/tests/project-manager.spec.ts @@ -2,9 +2,9 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, import { tmpdir } from 'node:os' import { join } from 'node:path' import { pathToFileURL } from 'node:url' -import { afterEach, describe, expect, it } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' import { resolveDesktopPaths } from '../src/paths.ts' -import { DesktopProjectManager, packageNameFromSpec, type DesktopProjectHooks } from '../src/project-manager.ts' +import { DesktopProjectManager, type DesktopProjectHooks } from '../src/project-manager.ts' import { runtimeFixture } from './runtime-fixture.ts' const roots: string[] = [] @@ -22,17 +22,17 @@ import { join } from 'node:path' const args = process.argv.slice(2) const project = process.cwd() 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') +appendFileSync(${JSON.stringify(join(root, 'pnpm-log.jsonl'))}, JSON.stringify({args, registry: process.env.NPM_CONFIG_REGISTRY, userconfig: process.env.NPM_CONFIG_USERCONFIG, pnpmHome: process.env.PNPM_HOME, configHome: process.env.XDG_CONFIG_HOME}) + '\\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 spec = args.includes('--') ? args[args.indexOf('--') + 1] : 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]] + if (command === 'remove') delete manifest.dependencies[args[args.indexOf('--') + 1]] writeFileSync(manifestPath, JSON.stringify(manifest)) rmSync(join(project, 'node_modules'), { recursive: true, force: true }) for (const [name, version] of Object.entries(manifest.dependencies)) { @@ -65,6 +65,7 @@ afterEach(async () => { const directories = roots.splice(0) const results = await Promise.allSettled(cleanups.map(cleanup => cleanup())) for (const root of directories) rmSync(root, { recursive: true, force: true }) + vi.unstubAllEnvs() const failures: unknown[] = results.flatMap((result): unknown[] => result.status === 'rejected' ? [result.reason] : []) if (failures.length > 0) throw new AggregateError(failures, 'desktop worker cleanup failed') }) @@ -100,7 +101,7 @@ describe('desktop external plugin profile', () => { 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) + expect(calls(root)).toHaveLength(1) await expect(manager.applyRelease()).resolves.toBe(false) }) @@ -127,7 +128,6 @@ describe('desktop external plugin profile', () => { 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') }, @@ -142,11 +142,79 @@ describe('desktop external plugin profile', () => { 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) + expect(calls(root)).toHaveLength(1) await expect(manager.applyRelease()).resolves.toBe(false) expect(existsSync(homeEnvironment)).toBe(true) }) + it.each(['missing', 'malformed', 'unversioned'] as const)('lists, disables, and removes a package with %s metadata', async (damage) => { + const { manager } = setup() + await manager.applyRelease() + await manager.mutate({ type: 'plugin-add', spec: 'plugin@1.0.0' }, hooks()) + const path = join(manager.paths.profile, 'node_modules/plugin/package.json') + if (damage === 'missing') unlinkSync(path) + else writeFileSync(path, damage === 'malformed' ? '{broken' : '{}') + expect(manager.listPlugins()).toEqual([{ name: 'plugin', version: '1.0.0', enabled: true }]) + await manager.mutate({ type: 'plugin-toggle', name: 'plugin', enabled: false }, hooks()) + expect(manager.listPlugins()[0]?.enabled).toBe(false) + await manager.mutate({ type: 'plugin-remove', name: 'plugin' }, hooks()) + expect(manager.listPlugins()).toEqual([]) + }) + + it('preserves custom profile metadata and bundle order during plugin changes', async () => { + const { manager } = setup() + await manager.applyRelease() + const path = join(manager.paths.profile, 'package.json') + writeFileSync(path, JSON.stringify({ name: 'custom', private: false, custom: true, + dependencies: {}, dsh: { profile: { bundles: ['custom-bundle', 'custom-bundle'] } } })) + await manager.mutate({ type: 'plugin-add', spec: 'plugin@1.0.0' }, hooks()) + expect(JSON.parse(readFileSync(path, 'utf8'))).toMatchObject({ name: 'custom', private: false, custom: true, + dsh: { profile: { bundles: ['custom-bundle', 'custom-bundle', 'plugin'] } } }) + await manager.mutate({ type: 'plugin-remove', name: 'plugin' }, hooks()) + expect(JSON.parse(readFileSync(path, 'utf8'))).toMatchObject({ + dsh: { profile: { bundles: ['custom-bundle', 'custom-bundle'] } } }) + }) + + it('passes user registry and pnpm configuration through to the bundled executable', async () => { + const { root, manager } = setup() + vi.stubEnv('NPM_CONFIG_REGISTRY', 'https://packages.example.test/') + vi.stubEnv('NPM_CONFIG_USERCONFIG', join(root, 'user.npmrc')) + vi.stubEnv('PNPM_HOME', join(root, 'user-pnpm')) + vi.stubEnv('XDG_CONFIG_HOME', join(root, 'user-config')) + await manager.applyRelease() + await manager.mutate({ type: 'plugin-add', spec: 'plugin@next' }, hooks()) + expect(calls(root)[0]).toMatchObject({ registry: 'https://packages.example.test/', + userconfig: join(root, 'user.npmrc'), pnpmHome: join(root, 'user-pnpm'), configHome: join(root, 'user-config'), + args: ['add', '--', 'plugin@next'] }) + }) + + it('initializes the same pnpm settings as a Web profile without a Desktop build allowlist', async () => { + const { manager } = setup() + await manager.applyRelease() + expect(readFileSync(join(manager.paths.profile, 'pnpm-workspace.yaml'), 'utf8')) + .toBe('packages:\n - .\n\nnodeLinker: hoisted\nautoInstallPeers: false\n') + }) + + it('opens a linked profile and migrates only the generated pnpm defaults', async () => { + const { root, manager } = setup() + const target = join(root, 'linked-profile') + mkdirSync(target) + mkdirSync(join(manager.paths.profile, '..'), { recursive: true }) + symlinkSync(target, manager.paths.profile, process.platform === 'win32' ? 'junction' : 'dir') + await manager.applyRelease() + const path = join(target, 'pnpm-workspace.yaml') + const defaults = readFileSync(path, 'utf8') + writeFileSync(path, `${defaults}strictDepBuilds: true\nallowBuilds:\n node-pty: true\n koffi: true\n fs-ext: true\n "@deepseek-ai/dsh-subprocess-local": true\n '@google/genai': false\n protobufjs: false\n node-addon-require-builtin: false\n`) + await manager.applyRelease() + expect(readFileSync(path, 'utf8')).toBe(defaults) + const custom = `${defaults}allowBuilds:\n my-plugin: true\n` + writeFileSync(path, custom) + await manager.applyRelease() + expect(readFileSync(path, 'utf8')).toBe(custom) + await manager.mutate({ type: 'plugin-add', spec: 'plugin@1.0.0' }, hooks()) + expect(manager.listPlugins()[0]?.name).toBe('plugin') + }) + it('reports damaged application metadata as a reinstall failure', async () => { const { manager } = setup() writeFileSync(join(manager.runtime.dsh, 'desktop-runtime.json'), '{broken') @@ -154,31 +222,6 @@ describe('desktop external plugin profile', () => { 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') - for (const spec of ['file:../plugin', '--registry=evil', 'https://example.test/plugin.tgz']) { - expect(() => packageNameFromSpec(spec)).toThrow(/unsupported npm package spec/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) - }) - it('preserves unknown files when initializing a profile', async () => { const { manager } = setup() mkdirSync(manager.paths.profile, { recursive: true }) @@ -189,38 +232,12 @@ describe('desktop external plugin profile', () => { 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') - } - 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('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(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: {} }) }) @@ -253,19 +270,29 @@ describe('desktop external plugin profile', () => { expect(calls(root)).toEqual([]) }) - it('installs only plugins and checks the graph before running lifecycle scripts', async () => { + it('installs plugins with pnpm script settings and restores host links', async () => { const { root, manager } = setup() await manager.applyRelease() await manager.mutate({ type: 'plugin-add', spec: '@scope/plugin@2.0.0' }, hooks()) expect(manager.listPlugins()).toEqual([{ name: '@scope/plugin', version: '2.0.0', enabled: true }]) expect(calls(root).map(call => call.args.filter(arg => !arg.startsWith('--config.')))).toEqual([ - ['add', '@scope/plugin@2.0.0', '--save-exact', '--ignore-scripts'], ['rebuild', '--pending'], + ['add', '--', '@scope/plugin@2.0.0'], ]) - expect(calls(root).every(call => call.registry === 'https://registry.npmjs.org/')).toBe(true) + expect(calls(root).every(call => call.registry === process.env.NPM_CONFIG_REGISTRY)).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) + expect(calls(root)).toHaveLength(1) + }) + + it('retains pnpm-installed host package copies instead of rejecting their dependency placement', async () => { + const { manager } = setup() + await manager.applyRelease() + await manager.mutate({ type: 'plugin-add', spec: '@deepseek-ai/cordis@2.0.0' }, hooks()) + expect(manager.listPlugins()).toEqual([{ name: '@deepseek-ai/cordis', version: '2.0.0', enabled: true }]) + await expect(manager.applyRelease()).resolves.toBe(false) + await manager.mutate({ type: 'plugin-remove', name: '@deepseek-ai/cordis' }, hooks()) + expect(realpathSync(join(manager.paths.profile, 'node_modules/@deepseek-ai/cordis'))) + .toBe(realpathSync(join(manager.runtime.dsh, 'node_modules/@deepseek-ai/cordis'))) }) it('retains disabled plugin versions through updates and enables them explicitly', async () => { @@ -273,7 +300,7 @@ describe('desktop external plugin profile', () => { 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(calls(root)).toHaveLength(1) 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 }]) @@ -295,12 +322,12 @@ describe('desktop external plugin profile', () => { 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(calls(root)).toHaveLength(1) 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('reinstalls the locked plugin graph when bundled Node changes', async () => { + it('preserves plugin files without running pnpm when bundled Node changes', async () => { const { root, manager } = setup() await manager.applyRelease() await manager.mutate({ type: 'plugin-add', spec: 'plugin@1.0.0' }, hooks()) @@ -308,20 +335,18 @@ describe('desktop external plugin profile', () => { 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(calls(root)).toHaveLength(1) 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 () => { + it('allows peer version mismatches to reach Host startup and remain available for recovery', 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) + await expect(next.applyRelease()).resolves.toBe(true) expect(next.releaseVersion()).toBe('2.0.0') await next.mutate({ type: 'plugins-disable-all' }, hooks()) expect(next.releaseVersion()).toBe('2.0.0') @@ -341,9 +366,6 @@ describe('desktop external plugin profile', () => { }))).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 () => { @@ -362,6 +384,10 @@ describe('desktop external plugin profile', () => { 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'))) + writeFileSync(join(manager.paths.profile, 'desktop-packages-pending'), '') + await manager.applyRelease() + await manager.mutate({ type: 'plugins-disable-all' }, hooks({ afterChange: async () => { starts++ } })) + expect(starts).toBe(1) await manager.mutate({ type: 'plugin-remove', name: 'plugin' }, hooks()) expect(manager.listPlugins()).toEqual([]) }) diff --git a/packages/boot/app-boot/README.i18n.yaml b/packages/boot/app-boot/README.i18n.yaml index 263c2cf9e9..2437c21556 100644 --- a/packages/boot/app-boot/README.i18n.yaml +++ b/packages/boot/app-boot/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 packages/boot/app-boot/README.md -README.md: a525440f20879314bd8d12b647830f2c541f59b3 -README.zh.md: 90aa0beda52c2968c93eab13bae11640e81e0664 +README.md: eeb0f682ac2a3fe9092c5b7cd132e04b4871b2aa +README.zh.md: 75b8b832eaeef365247ea3d8a5c417a04567e9bb diff --git a/packages/boot/app-boot/README.md b/packages/boot/app-boot/README.md index a525440f20..eeb0f682ac 100644 --- a/packages/boot/app-boot/README.md +++ b/packages/boot/app-boot/README.md @@ -86,7 +86,7 @@ This section explains how the outcomes above are realized and points at the code - **Channel-neutral library.** The package carries no loader hooks and no dev-mode surface; the [`dsh` app](../../../apps/cli/README.md) owns its Node source-launch hook and consumes these helpers for the boot sequence, and built consumers use plain Node package resolution. - **Two Loader builtins.** `mountRootInclude` registers `cordis:include` and `cordis:group` as Loader builtins: a group row gives one `isolate` realm to a provider and its consumers together, and an agent preset outside this workspace cannot resolve `@deepseek-ai/cordis-plugin-group` by name. Both load through the ambient module pipeline rather than the included tree's own specifier resolution. -- **Profile module fallback.** Bare plugin specifiers resolve through the Loader from the config directory. Plain Node maintains one symlink per package in the installation dependency closure. A packaged executable instead reads each installed export map with Node ESM conditions and writes real proxy packages that re-export virtual module URLs, because an operating-system symlink cannot enter pkg's `/snapshot` tree. Missing exports stay unavailable, malformed maps fail startup, and a cross-process writer lock replaces stale entries without exposing partial proxies. A selected external bundle absent from the installation closure receives a profile-local `.dsh-module-fallback` link; existing pnpm entries win, projected links are excluded from later closure discovery, and cleanup removes only dsh-owned links. +- **Profile module fallback.** Bare plugin specifiers resolve through the Loader from the config directory. Plain Node maintains one symlink per package in the installation dependency closure. A packaged executable instead reads each installed export map with Node ESM conditions and writes real proxy packages that re-export virtual module URLs, because an operating-system symlink cannot enter pkg's `/snapshot` tree. Missing exports stay unavailable, malformed maps fail startup, and a cross-process writer lock replaces stale entries without exposing partial proxies. A selected external bundle absent from the installation closure receives a profile-local `.dsh-module-fallback` link; existing pnpm entries win, projected links are excluded from later closure discovery, and cleanup removes only dsh-owned links. Application-owned filesystem profiles use the same projection for their installation closure, so missing peers resolve inside their own profile without maintaining a shared fallback directory. - **One rejection checkpoint.** `assertEntriesActivated` keeps the exact reasons it folds into the boot diagnostic visible through the next process rejection checkpoint, so `installFailLoud` coalesces Loader's duplicate notification while unrelated unhandled rejections remain fatal. - **Two-stage failure labels.** `boot()` distinguishes `host preparation failed` — `prepare` threw before any config-tree entry mounted — from `plugin tree failed to load`, and appends the deepest plugin error's stack so the startup diagnostic preserves the original activation error instead of only the wrap chain. diff --git a/packages/boot/app-boot/README.zh.md b/packages/boot/app-boot/README.zh.md index 90aa0beda5..75b8b832ea 100644 --- a/packages/boot/app-boot/README.zh.md +++ b/packages/boot/app-boot/README.zh.md @@ -86,7 +86,7 @@ profile 是同一套 dsh 安装提供不同应用界面的方式:`web`、`head - **与渠道无关的库。** 此包不包含 loader 钩子,也不提供开发模式接口;[`dsh` 应用](../../../apps/cli/README.zh.md) 持有自己的 Node 源码启动钩子,并在启动序列中使用这些 helper,构建后的消费方则使用普通 Node 包解析。 - **两个 Loader builtin。** `mountRootInclude` 把 `cordis:include` 与 `cordis:group` 注册为 Loader builtin:group 行能把一个提供方与它的消费方放进同一个 `isolate` realm,而位于本工作区之外的 agent preset 无法按名称解析 `@deepseek-ai/cordis-plugin-group`。两者都通过宿主的模块管线加载,而非被包含树自身的说明符解析。 -- **Profile 模块后备机制。** 裸插件 specifier 由 Loader 从配置目录解析。普通 Node 会为安装依赖闭包中的每个包维护一个符号链接。打包可执行文件无法让操作系统符号链接进入 pkg 的 `/snapshot` 树,因此会按 Node ESM 条件读取已安装包的 export map,并写入重新导出虚拟模块 URL 的真实代理包。缺失 export 保持不可用,错误 export map 会让启动失败,跨进程 writer lock 则会在不暴露部分代理的情况下替换陈旧条目。所选外部组合包若不在安装闭包中,则会获得 profile 本地的 `.dsh-module-fallback` 链接;已有 pnpm 条目优先,后续闭包发现会排除投影链接,清理也只删除 dsh 自有链接。 +- **Profile 模块后备机制。** 裸插件 specifier 由 Loader 从配置目录解析。普通 Node 会为安装依赖闭包中的每个包维护一个符号链接。打包可执行文件无法让操作系统符号链接进入 pkg 的 `/snapshot` 树,因此会按 Node ESM 条件读取已安装包的 export map,并写入重新导出虚拟模块 URL 的真实代理包。缺失 export 保持不可用,错误 export map 会让启动失败,跨进程 writer lock 则会在不暴露部分代理的情况下替换陈旧条目。所选外部组合包若不在安装闭包中,则会获得 profile 本地的 `.dsh-module-fallback` 链接;已有 pnpm 条目优先,后续闭包发现会排除投影链接,清理也只删除 dsh 自有链接。应用自有的文件系统 profile 使用同一投影机制补全安装闭包,因此缺失的 peer 可在自己的 profile 内解析,无需维护共享后备目录。 - **单一 rejection 检查点。** `assertEntriesActivated` 把折入启动诊断的确切原因保持到下一个进程级 rejection 检查点可见,使 `installFailLoud` 能合并 Loader 的重复通知,而所有无关的未处理 rejection 仍然致命。 - **两阶段失败标签。** `boot()` 区分 `host preparation failed`(`prepare` 在任何配置树条目挂载前抛出)与 `plugin tree failed to load`(此后的一切失败),并追加最深层插件错误的堆栈,使启动诊断保留原始激活错误,而不只是包装链。 diff --git a/packages/boot/app-boot/src/index.ts b/packages/boot/app-boot/src/index.ts index ef891cef0d..ee79f3bc01 100644 --- a/packages/boot/app-boot/src/index.ts +++ b/packages/boot/app-boot/src/index.ts @@ -32,6 +32,7 @@ export { DEFAULT_PROFILE_BUNDLES, DEFAULT_PROFILE_PATCH_RELOAD, healProfilesModuleFallback, + healIsolatedProfileModuleFallback, initProfile, loadProfile, loadProfileDirectory, diff --git a/packages/boot/app-boot/src/profile.ts b/packages/boot/app-boot/src/profile.ts index 3324c996b4..37e9383ccf 100644 --- a/packages/boot/app-boot/src/profile.ts +++ b/packages/boot/app-boot/src/profile.ts @@ -462,9 +462,7 @@ function profileDependencyNames(manifest: ProfileManifest): string[] { } /** Resolve the installation generation that every profile must find through the fallback directory. */ -function resolveModuleFallbackEntries( - installAnchor: string, -): { entries: ModuleFallbackEntry[]; packageNames: ReadonlySet } { +function resolveInstallationPackageDirectories(installAnchor: string): Map { const appManifest = readModuleFallbackManifest(installAnchor) const links = new Map() /* v8 ignore next -- a real app manifest always declares its name */ @@ -488,6 +486,14 @@ function resolveModuleFallbackEntries( queue.push({ anchor: manifestPath, manifest: readModuleFallbackManifest(manifestPath) }) } } + return links +} + +/** Resolve installation packages as filesystem links or packaged-executable proxies. */ +function resolveModuleFallbackEntries( + installAnchor: string, +): { entries: ModuleFallbackEntry[]; packageNames: ReadonlySet } { + const links = resolveInstallationPackageDirectories(installAnchor) const entries = !isPackagedExecutable() ? [...links].map(([packageName, packageDir]) => ({ kind: 'symlink' as const, packageName, packageDir })) : [...links].flatMap(([packageName, packageDir]) => { @@ -559,6 +565,17 @@ export async function healProfilesModuleFallback(options: ProfileModuleFallbackO if (profile !== undefined) healProfileModuleFallback(profile, packageNames) } +/** + * Supply an application-owned profile with filesystem packages from its installation and selected bundles. + * All fallback links belong to the profile; no shared Harness-home directory is written. + * Existing pnpm-managed packages remain authoritative. The caller serializes profile mutations. + * @param options - owning installation package.json and the loaded application profile. + */ +export function healIsolatedProfileModuleFallback(options: { installAnchor: string; profile: Profile }): void { + const installationLinks = resolveInstallationPackageDirectories(options.installAnchor) + healProfileModuleFallback(options.profile, new Set(installationLinks.keys()), installationLinks) +} + /** Heal one module-fallback generation while the cross-process writer lock is held. */ function healProfilesModuleFallbackLocked(entries: readonly ModuleFallbackEntry[], modulesDir: string): void { for (const entry of entries) { @@ -608,7 +625,10 @@ function dependencyClosure( } /** Reconcile packages carried only by selected bundles into one profile. */ -function healProfileModuleFallback(profile: Profile, installationPackageNames: ReadonlySet): void { +function healProfileModuleFallback( + profile: Profile, installationPackageNames: ReadonlySet, + installationLinks: ReadonlyMap = new Map(), +): void { const profileModulesDir = join(profile.dir, 'node_modules') const ownedModulesDir = join(profile.dir, PROFILE_MODULE_FALLBACK_DIR, 'node_modules') mkdirSync(profileModulesDir, { recursive: true }) @@ -631,10 +651,11 @@ function healProfileModuleFallback(profile: Profile, installationPackageNames: R } }) for (const layer of profile.layers) bundleLinks.delete(layer.packageName) + const links = new Map([...installationLinks, ...bundleLinks]) for (const packageName of ownedPackageNames(ownedModulesDir)) { - if (!bundleLinks.has(packageName)) removeProfileSymlink(profileModulesDir, ownedModulesDir, packageName) + if (!links.has(packageName)) removeProfileSymlink(profileModulesDir, ownedModulesDir, packageName) } - for (const [packageName, target] of bundleLinks) { + for (const [packageName, target] of links) { const ownedLink = join(ownedModulesDir, packageName) mkdirSync(dirname(ownedLink), { recursive: true }) ensureSymlink(ownedLink, target) diff --git a/packages/boot/app-boot/tests/profile.spec.ts b/packages/boot/app-boot/tests/profile.spec.ts index 3fa0cf97b4..2ee9f7c3dc 100644 --- a/packages/boot/app-boot/tests/profile.spec.ts +++ b/packages/boot/app-boot/tests/profile.spec.ts @@ -9,12 +9,14 @@ import { unlinkSync, writeFileSync, } from 'node:fs' import { tmpdir } from 'node:os' +import { createRequire } from 'node:module' import { join } from 'node:path' import { withFileLock } from '@deepseek-ai/dsh-atomic-write' import { afterAll, describe, expect, it } from 'vitest' import { composeEntries, healProfilesModuleFallback, + healIsolatedProfileModuleFallback, initProfile, loadProfile, loadProfileDirectory, @@ -89,6 +91,55 @@ function stageProfile(home: string, name: string, bundleAnchor: string): Profile } } +describe('healIsolatedProfileModuleFallback', () => { + it.each([false, true])('resolves peers from each installation without sharing profile state (Web fallback: %s)', async (webFallback) => { + const home = tmp() + const webAnchor = stageInstallation({ commander: {} }) + if (webFallback) await healProfilesModuleFallback({ installAnchor: webAnchor, home }) + const sharedCommander = join(home, 'profiles', 'node_modules', 'commander') + const sharedTarget = webFallback ? readlinkSync(sharedCommander) : undefined + const bundleAnchor = stageInstallation({ 'bundle-only': {} }, 'external-bundle') + const anchorA = stageInstallation({ commander: {}, 'pnpm-owned': {} }) + const anchorB = stageInstallation({ commander: {}, 'pnpm-owned': {} }) + const profileA = stageProfile(home, 'desktop-a', bundleAnchor) + const profileB = stageProfile(home, 'desktop-b', bundleAnchor) + const consumerA = join(profileA.dir, 'node_modules', 'custom-plugin', 'index.js') + const consumerB = join(profileB.dir, 'node_modules', 'custom-plugin', 'index.js') + for (const consumer of [consumerA, consumerB]) { + mkdirSync(join(consumer, '..'), { recursive: true }) + writeFileSync(consumer, 'module.exports = require("commander")\n') + writeFileSync(join(consumer, '..', 'package.json'), JSON.stringify({ + name: 'custom-plugin', peerDependencies: { commander: '*' }, + })) + } + const installed = join(profileA.dir, 'node_modules', 'pnpm-owned') + mkdirSync(installed) + writeFileSync(join(installed, 'package.json'), JSON.stringify({ name: 'pnpm-owned', main: 'index.js' })) + writeFileSync(join(installed, 'index.js'), 'module.exports = "profile-installed"\n') + + healIsolatedProfileModuleFallback({ installAnchor: anchorA, profile: profileA }) + healIsolatedProfileModuleFallback({ installAnchor: anchorB, profile: profileB }) + healIsolatedProfileModuleFallback({ installAnchor: anchorA, profile: profileA }) + + expect(createRequire(consumerA).resolve('commander')) + .toBe(realpathSync.native(join(anchorA, '..', 'node_modules', 'commander', 'index.js'))) + expect(createRequire(consumerB).resolve('commander')) + .toBe(realpathSync.native(join(anchorB, '..', 'node_modules', 'commander', 'index.js'))) + expect(createRequire(consumerA).resolve('pnpm-owned')).toBe(join(installed, 'index.js')) + expect(readFileSync(join(installed, 'index.js'), 'utf8')).toContain('profile-installed') + expect(createRequire(consumerA).resolve('bundle-only')) + .toBe(realpathSync.native(join(bundleAnchor, '..', 'node_modules', 'bundle-only', 'index.js'))) + expect(existsSync(join(home, 'profiles', 'node_modules'))).toBe(webFallback) + if (webFallback) expect(readlinkSync(sharedCommander)).toBe(sharedTarget) + + healIsolatedProfileModuleFallback({ installAnchor: anchorA, profile: { ...profileA, layers: [] } }) + expect(existsSync(join(profileA.dir, 'node_modules', 'bundle-only'))).toBe(false) + expect(existsSync(join(profileB.dir, 'node_modules', 'bundle-only'))).toBe(true) + expect(createRequire(consumerA).resolve('commander')) + .toBe(realpathSync.native(join(anchorA, '..', 'node_modules', 'commander', 'index.js'))) + }) +}) + describe('resolveProfileDir', () => { it('joins the home and rejects traversal-shaped names', () => { const home = tmp() diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a2773904c8..428e5c0621 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -541,42 +541,24 @@ importers: '@deepseek-ai/cordis': specifier: workspace:^ version: link:../../vendor/cordis - '@deepseek-ai/cordis-plugin-include': - specifier: workspace:^ - version: link:../../vendor/include '@deepseek-ai/dsh': specifier: workspace:^ version: link:../cli - '@deepseek-ai/dsh-api-gateway': - specifier: workspace:^ - version: link:../../packages/api/gateway '@deepseek-ai/dsh-app-boot': specifier: workspace:^ version: link:../../packages/boot/app-boot '@deepseek-ai/dsh-client-connection': specifier: workspace:^ version: link:../../packages/client/connection - '@deepseek-ai/dsh-client-modules': - specifier: workspace:^ - version: link:../../packages/client/modules '@deepseek-ai/dsh-client-ui-directory-picker-native': specifier: workspace:^ version: link:../../packages/client/ui-directory-picker-native - '@deepseek-ai/dsh-cmdline': - specifier: workspace:^ - version: link:../../packages/boot/cmdline '@deepseek-ai/dsh-host-directory-picker-native': specifier: workspace:^ version: link:../../packages/host/directory-picker-native '@deepseek-ai/dsh-host-webserver': specifier: workspace:^ version: link:../../packages/host/webserver - '@deepseek-ai/dsh-launch-environment': - specifier: workspace:^ - version: link:../../packages/util/launch-environment - '@deepseek-ai/dsh-web-frontend': - specifier: workspace:^ - version: link:../web apps/web: devDependencies: diff --git a/tsconfig.base.json b/tsconfig.base.json index 245d733e82..2d6338f00a 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -28,6 +28,7 @@ // not declaration path aliases, keep each package/vendor source compiled // under its own tsconfig boundary. "paths": { + "@deepseek-ai/dsh/profile-boot": ["./apps/cli/src/profile-boot.ts"], "@deepseek-ai/cordis": ["./vendor/cordis/src"], "@deepseek-ai/cosmokit": ["./vendor/cosmokit/src"], "@deepseek-ai/schemastery": ["./vendor/schemastery/src"], From 8345ac129ea269dd7b26dd84f9960db290bbebce Mon Sep 17 00:00:00 2001 From: 07akioni <07akioni2@gmail.com> Date: Thu, 10 Sep 2026 22:29:49 +0800 Subject: [PATCH 02/35] fix(desktop): separate default port and replace plugin update prompt --- .../2026-09-10-desktop-web-wrapper.i18n.yaml | 4 +- .../2026-09-10-desktop-web-wrapper.md | 2 +- .../2026-09-10-desktop-web-wrapper.zh.md | 2 +- apps/desktop-host/src/index.ts | 2 +- apps/desktop/README.i18n.yaml | 4 +- apps/desktop/README.md | 4 +- apps/desktop/README.zh.md | 4 +- apps/desktop/renderer/plugin-manager.html | 8 +++ apps/desktop/renderer/plugin-manager.js | 28 +++++++++-- apps/desktop/src/locale.ts | 2 + apps/desktop/tests/plugin-manager.spec.ts | 50 +++++++++++++++++++ 11 files changed, 96 insertions(+), 14 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-09-10-desktop-web-wrapper.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-10-desktop-web-wrapper.i18n.yaml index c1f7e4c099..7868e341c5 100644 --- a/.agents/notes/implemented/architecture/2026-09-10-desktop-web-wrapper.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-10-desktop-web-wrapper.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-09-10-desktop-web-wrapper.md -2026-09-10-desktop-web-wrapper.md: 7a79f50763270058cd3a611f6b158209d138e6e3 -2026-09-10-desktop-web-wrapper.zh.md: b7c5b3ea7df00b89c59e26115342db2a05c3e837 +2026-09-10-desktop-web-wrapper.md: f37976f9216eadb78673f00a22c1fae1c78bce11 +2026-09-10-desktop-web-wrapper.zh.md: 401a9e6fdb82ef1a6e415c3bdf5cbb7226458439 diff --git a/.agents/notes/implemented/architecture/2026-09-10-desktop-web-wrapper.md b/.agents/notes/implemented/architecture/2026-09-10-desktop-web-wrapper.md index 7a79f50763..f37976f921 100644 --- a/.agents/notes/implemented/architecture/2026-09-10-desktop-web-wrapper.md +++ b/.agents/notes/implemented/architecture/2026-09-10-desktop-web-wrapper.md @@ -12,7 +12,7 @@ Separate Desktop composition and request transport require their own configurati The private Desktop Host invokes the CLI's shared profile runner against the independently owned Desktop profile. The complete Web composition owns authentication, HTTP routes, client assets, RPC, and response streaming. Electron loads the authenticated URL reported by the child. Child IPC carries readiness and shutdown; application requests travel directly over HTTP. -The shared runner owns profile and Harness-home patches, proxy setup, telemetry defaults, module fallbacks, configuration reload, and application lifecycle. Desktop preserves Web defaults and user configuration. Native directory selection is a Desktop overlay with an observable UI purpose; shell windows, menus, plugin management, recovery, and updates remain Electron responsibilities. +The shared runner owns profile and Harness-home patches, proxy setup, telemetry defaults, module fallbacks, configuration reload, and application lifecycle. Web and Desktop share application mechanisms while owning their deployment defaults. Desktop uses a separate default listener port so both applications can run concurrently; profile configuration can override it. Native directory selection is a Desktop overlay with an observable UI purpose; shell windows, menus, plugin management, recovery, and updates remain Electron responsibilities. The [bundled-runtime decision](2026-09-08-desktop-bundled-runtime-and-external-plugins.md) retains separate runtime and plugin storage, bundled Node.js and pnpm, and explicit package ownership. The [in-place decision](2026-09-09-desktop-in-place-profile.md) retains package transactions and partial-failure recovery. The public CLI continues to reject the reserved Desktop profile. diff --git a/.agents/notes/implemented/architecture/2026-09-10-desktop-web-wrapper.zh.md b/.agents/notes/implemented/architecture/2026-09-10-desktop-web-wrapper.zh.md index b7c5b3ea7d..401a9e6fdb 100644 --- a/.agents/notes/implemented/architecture/2026-09-10-desktop-web-wrapper.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-10-desktop-web-wrapper.zh.md @@ -12,7 +12,7 @@ Status: implemented 私有 Desktop Host 针对独立归属的 Desktop profile 调用 CLI 的共享 profile runner。完整 Web 组合负责认证、HTTP 路由、客户端资源、RPC 与响应流。Electron 加载子进程报告的认证 URL。子进程 IPC 承载就绪与关闭;应用请求直接通过 HTTP 传输。 -共享 runner 负责 profile 与 Harness-home patch、代理设置、遥测默认值、模块补全、配置重载及应用生命周期。Desktop 保留 Web 默认值与用户配置。原生目录选择是具有可见 UI 用途的 Desktop overlay;壳窗口、菜单、插件管理、恢复及更新仍由 Electron 负责。 +共享 runner 负责 profile 与 Harness-home patch、代理设置、遥测默认值、模块补全、配置重载及应用生命周期。Web 与 Desktop 共享应用机制,各自决定部署默认值。Desktop 使用独立的默认监听端口,使两个应用可以同时运行;profile 配置可以覆盖该端口。原生目录选择是具有可见 UI 用途的 Desktop overlay;壳窗口、菜单、插件管理、恢复及更新仍由 Electron 负责。 [内置运行时决策](2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md)保留独立运行时与插件存储、内置 Node.js 和 pnpm,以及明确的包归属。[原位修改决策](2026-09-09-desktop-in-place-profile.zh.md)保留包事务与部分失败恢复。公开 CLI 继续拒绝保留的 Desktop profile。 diff --git a/apps/desktop-host/src/index.ts b/apps/desktop-host/src/index.ts index fd8e84efff..285b496cc6 100644 --- a/apps/desktop-host/src/index.ts +++ b/apps/desktop-host/src/index.ts @@ -17,7 +17,7 @@ async function main(): Promise { profile: 'desktop', resolvedProfile: { profile, installAnchor }, patchFiles: [fileURLToPath(new URL('../config/desktop.cordis.patch.yml', import.meta.url))], - args: ['--no-open'], + args: ['--no-open', '--port', '19387'], }) const stop = async (): Promise => { // Startup failure is reported by main; shutdown only owns a tree that booted. diff --git a/apps/desktop/README.i18n.yaml b/apps/desktop/README.i18n.yaml index 82a08c0213..524b66d779 100644 --- a/apps/desktop/README.i18n.yaml +++ b/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: 8812ac195f8965785b9c5acda5b977e2b200a82d -README.zh.md: c6f763085828595196634aca62b51886944a2899 +README.md: ee1789c58d7d15946ebb06e1ecb148ededd652ea +README.zh.md: 8ac973aa96b3c3a4e8c40b97f79bfc85ba7e7909 diff --git a/apps/desktop/README.md b/apps/desktop/README.md index 8812ac195f..ee1789c58d 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -2,7 +2,7 @@ English | [中文](README.zh.md) -The desktop application is an Electron shell around the complete dsh Web application. A bundled upstream Node.js child starts the shared profile runner, and Electron loads its authenticated HTTP URL. Web owns client assets, API routes, and response streaming; Node IPC carries child readiness and shutdown. +The desktop application is an Electron shell around the complete dsh Web application. A bundled upstream Node.js child starts the shared profile runner, and Electron loads its authenticated HTTP URL. Web owns client assets, API routes, and response streaming; Node IPC carries child readiness and shutdown. Desktop defaults to port `19387`, separate from Web’s `3080`; a `webserver.config.port` patch can override it. ## Key technical decisions @@ -34,7 +34,7 @@ The signed `resources/dsh/desktop-runtime.json` binds the shell version, bundled 1. The main window displays a local loading page before profile preparation or backend startup. A fresh profile creates its manifest and shared package links while preserving unrelated files, then starts the actual backend once. Unchanged startups reuse the profile without scanning installed plugin manifests. 2. A compatible application upgrade refreshes shared links in the current profile without checking plugin peer requirements. Plugin files, configuration, versions, and lockfile remain in place; pnpm does not run. 3. Changes to bundled Node, platform, or architecture preserve installed plugins. Native incompatibilities surface during loading and can be repaired through pnpm. -4. Plugin add, update, and remove operations use bundled pnpm with its normal user and profile configuration. Desktop does not override the registry, npmrc, cache, or store, and new profiles add no build allowlist or strict-build setting. Update versions and ranges pass to pnpm. Package specs pass to pnpm, including local directories, Git, tarballs, and aliases. Relative paths resolve from the Desktop profile directory. Packages declaring `dsh.bundle.patch` activate as bundles; ordinary dependencies remain installed without activation. Desktop does not scan plugin dependency graphs or validate patch files before Host startup. Custom profile metadata and bundle order are retained. Unreadable installed metadata does not block listing, disabling, or removing dependencies; the list uses the dependency spec when the installed version is unavailable. +4. Plugin add, update, and remove operations use bundled pnpm with its normal user and profile configuration. Desktop does not override the registry, npmrc, cache, or store, and new profiles add no build allowlist or strict-build setting. The plugin-management page has an inline version form with cancellation; versions and ranges pass to pnpm, including the installed version for a reinstall. Package specs pass to pnpm, including local directories, Git, tarballs, and aliases. Relative paths resolve from the Desktop profile directory. Packages declaring `dsh.bundle.patch` activate as bundles; ordinary dependencies remain installed without activation. Desktop does not scan plugin dependency graphs or validate patch files before Host startup. Custom profile metadata and bundle order are retained. Unreadable installed metadata does not block listing, disabling, or removing dependencies; the list uses the dependency spec when the installed version is unavailable. 5. Plugin changes stop the backend before modifying the current profile. Successful preparation starts the Host. Package or Host startup failures retain modified files and report the error. Desktop creates no staging directories, activation journals, or rollback copies. The loading page does not depend on the Host. Errors offer restart and reinstallation guidance. Disabling plugins and resetting Desktop are offered when runtime resources support profile recovery, including development mode; early initialization failures expose restart alone. The plugin manager remains available through the application menu. Plugin changes have no automatic rollback. diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index c6f7630858..8ac973aa96 100644 --- a/apps/desktop/README.zh.md +++ b/apps/desktop/README.zh.md @@ -2,7 +2,7 @@ [English](README.md) | 中文 -桌面应用是完整 dsh Web 应用外的一层 Electron 壳。内置上游 Node.js 子进程启动共享 profile runner,Electron 加载其带认证的 HTTP URL。Web 负责客户端资源、API 路由与响应流;Node IPC 承载子进程就绪与关闭。 +桌面应用是完整 dsh Web 应用外的一层 Electron 壳。内置上游 Node.js 子进程启动共享 profile runner,Electron 加载其带认证的 HTTP URL。Web 负责客户端资源、API 路由与响应流;Node IPC 承载子进程就绪与关闭。Desktop 默认使用端口 `19387`,与 Web 的 `3080` 分开;可通过 `webserver.config.port` patch 覆盖。 ## 关键技术决策 @@ -34,7 +34,7 @@ Electron 根据应用 locale 选择类型化的英文或中文桌面壳文案, 1. 主窗口在 profile 准备或后端启动前显示本地加载页。新 profile 创建清单和共享包链接,保留无关文件,然后启动一次实际后端。未变化的启动复用 profile,不扫描已安装插件的清单。 2. 兼容的应用升级在当前 profile 中刷新共享链接,不检查插件的 peer 要求。插件文件、配置、版本和锁文件留在原处;不运行 pnpm。 3. 内置 Node 版本、平台或架构变化时保留已安装插件。原生兼容性问题在加载时报错,可通过 pnpm 修复。 -4. 插件添加、更新和删除使用内置 pnpm 及其正常的用户和 profile 配置。Desktop 不覆盖 registry、npmrc、缓存或 store,新 profile 不添加构建许可列表或严格构建设置。更新版本及范围交给 pnpm。包规格交给 pnpm,包括本地目录、Git、tarball 和别名。相对路径从 Desktop profile 目录解析。声明 `dsh.bundle.patch` 的包作为 bundle 启用;普通依赖安装后不自动启用。Desktop 不扫描插件依赖图,也不在 Host 启动前验证 patch 文件。自定义 profile 元数据和 bundle 顺序会保留。已安装元数据不可读时,仍能列出、禁用和删除依赖;无法读取已安装版本时,列表使用依赖规格。 +4. 插件添加、更新和删除使用内置 pnpm 及其正常的用户和 profile 配置。Desktop 不覆盖 registry、npmrc、缓存或 store,新 profile 不添加构建许可列表或严格构建设置。插件管理页提供可取消的行内版本表单;版本和范围交给 pnpm,也允许提交已安装版本以重装。包规格交给 pnpm,包括本地目录、Git、tarball 和别名。相对路径从 Desktop profile 目录解析。声明 `dsh.bundle.patch` 的包作为 bundle 启用;普通依赖安装后不自动启用。Desktop 不扫描插件依赖图,也不在 Host 启动前验证 patch 文件。自定义 profile 元数据和 bundle 顺序会保留。已安装元数据不可读时,仍能列出、禁用和删除依赖;无法读取已安装版本时,列表使用依赖规格。 5. 插件变更在直接修改当前 profile 前停止后端。准备成功后启动 Host。包操作或 Host 启动失败会保留已修改文件并报告错误。Desktop 不创建 staging 目录、激活日志或回滚副本。 加载页不依赖 Host。错误页提供重启和重装指导。运行时资源支持 profile 恢复时,即可禁用插件和重置 Desktop,包括开发模式;早期初始化失败只提供重启。应用菜单仍提供插件管理器入口。插件修改不自动回滚。 diff --git a/apps/desktop/renderer/plugin-manager.html b/apps/desktop/renderer/plugin-manager.html index 112fd1825f..81a954ef56 100644 --- a/apps/desktop/renderer/plugin-manager.html +++ b/apps/desktop/renderer/plugin-manager.html @@ -29,6 +29,14 @@ +

diff --git a/apps/desktop/renderer/plugin-manager.js b/apps/desktop/renderer/plugin-manager.js index c87460a49f..24f45c0cdd 100644 --- a/apps/desktop/renderer/plugin-manager.js +++ b/apps/desktop/renderer/plugin-manager.js @@ -24,6 +24,12 @@ async function main() { const form = document.querySelector('#install-form') const input = document.querySelector('#package-spec') const refresh = document.querySelector('#refresh') + const updateForm = document.querySelector('#update-form') + const updateVersion = document.querySelector('#update-version') + let updateName = '' + let updateTrigger + document.querySelector('#update-submit').textContent = messages.update + document.querySelector('#update-cancel').textContent = messages.cancel function setBusy(busy, statusMessage = '') { for (const control of document.querySelectorAll('button, input')) control.disabled = busy @@ -53,9 +59,13 @@ async function main() { update.type = 'button' update.textContent = messages.update update.addEventListener('click', () => { - const next = window.prompt(message('targetVersion', { name: plugin.name }), plugin.version)?.trim() - if (next === undefined || next === '' || next === plugin.version) return - void run(() => api.plugins.update(plugin.name, next), message('updating', { name: plugin.name })) + updateName = plugin.name + updateTrigger = update + document.querySelector('#update-label').textContent = message('targetVersion', { name: plugin.name }) + updateVersion.value = plugin.version + updateForm.hidden = false + updateVersion.focus() + updateVersion.select() }) const actions = document.createElement('span') actions.className = 'package-actions' @@ -106,6 +116,18 @@ async function main() { input.value = '' }, message('installing', { spec })) }) + updateForm.addEventListener('submit', (event) => { + event.preventDefault() + const version = updateVersion.value.trim() + if (version === '') return + const name = updateName + updateForm.hidden = true + void run(() => api.plugins.update(name, version), message('updating', { name })) + }) + document.querySelector('#update-cancel').addEventListener('click', () => { + updateForm.hidden = true + updateTrigger.focus() + }) 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)) diff --git a/apps/desktop/src/locale.ts b/apps/desktop/src/locale.ts index f8a324820c..5eb07c811e 100644 --- a/apps/desktop/src/locale.ts +++ b/apps/desktop/src/locale.ts @@ -40,6 +40,7 @@ export const en = { noPlugins: 'No Desktop plugins are installed.', remove: 'Remove', update: 'Update', + cancel: 'Cancel', targetVersion: 'Enter the target version for {name}', removing: 'Removing {name}…', updating: 'Updating {name}…', @@ -93,6 +94,7 @@ export const zh = { noPlugins: '还没有安装桌面插件。', remove: '移除', update: '更新', + cancel: '取消', targetVersion: '输入 {name} 的目标版本', removing: '正在移除 {name}…', updating: '正在更新 {name}…', diff --git a/apps/desktop/tests/plugin-manager.spec.ts b/apps/desktop/tests/plugin-manager.spec.ts index d870b7ecc7..4564ea8568 100644 --- a/apps/desktop/tests/plugin-manager.spec.ts +++ b/apps/desktop/tests/plugin-manager.spec.ts @@ -31,3 +31,53 @@ it('keeps disabled packages visible and offers recovery without a running backen await expect.poll(() => document.querySelector('#plugins li')?.textContent).toBe('example-plugin1.0.0DisableUpdateRemove') } finally { dom.window.close() } }) + +it.each(['en', 'zh-CN'])('updates through the inline form, including the installed version (%s)', async (language) => { + const dom = new JSDOM(readFileSync(new URL('../renderer/plugin-manager.html', import.meta.url), 'utf8'), { runScripts: 'outside-only' }) + const locale = resolveDesktopLocale(language) + const update = vi.fn(async () => {}) + Object.defineProperty(dom.window, 'dshDesktop', { value: { + locale: async () => locale, + backend: { status: async () => ({ phase: 'ready' }) }, + plugins: { list: async () => [{ name: 'example-plugin', version: '1.0.0', enabled: true }], update }, + } }) + 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') + const updateButton = () => document.querySelectorAll('#plugins li button')[1]! + const form = document.querySelector('#update-form')! + const version = document.querySelector('#update-version')! + updateButton().click() + expect(form.hidden).toBe(false) + expect(version.value).toBe('1.0.0') + expect(document.activeElement).toBe(version) + expect(document.querySelector('#update-label')?.textContent).toBe(locale.messages.targetVersion.replace('{name}', 'example-plugin')) + expect(document.querySelector('#update-cancel')?.textContent).toBe(locale.messages.cancel) + if (language === 'en') { + expect({ label: document.querySelector('#update-label')?.textContent, + actions: [...form.querySelectorAll('button')].map(button => button.textContent) }).toMatchInlineSnapshot(` + { + "actions": [ + "Update", + "Cancel", + ], + "label": "Enter the target version for example-plugin", + } + `) + } + document.querySelector('#update-cancel')!.click() + expect(form.hidden).toBe(true) + expect(document.activeElement).toBe(updateButton()) + expect(update).not.toHaveBeenCalled() + for (const target of ['1.0.0', '^2.0.0']) { + updateButton().click() + version.value = target + form.requestSubmit() + await expect.poll(() => document.querySelector('#status')?.textContent).toBe(locale.messages.operationComplete) + expect(update).toHaveBeenLastCalledWith('example-plugin', target) + expect(form.hidden).toBe(true) + } + expect(update).toHaveBeenCalledTimes(2) + } finally { dom.window.close() } +}) From 8c2fa73ceb7bd2b2719003beb72bdf82c552c562 Mon Sep 17 00:00:00 2001 From: 07akioni <07akioni2@gmail.com> Date: Thu, 10 Sep 2026 22:44:52 +0800 Subject: [PATCH 03/35] refactor(desktop): share profile initialization and plugin management --- ...on-desktop-packaging-and-updates.i18n.yaml | 4 +- ...-electron-desktop-packaging-and-updates.md | 1 - ...ectron-desktop-packaging-and-updates.zh.md | 1 - ...led-runtime-and-external-plugins.i18n.yaml | 4 +- ...op-bundled-runtime-and-external-plugins.md | 12 +- ...bundled-runtime-and-external-plugins.zh.md | 12 +- ...6-09-09-desktop-in-place-profile.i18n.yaml | 4 +- .../2026-09-09-desktop-in-place-profile.md | 2 +- .../2026-09-09-desktop-in-place-profile.zh.md | 2 +- .../2026-09-10-desktop-web-wrapper.i18n.yaml | 4 +- .../2026-09-10-desktop-web-wrapper.md | 6 + .../2026-09-10-desktop-web-wrapper.zh.md | 6 + apps/cli/src/plugin.ts | 80 ++------- apps/cli/tests/built-bin.e2e.ts | 44 +++++ apps/desktop/README.i18n.yaml | 4 +- apps/desktop/README.md | 13 +- apps/desktop/README.zh.md | 13 +- apps/desktop/package.json | 1 + apps/desktop/scripts/smoke-runtime.ts | 2 - apps/desktop/src/profile-packages.ts | 103 +++--------- apps/desktop/src/project-manager.ts | 158 ++++-------------- apps/desktop/src/runtime-tree.ts | 9 - apps/desktop/tests/plugin-pnpm.spec.ts | 10 +- apps/desktop/tests/profile-packages.spec.ts | 158 +++++++++++++----- apps/desktop/tests/project-manager.spec.ts | 62 +++---- apps/desktop/tests/runtime-fixture.ts | 12 +- apps/desktop/tests/runtime-tree.spec.ts | 4 +- apps/desktop/tsconfig.json | 1 + docs/architecture.i18n.yaml | 4 +- docs/architecture.md | 4 +- docs/architecture.zh.md | 4 +- packages/boot/app-boot/README.i18n.yaml | 4 +- packages/boot/app-boot/README.md | 5 + packages/boot/app-boot/README.zh.md | 5 + packages/boot/app-boot/src/index.ts | 6 + packages/boot/app-boot/src/profile-plugins.ts | 127 ++++++++++++++ packages/boot/app-boot/src/profile.ts | 13 ++ .../app-boot/tests/profile-plugins.spec.ts | 125 ++++++++++++++ packages/boot/app-boot/tests/profile.spec.ts | 28 ++++ pnpm-lock.yaml | 3 + 40 files changed, 643 insertions(+), 417 deletions(-) create mode 100644 packages/boot/app-boot/src/profile-plugins.ts create mode 100644 packages/boot/app-boot/tests/profile-plugins.spec.ts diff --git a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.i18n.yaml index cb477bd3f1..319212c10a 100644 --- a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.i18n.yaml +++ b/.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: 0456784f864ad6ee89d1c8717488f954984fdce7 -2026-08-25-electron-desktop-packaging-and-updates.zh.md: 8259a5ac30353e001ccf99bba4b9f2151e8ea01b +2026-08-25-electron-desktop-packaging-and-updates.md: 92dcd8b30ed43ed5a856e98649830402d7f0a5ff +2026-08-25-electron-desktop-packaging-and-updates.zh.md: b937baeb15e4058c65ca7d74dd02887a338491e0 diff --git a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md index 0456784f86..92dcd8b30e 100644 --- a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md +++ b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md @@ -48,7 +48,6 @@ The renderer uses `nodeIntegration: false`, `contextIsolation: true`, and `sandb pnpm-lock.yaml lock pnpm-workspace.yaml - desktop-runtime-state.json node_modules/ sessions/ storages/ diff --git a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md index 8259a5ac30..b937baeb15 100644 --- a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md @@ -48,7 +48,6 @@ Electron 拥有 `.dsh/profiles/desktop` 保留 profile。[内置运行时决策] pnpm-lock.yaml lock pnpm-workspace.yaml - desktop-runtime-state.json node_modules/ sessions/ storages/ diff --git a/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.i18n.yaml index 098306b93a..e624e58b81 100644 --- a/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.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-09-08-desktop-bundled-runtime-and-external-plugins.md -2026-09-08-desktop-bundled-runtime-and-external-plugins.md: e36e67313b5319416dab0ce354d7e483d66d7900 -2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md: b0122ae97a79b33e26e653ba9a8b7f3756d1ff93 +2026-09-08-desktop-bundled-runtime-and-external-plugins.md: 80c11592a16c50909cde072004f86d944f709fe8 +2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md: ddb25909c8c8906f3763e549e9485f3ffc632c7b diff --git a/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.md b/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.md index e36e67313b..80c11592a1 100644 --- a/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.md +++ b/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.md @@ -26,11 +26,11 @@ The [Desktop file policy](../../../../apps/desktop/scripts/runtime-file-policy.t 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 supplies missing packages through directory symlinks to those resources, or junctions on Windows; pnpm-installed packages take precedence. Links resolve to real host package directories under normal Node resolution. Host and plugin imports that resolve through these links 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. +The shared profile runner projects missing installation and selected-bundle dependencies within the Desktop profile. pnpm-installed packages take precedence. Links resolve to real package directories under normal Node resolution, so Host and plugin imports reaching the same export share its module instance. Distinct ESM and CommonJS conditional exports remain distinct entry points; a link cannot merge a package’s dual implementations. -External plugins use normal Node package resolution. Desktop does not recursively check peer versions, duplicate packages, linked packages, or ancestor dependency resolution. These checks duplicate package-manager and loader responsibilities and reject pnpm-supported installation sources. Shared host links remain available, but a plugin can resolve another installed copy; incompatible plugins may fail during Host startup and require recovery through the independent shell UI. 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. +External plugins use normal Node package resolution. Desktop does not recursively check peer versions, duplicate packages, linked packages, or ancestor dependency resolution. These checks duplicate package-manager and loader responsibilities and reject pnpm-supported installation sources. Shared fallback links supply missing packages, but a plugin can resolve another installed copy; incompatible plugins may fail during Host startup and require recovery through the independent shell UI. -The profile manifest records pnpm-installed 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 them. +The profile manifest records pnpm-installed dependencies separately from its enabled bundle list. Disabling a plugin preserves its package, lockfile entry, and user configuration. The [thin-wrapper decision](2026-09-10-desktop-web-wrapper.md) assigns initialization, bundle reconciliation, and module links to shared app-boot helpers; Desktop holds no separate link ledger or runtime-state identity. ## Transactions and upgrades @@ -40,16 +40,16 @@ Native canonical paths identify shared package directories. Windows launchers ca Dependency mutations use ordinary pnpm add and remove commands, including their configured lifecycle scripts. Installation sources and dependency resolution belong to pnpm. Bundle declarations select automatic activation; patch validation belongs to the bundle loader. Plain dependencies remain installed without activation. The bundled pnpm reads normal user and profile settings, including registry and build permissions. Desktop supplies no runtime build allowlist, strict-build setting, version-range restriction, or fixed profile identity. Unreadable package metadata does not prevent listing, disabling, or removing a dependency. Development uses the same manager against a separate plugin profile, with workspace packages supplied by the development runtime. -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 explicit recovery. Recorded host links identify owned directories independently of package-operation completion. +Desktop stops the Host before package mutations and waits for pnpm exit before restarting it. Shared cleanup removes only fallback-owned links, preserving pnpm entries. The [in-place decision](2026-09-09-desktop-in-place-profile.md) owns partial failures and explicit recovery. 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. ## 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. +Full runtime verification belongs to packaging. Startup reads the resource descriptor and checks shared package records and required Host entries. The [release-validation decision](2026-09-09-desktop-build-release-validation.md) assigns release and target compatibility checks to packaging. Startup neither enumerates nor hashes installed runtime files. Reading every file before backend loading adds I/O proportional to distribution size; unusable modules instead fail when loaded. Build-time verification 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. +- **Force host dependency versions into plugins.** This unnecessarily couples ordinary plugin dependencies to the host. Shared fallback supplies missing packages while pnpm-owned entries 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. diff --git a/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md b/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md index b0122ae97a..ddb25909c8 100644 --- a/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md @@ -26,11 +26,11 @@ Desktop 初始化时安装核心依赖图,会重复发布构建器已经完成 包专用排除项包括 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;pnpm 安装的包优先。正常 Node 解析会把链接解析到实际宿主包目录。通过这些链接解析的宿主与插件导入对每个已解析导出共享同一模块实例。不同的 ESM 与 CommonJS 条件导出仍是不同入口;链接不能合并包的两套实现。 +共享 profile runner 在 Desktop profile 内补全安装包与选中 bundle 缺失的依赖。pnpm 安装的包优先。链接通过正常 Node 解析指向真实包目录,因此 Host 与插件导入同一导出时共享其模块实例。不同的 ESM 与 CommonJS 条件导出仍是不同入口;链接不能合并包的双重实现。 -外部插件使用正常的 Node 包解析。Desktop 不递归检查 peer 版本、重复包、链接包或祖先目录依赖解析。这些检查重复了包管理器和加载器的职责,并拒绝 pnpm 支持的安装来源。共享宿主链接仍然可用,但插件可以解析到另一个已安装副本;不兼容插件可能在 Host 启动时失败,需要通过独立的桌面壳 UI 恢复。如果第三方包需要宿主范围的实例身份,必须明确加入运行时共享清单;版本号相同并不足够。 +外部插件使用正常 Node 包解析。Desktop 不递归检查 peer 版本、重复包、链接包或上级目录依赖解析。这些检查重复包管理器及加载器的职责,并拒绝 pnpm 支持的安装来源。共享补全链接提供缺失的包,但插件可以解析到另一份已安装副本;不兼容插件可能在 Host 启动时失败,需要通过独立壳 UI 恢复。 -profile manifest 分别记录pnpm 安装的依赖和已启用 bundle 列表。停用插件会保留其包、锁文件条目和用户配置。共享链接是 Desktop 拥有的派生状态,独立于 pnpm 记录;包管理器操作不携带这些链接,随后 Desktop 重建它们。 +profile manifest 分别记录 pnpm 安装的依赖及已启用 bundle 列表。禁用插件保留其包、锁文件条目及用户配置。[薄壳决策](2026-09-10-desktop-web-wrapper.zh.md)将初始化、bundle 协调和模块链接交给共享 app-boot helper;Desktop 不保存独立链接账本或运行时状态身份。 ## 事务与升级 @@ -40,16 +40,16 @@ profile manifest 分别记录pnpm 安装的依赖和已启用 bundle 列表。 依赖修改使用普通的 pnpm add 和 remove 命令,并遵循其生命周期脚本配置。安装来源和依赖解析由 pnpm 负责。bundle 声明决定自动启用;patch 验证由 bundle 加载器负责。普通依赖安装后不自动启用。内置 pnpm 读取正常的用户和 profile 设置,包括 registry 和构建权限。Desktop 不提供运行时构建许可列表、严格构建设置、版本范围限制或固定 profile 身份。包元数据不可读时,仍可列出、禁用或删除依赖。开发模式使用同一管理器操作独立的插件 profile,工作区包由开发运行时提供。 -Desktop 在包修改前停止 Host,并等待 pnpm 退出后再重启它。[直接修改决策](2026-09-09-desktop-in-place-profile.zh.md)规定部分失败和显式恢复的处理方式。记录的宿主链接用于识别自有目录,与包操作是否完成相互独立。 +Desktop 在包变更前停止 Host,并等待 pnpm 退出后重新启动。共享清理仅移除模块补全逻辑拥有的链接,保留 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。因此,启动不会通过校验和比较检测已安装内容的变化;不可用模块在加载时失败。构建时验证仍按记录的清单拒绝内容变化、缺失、多余或链接文件。 +完整运行时验证属于打包流程。启动读取资源描述文件,并检查共享包记录及必要的 Host 入口。[发布验证决策](2026-09-09-desktop-build-release-validation.zh.md)将发布与目标兼容性检查交给打包流程。启动既不枚举已安装运行时文件,也不计算其哈希。后端加载前读取每个文件会增加与分发体积成正比的 I/O;不可用模块改由加载时失败暴露。构建时验证按记录清单拒绝内容变化、缺失、多余或链接文件。 - **启动时安装内置离线 seed。** 这保留普通 pnpm 安装流程,但会在每台受影响机器上重复核心解压与安装。物化资源消除了这部分工作,代价是更多应用文件和发布构建器责任。 -- **把所有宿主依赖链接给插件。** 这会让普通插件依赖与宿主产生不必要的耦合。只链接明确的共享清单;私有包保留独立版本。 +- **强制插件使用 Host 依赖版本。** 这会让普通插件依赖不必要地耦合于 Host。共享模块补全提供缺失的包,pnpm 拥有的条目保留独立版本。 - **使用硬链接。** 它不能表示目录,可能无法跨卷,共享可写字节,并在应用替换后保留旧 inode。目录软链接和 Windows junction 能表达预期的包目标。 - **使用 `NODE_PATH` 或保留软链接路径。** 它们不能提供统一的 ESM 解析或共享模块身份。通过明确链接进行正常包查找可以直接测试。 - **把核心包留在 ASAR。** 后端使用上游 Node,而不是 Electron 修改过的文件系统。普通 `extraResources` 也能保留原生加载和子进程路径。 diff --git a/.agents/notes/implemented/architecture/2026-09-09-desktop-in-place-profile.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-09-desktop-in-place-profile.i18n.yaml index efab435b0d..23f7613c0e 100644 --- a/.agents/notes/implemented/architecture/2026-09-09-desktop-in-place-profile.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-09-desktop-in-place-profile.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-09-09-desktop-in-place-profile.md -2026-09-09-desktop-in-place-profile.md: e91ee4c04cfab07e70e222f34e92ece7766bf5b4 -2026-09-09-desktop-in-place-profile.zh.md: 6846b0fbf8f0ae8c44659735817c4e66d7abdf9d +2026-09-09-desktop-in-place-profile.md: 425145ad89f9697c2420544b0ce2e70759313ffc +2026-09-09-desktop-in-place-profile.zh.md: 8b98ec1c2e426b0019115a9a19eb84db4b9caef8 diff --git a/.agents/notes/implemented/architecture/2026-09-09-desktop-in-place-profile.md b/.agents/notes/implemented/architecture/2026-09-09-desktop-in-place-profile.md index e91ee4c04c..425145ad89 100644 --- a/.agents/notes/implemented/architecture/2026-09-09-desktop-in-place-profile.md +++ b/.agents/notes/implemented/architecture/2026-09-09-desktop-in-place-profile.md @@ -10,7 +10,7 @@ Staging preserves an old plugin installation but adds profile copying, directory ## 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 and approved native builds remain. Compatible upgrades refresh links without copying plugin files. +Desktop stops the Host and modifies the current profile directly. Shared app-boot cleanup detaches its own fallback links before package changes; the Host’s shared profile runner supplies required links on startup. Package locking and configured lifecycle scripts remain. Upgrades refresh module 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. diff --git a/.agents/notes/implemented/architecture/2026-09-09-desktop-in-place-profile.zh.md b/.agents/notes/implemented/architecture/2026-09-09-desktop-in-place-profile.zh.md index 6846b0fbf8..8b98ec1c2e 100644 --- a/.agents/notes/implemented/architecture/2026-09-09-desktop-in-place-profile.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-09-desktop-in-place-profile.zh.md @@ -10,7 +10,7 @@ staging 能保留旧插件安装,但增加 profile 复制、目录移动、恢 ## 决策 -Desktop 停止 Host 后直接修改当前 profile。修改包前解除宿主共享链接,操作结束后恢复链接。保留包锁和已批准的原生构建。兼容升级只刷新链接,不复制插件文件。 +Desktop 停止 Host 后直接修改当前 profile。共享 app-boot 清理在包变更前分离其拥有的模块补全链接;Host 的共享 profile runner 在启动时补全所需链接。包锁及配置允许的生命周期脚本保留。升级刷新模块链接,不复制插件文件。 包操作或 Host 失败会保留部分修改,供修复和重试。不使用 staging profile、激活日志、目录切换恢复或自动回滚。已有临时目录不会被解释或删除。 diff --git a/.agents/notes/implemented/architecture/2026-09-10-desktop-web-wrapper.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-10-desktop-web-wrapper.i18n.yaml index 7868e341c5..c832d35eb7 100644 --- a/.agents/notes/implemented/architecture/2026-09-10-desktop-web-wrapper.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-10-desktop-web-wrapper.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-09-10-desktop-web-wrapper.md -2026-09-10-desktop-web-wrapper.md: f37976f9216eadb78673f00a22c1fae1c78bce11 -2026-09-10-desktop-web-wrapper.zh.md: 401a9e6fdb82ef1a6e415c3bdf5cbb7226458439 +2026-09-10-desktop-web-wrapper.md: 19365f6448e7cb5183d35922cff4dafdc493a93a +2026-09-10-desktop-web-wrapper.zh.md: d78b96a772becb0d353504f7c32e0fb93811c4ff diff --git a/.agents/notes/implemented/architecture/2026-09-10-desktop-web-wrapper.md b/.agents/notes/implemented/architecture/2026-09-10-desktop-web-wrapper.md index f37976f921..19365f6448 100644 --- a/.agents/notes/implemented/architecture/2026-09-10-desktop-web-wrapper.md +++ b/.agents/notes/implemented/architecture/2026-09-10-desktop-web-wrapper.md @@ -16,6 +16,10 @@ The shared runner owns profile and Harness-home patches, proxy setup, telemetry The [bundled-runtime decision](2026-09-08-desktop-bundled-runtime-and-external-plugins.md) retains separate runtime and plugin storage, bundled Node.js and pnpm, and explicit package ownership. The [in-place decision](2026-09-09-desktop-in-place-profile.md) retains package transactions and partial-failure recovery. The public CLI continues to reject the reserved Desktop profile. +App-boot owns installed-dependency discovery, installation-first bundle declaration resolution, and bundle-list updates after pnpm succeeds. CLI selects automatic activation; Desktop explicitly preserves bundles disabled through its UI. The policy difference belongs to the visible activation control, while metadata handling and reconciliation remain shared. + +Shared `initProfile` creates missing profile files and preserves existing content. The Host’s `healIsolatedProfileModuleFallback` is the sole owner of installation and bundle projections; package operations use shared `unlinkProfileModuleFallback` to detach only its own links before pnpm. pnpm-managed directories retain priority. Desktop maintains no second runtime-state, lockfile hash, or link reconciliation mechanism. One-time cleanup of `desktop-runtime-state.json` removes only matching recorded links and retires that metadata. + This partially supersedes the private composition and portless transport in the [packaging decision](2026-08-25-electron-desktop-packaging-and-updates.md). That design avoided listening ports and used framed byte pipes to avoid Base64 expansion and cross-version V8 serialization. Shared HTTP gives up the portless guarantee and assigns serving and authentication to the existing Web implementation. Release identity, signing, process ownership, and native shell features remain active decisions. ## Alternatives considered @@ -24,6 +28,8 @@ This partially supersedes the private composition and portless transport in the **Merge CLI and Desktop plugin installations.** Shared boot code does not require shared executable dependencies. Separate installations allow independently qualified releases and plugin versions while their existing data owners govern shared sessions and settings. +**Keep a Desktop link ledger and manifest reconciler.** These duplicate shared profile mechanisms and can reject otherwise usable installations when derived metadata drifts. A single fallback owner can protect pnpm directories without maintaining release identity in the plugin profile. + ## Consequences Desktop inherits Web features through the same boot and serving path. HTTP listener ownership and authentication remain part of application startup, and Electron must load the ready URL instead of assuming a port or translating requests. The independent loading and recovery window remains available before the Web application starts. diff --git a/.agents/notes/implemented/architecture/2026-09-10-desktop-web-wrapper.zh.md b/.agents/notes/implemented/architecture/2026-09-10-desktop-web-wrapper.zh.md index 401a9e6fdb..d78b96a772 100644 --- a/.agents/notes/implemented/architecture/2026-09-10-desktop-web-wrapper.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-10-desktop-web-wrapper.zh.md @@ -16,6 +16,10 @@ Status: implemented [内置运行时决策](2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md)保留独立运行时与插件存储、内置 Node.js 和 pnpm,以及明确的包归属。[原位修改决策](2026-09-09-desktop-in-place-profile.zh.md)保留包事务与部分失败恢复。公开 CLI 继续拒绝保留的 Desktop profile。 +App-boot 负责已安装依赖发现、安装目录优先的 bundle 声明解析及 pnpm 成功后的 bundle 列表更新。CLI 选择自动激活;Desktop 显式保留通过 UI 禁用的 bundle。策略差异属于可见的启用控件,元数据处理与协调逻辑仍然共享。 + +共享 `initProfile` 创建缺失的 profile 文件并保留现有内容。Host 的 `healIsolatedProfileModuleFallback` 是安装包与 bundle 投影的唯一归属方;包操作在 pnpm 前通过共享 `unlinkProfileModuleFallback` 仅分离它自己拥有的链接。pnpm 管理的目录保持优先。Desktop 不维护第二套运行时状态、锁文件哈希或链接协调机制。`desktop-runtime-state.json` 的一次性清理仅移除与记录匹配的链接,并清除该元数据。 + 本记录部分取代[打包决策](2026-08-25-electron-desktop-packaging-and-updates.zh.md)中的私有组合与无端口传输。该设计避免监听端口,并使用分帧字节管道避免 Base64 膨胀与跨版本 V8 序列化。共享 HTTP 放弃无端口保证,将服务与认证交给已有 Web 实现。发布身份、签名、进程归属及原生壳功能仍是有效决策。 ## Alternatives considered @@ -24,6 +28,8 @@ Status: implemented **合并 CLI 与 Desktop 插件安装。** 共享启动代码不要求共享可执行依赖。独立安装允许分别验收发布与插件版本,共享会话和设置则仍由已有数据归属方负责。 +**保留 Desktop 链接账本与 manifest 协调器。** 这些机制重复共享 profile 逻辑,并可能因派生元数据漂移而拒绝原本可用的安装。单一模块补全归属方可以保护 pnpm 目录,无需在插件 profile 中维护发布身份。 + ## Consequences Desktop 通过相同启动与服务路径继承 Web 功能。HTTP 监听归属与认证仍属于应用启动,Electron 必须加载就绪 URL,而不是假设端口或转换请求。独立加载与恢复窗口在 Web 应用启动前仍可用。 diff --git a/apps/cli/src/plugin.ts b/apps/cli/src/plugin.ts index 70741703c4..f00d703808 100644 --- a/apps/cli/src/plugin.ts +++ b/apps/cli/src/plugin.ts @@ -17,79 +17,14 @@ import { DEFAULT_PROFILE_BUNDLES, initProfile, PROFILE_TEMPLATES, - readProfileManifest, - resolveBundleDir, + readProfilePlugins, + reconcileProfilePlugins, resolveProfileDir, - writeProfileManifest, - type ProfileManifest, } from '@deepseek-ai/dsh-app-boot' import { INSTALL_ANCHOR } from './profile-boot.ts' const NAME = 'dsh' -/** - * Whether a resolved dependency exports a profile patch, i.e. is a bundle. - * @param packageName - the dependency's package name. - * @param profileDir - the profile directory (resolution anchor). - * @returns true when the package manifest declares `dsh.bundle`. - */ -function exportsPatch(packageName: string, profileDir: string): boolean { - let dir: string - try { - dir = resolveBundleDir(NAME, packageName, INSTALL_ANCHOR, profileDir) - } catch { - return false // pnpm reported success yet the package is unresolvable — treat as plain - } - const manifest = readProfileManifest(NAME, dir) - return manifest.dsh?.bundle?.patch !== undefined -} - -/** - * Reconcile `dsh.profile.bundles` against the installed state: pnpm has - * already written the real installed names (so a git/path/tarball/alias spec - * on the command line reconciles by its true package name) and materialized - * the packages. A dependency that resolves to a `dsh.bundle`-declaring - * package joins the layer stack (appended in dependency order); a - * dependency-listed name that no longer does — removed, or the installed - * version dropped the declaration — leaves it. In-box bundles from the - * profile template are not dependencies and are never touched. Warns once - * per newly-added bundle-less dependency (a plain library is fine; the - * warning is orientation). - */ -function reconcilePlugins(before: ProfileManifest, profileDir: string): void { - const after = readProfileManifest(NAME, profileDir) - const beforeDeps = new Set(Object.keys(before.dependencies ?? {})) - const dependencies = Object.keys(after.dependencies ?? {}) - const plugins = after.dsh?.profile?.bundles ?? [] - let changed = false - for (const packageName of dependencies) { - const isBundle = exportsPatch(packageName, profileDir) - if (isBundle && !plugins.includes(packageName)) { - plugins.push(packageName) - changed = true - } else if (!isBundle && !beforeDeps.has(packageName)) { - process.stderr.write( - `${NAME}: warning: ${packageName} declares no dsh.bundle — installed as a plain dependency, not a profile layer ` - + '(a later update that gains one activates it automatically)\n', - ) - } - } - const dependencySet = new Set(dependencies) - for (const packageName of [...plugins]) { - // Only dependency-managed entries are subject to removal; template - // bundles (dsh-base and friends) are not dependencies. - const wasDependency = beforeDeps.has(packageName) || dependencySet.has(packageName) - const stillBundle = dependencySet.has(packageName) && exportsPatch(packageName, profileDir) - if (wasDependency && !stillBundle) { - plugins.splice(plugins.indexOf(packageName), 1) - changed = true - } - } - if (!changed) return - after.dsh = { ...after.dsh, profile: { ...after.dsh?.profile, bundles: plugins } } - writeProfileManifest(profileDir, after) -} - /** * Rewrite relative filesystem specs against the user's invoking directory. * pnpm runs with cwd = the profile directory, so a bare `.` or `../plugin` @@ -128,7 +63,8 @@ export function runPlugin(profile: string, args: readonly string[]): number { ) process.stderr.write(`${NAME}: initialized profile ${profile} at ${dir}\n`) } - const before = readProfileManifest(NAME, dir) + const location = { binName: NAME, profileDir: dir, installAnchor: INSTALL_ANCHOR } + const before = readProfilePlugins(location) // Windows resolves pnpm through its .cmd shim, which spawn() refuses // without a shell since the CVE-2024-27980 hardening. const result = spawnSync('pnpm', args.map(argument => anchorPathSpec(argument, process.cwd())), { @@ -146,7 +82,13 @@ export function runPlugin(profile: string, args: readonly string[]): number { } const exitCode = result.status ?? 1 if (exitCode === 0) { - reconcilePlugins(before, dir) + const result = reconcileProfilePlugins({ ...location, before, preserveDisabled: false }) + for (const packageName of result.addedPlainDependencies) { + process.stderr.write( + `${NAME}: warning: ${packageName} declares no dsh.bundle — installed as a plain dependency, not a profile layer ` + + '(a later update that gains one activates it automatically)\n', + ) + } } else { // pnpm's own diagnostics name pnpm-workspace.yaml without saying WHICH // one; the profile owns it, and the commonest failure here is pnpm ≥10 diff --git a/apps/cli/tests/built-bin.e2e.ts b/apps/cli/tests/built-bin.e2e.ts index ef606d49af..c2f273198c 100644 --- a/apps/cli/tests/built-bin.e2e.ts +++ b/apps/cli/tests/built-bin.e2e.ts @@ -970,6 +970,50 @@ describe.skipIf(!existsSync(dshBin))('dsh BUILT bin (node lib/bin.js, no tsx)', } }, SPAWN_TIMEOUT_MS * 2 + 30_000) + it('reconciles a real pnpm alias and keeps ordinary dependencies outside the bundle list', async () => { + const home = mkdtempSync(join(tmpdir(), 'dsh-plugin-alias-')) + try { + const bundle = join(home, 'bundle-source') + const library = join(home, 'library-source') + mkdirSync(bundle) + mkdirSync(library) + writeFileSync(join(bundle, 'package.json'), JSON.stringify({ + name: 'original-bundle-name', version: '1.0.0', dsh: { bundle: { patch: './cordis.patch.yml' } }, + })) + writeFileSync(join(bundle, 'cordis.patch.yml'), '[]\n') + writeFileSync(join(library, 'package.json'), JSON.stringify({ name: 'ordinary-library', version: '1.0.0' })) + const added = await runBuiltBin([ + 'plugin', '--profile', 'alias', 'add', `bundle-alias@file:${bundle}`, `file:${library}`, + ], { DSH_HOME: home }, home) + expect(added.code).toBe(0) + expect(added.stderr).toContain('ordinary-library declares no dsh.bundle — installed as a plain dependency, not a profile layer') + const manifestPath = join(home, 'profiles', 'alias', 'package.json') + const installed = JSON.parse(readFileSync(manifestPath, 'utf8')) as { + dependencies: Record + dsh: { profile: { bundles: string[] } } + } + expect(Object.keys(installed.dependencies).sort()).toEqual(['bundle-alias', 'ordinary-library']) + expect(installed.dsh.profile.bundles).toEqual(['@deepseek-ai/dsh-base', 'bundle-alias']) + installed.dsh.profile.bundles = ['@deepseek-ai/dsh-base'] + writeFileSync(manifestPath, JSON.stringify(installed)) + const refreshed = await runBuiltBin(['plugin', '--profile', 'alias', 'root'], { DSH_HOME: home }, home) + expect(refreshed.code).toBe(0) + expect(refreshed.stderr).not.toContain('declares no dsh.bundle') + const active = JSON.parse(readFileSync(manifestPath, 'utf8')) as { dsh: { profile: { bundles: string[] } } } + expect(active.dsh.profile.bundles).toContain('bundle-alias') + const removed = await runBuiltBin(['plugin', '--profile', 'alias', 'remove', 'bundle-alias'], { DSH_HOME: home }, home) + expect(removed.code).toBe(0) + const remaining = JSON.parse(readFileSync(manifestPath, 'utf8')) as { + dependencies: Record + dsh: { profile: { bundles: string[] } } + } + expect(Object.keys(remaining.dependencies)).toEqual(['ordinary-library']) + expect(remaining.dsh.profile.bundles).toEqual(['@deepseek-ai/dsh-base']) + } finally { + rmSync(home, { recursive: true, force: true }) + } + }) + it('activates a dependency that gained dsh.bundle in a later update', async () => { // Reconcile runs against the INSTALLED state on every successful pnpm // run, so `update` (not only `add`) activates a package whose newer diff --git a/apps/desktop/README.i18n.yaml b/apps/desktop/README.i18n.yaml index 524b66d779..b0f0753a93 100644 --- a/apps/desktop/README.i18n.yaml +++ b/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: ee1789c58d7d15946ebb06e1ecb148ededd652ea -README.zh.md: 8ac973aa96b3c3a4e8c40b97f79bfc85ba7e7909 +README.md: 8976fd23a5ad77f35da0182d6fb5761e96af80c9 +README.zh.md: ef1689e30975d65690e04861763419c494c3b8e6 diff --git a/apps/desktop/README.md b/apps/desktop/README.md index ee1789c58d..8976fd23a5 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -11,7 +11,7 @@ The desktop application is an Electron shell around the complete dsh Web applica | Release identity | The shell API, Web client, backend, and plugin graph are qualified as one combination; independent versions would create untested combinations and ambiguous update availability. | Electron and `@deepseek-ai/dsh` always have the same exact version. A dsh upgrade is a Desktop release, even when the shell code is unchanged. | | Runtime | Electron's Node.js carries Electron patches, fuses, ABI, and lifecycle constraints, while system runtimes and package-manager state are uncontrolled. | dsh runs under the bundled upstream Node.js and every package operation uses the bundled pnpm. Package-manager configuration and the Host environment follow the user's settings. | | Package sources | Core installation at startup adds work even when offline. | `extraResources/dsh` carries a complete production dependency tree; the profile installs only external plugins. | -| Shared modules | Host APIs can depend on module identity. | Desktop links every bundled first-party package into the profile using directory symlinks, or Windows junctions; ordinary plugin dependencies remain local. | +| Shared modules | Host APIs can depend on module identity. | The shared profile runner projects missing installation and bundle dependencies inside the Desktop profile; pnpm-managed packages take precedence. | | State ownership | Sharing executable dependency graphs would let CLI and Desktop change each other's dsh, Cordis, plugin, or native-module versions, while two desktop processes could race on the same profile. | Electron acquires its process-lifetime single-instance lock before any profile access and exclusively owns `$DSH_HOME/profiles/desktop` plus its package-manager state. CLI and Desktop share supported product data under `$DSH_HOME`, but never executable packages, plugin activation, lockfiles, or `node_modules`. | | Transport | Reusing Web serving and authentication keeps application behavior in one implementation. | Electron loads the Host’s authenticated HTTP URL directly; child IPC carries lifecycle messages, and the local shell protocol serves startup and management pages. | | Plugin changes | Package installation and Host startup can fail. | Desktop stops the Host and modifies the current profile directly. Failures retain partial changes for explicit repair; there is no automatic profile rollback. | @@ -25,23 +25,27 @@ Electron owns `$DSH_HOME/profiles/desktop`. Its `dependencies` contains packages The local startup page exposes startup status and available recovery actions. The product renderer uses the Web application’s HTTP APIs. The separate plugin window receives structured list, install, remove, update, and update-check operations; neither renderer receives filesystem access, raw Electron IPC, a shell, or arbitrary pnpm arguments. +The product UI retains Web actions, including "Open In..." through the shared authenticated HTTP routes. Desktop supplies its native directory picker as a profile overlay. + Electron chooses typed English or Chinese shell copy from its application locale and falls back to English. Menus, native dialogs, the startup page, and the plugin-management renderer use the same locale payload; the repository Client UI i18n gate checks these desktop sources. ### Runtime and plugin activation The signed `resources/dsh/desktop-runtime.json` binds the shell version, bundled Node version, platform, architecture, shared package versions, and final file inventory. Startup reads the metadata and checks shared package records. Release schema, shell version, target compatibility, and file integrity are verified during packaging. Core packages are never copied into profile storage or installed by pnpm at first launch. -1. The main window displays a local loading page before profile preparation or backend startup. A fresh profile creates its manifest and shared package links while preserving unrelated files, then starts the actual backend once. Unchanged startups reuse the profile without scanning installed plugin manifests. -2. A compatible application upgrade refreshes shared links in the current profile without checking plugin peer requirements. Plugin files, configuration, versions, and lockfile remain in place; pnpm does not run. +1. The main window displays a local loading page before profile preparation or backend startup. Shared profile initialization creates missing manifest, empty user patch, and pnpm workspace files without overwriting existing files. The actual Host starts once and supplies missing module links through the shared profile runner. +2. On application upgrades, the shared profile runner refreshes its owned module links without checking plugin peer requirements. Plugin files, configuration, versions, and lockfile remain in place; pnpm does not run. 3. Changes to bundled Node, platform, or architecture preserve installed plugins. Native incompatibilities surface during loading and can be repaired through pnpm. 4. Plugin add, update, and remove operations use bundled pnpm with its normal user and profile configuration. Desktop does not override the registry, npmrc, cache, or store, and new profiles add no build allowlist or strict-build setting. The plugin-management page has an inline version form with cancellation; versions and ranges pass to pnpm, including the installed version for a reinstall. Package specs pass to pnpm, including local directories, Git, tarballs, and aliases. Relative paths resolve from the Desktop profile directory. Packages declaring `dsh.bundle.patch` activate as bundles; ordinary dependencies remain installed without activation. Desktop does not scan plugin dependency graphs or validate patch files before Host startup. Custom profile metadata and bundle order are retained. Unreadable installed metadata does not block listing, disabling, or removing dependencies; the list uses the dependency spec when the installed version is unavailable. 5. Plugin changes stop the backend before modifying the current profile. Successful preparation starts the Host. Package or Host startup failures retain modified files and report the error. Desktop creates no staging directories, activation journals, or rollback copies. +CLI and Desktop use the same installed-dependency inventory and bundle reconciliation. Bundle declarations resolve with the same installation-first precedence as startup. CLI operations automatically enable installed bundles; Desktop preserves bundles disabled through its UI across updates. Neither path requires readable installed metadata to list or remove a dependency. + The loading page does not depend on the Host. Errors offer restart and reinstallation guidance. Disabling plugins and resetting Desktop are offered when runtime resources support profile recovery, including development mode; early initialization failures expose restart alone. The plugin manager remains available through the application menu. Plugin changes have no automatic rollback. Reset deletes every entry in `$DSH_HOME/profiles/desktop` except the held transaction lock, then initializes the built-in profile. It removes Desktop configuration and installed third-party packages without a backup. Shared tasks, settings, and the Harness-home `.env` are untouched. Shell resource and preload failures use a self-contained document with the available recovery actions and diagnostics; its controls do not require preload. -Package transactions hold `$DSH_HOME/profiles/desktop/lock` exclusively through pnpm process exit. Reset preserves the directory and its lock until initialization and Host startup finish. Shared links use directory symlinks on macOS/Linux and junctions on Windows; cleanup removes links without deleting their targets. Canonical filesystem paths identify shared packages, so Windows path casing alone does not trigger profile activation. Native builds follow pnpm’s configured build policy. Release preparation owns its separate build-time allowlist. +Package transactions hold `$DSH_HOME/profiles/desktop/lock` exclusively through pnpm process exit. Before pnpm runs, the shared module-fallback helper removes only its owned links and preserves pnpm-managed directories; the Host recreates needed links on startup. Reset preserves the profile directory and its lock until initialization and Host startup finish. Link cleanup preserves target directories. Native builds follow pnpm’s configured build policy; release preparation owns its separate build-time allowlist. ## Develop @@ -196,7 +200,6 @@ An unpackaged Electron process uses `.desktop-build/development/project` under i ## Known limitations -- The Web "Open In..." action is disabled in Desktop because its host plugin requires HTTP routes; Desktop does not provide a `webServer`. - Release signing, notarization, update hosting, and previous-version installed-artifact qualification require the production release environment. - Dependency lifecycle scripts follow pnpm’s build permissions; Desktop provides no separate approval dialog. - The desktop shell shares sessions, settings, credentials, workspaces, and storage under `$DSH_HOME` with CLI dsh, while executable packages, plugin activation, and lockfiles remain separate. diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index 8ac973aa96..ef1689e309 100644 --- a/apps/desktop/README.zh.md +++ b/apps/desktop/README.zh.md @@ -11,7 +11,7 @@ | 发布身份 | 桌面壳 API、Web 客户端、后端与插件依赖图作为一个组合完成验证;独立版本会产生未经验证的组合,并让更新可用性含糊不清。 | Electron 与 `@deepseek-ai/dsh` 始终使用同一精确版本。即使桌面壳代码不变,升级 dsh 也必须发布新 Desktop 版本。 | | 运行时 | Electron 的 Node.js 带有 Electron 补丁、fuse、ABI 与生命周期约束,而系统运行时和包管理器状态不可控。 | dsh 通过内置的上游 Node.js 运行,所有包操作都使用内置 pnpm。包管理器配置和 Host 环境遵循用户设置。 | | 包来源 | 即使离线,启动时安装核心依赖也会增加开销。 | `extraResources/dsh` 携带完整生产依赖树;profile 只安装外部插件。 | -| 共享模块 | 宿主 API 可能依赖模块实例身份。 | Desktop 用目录软链接或 Windows junction 把每个内置第一方包连接到 profile;普通插件依赖保留在本地。 | +| 共享模块 | Host API 可能依赖模块身份。 | 共享 profile runner 在 Desktop profile 内补全安装包与 bundle 缺失的依赖;pnpm 管理的包优先。 | | 状态归属 | 共享可执行依赖图会让 CLI(命令行界面)与 Desktop 相互改变 dsh、Cordis、插件或原生模块版本,而两个桌面进程还可能争用同一个 profile。 | Electron 在访问任何 profile 前获取进程生命周期单实例锁,并独占 `$DSH_HOME/profiles/desktop` 及其包管理器状态。CLI 与 Desktop 共享 `$DSH_HOME` 下受支持的产品数据,但绝不共享可执行包、插件激活、锁文件或 `node_modules`。 | | 传输 | 复用 Web 服务与认证,让应用行为由同一份实现负责。 | Electron 直接加载 Host 的认证 HTTP URL;子进程 IPC 承载生命周期消息,本地壳协议提供启动和管理页面。 | | 插件变更 | 包安装和 Host 启动可能失败。 | Desktop 停止 Host 后直接修改当前 profile。失败保留部分修改供用户修复,不自动回滚 profile。 | @@ -25,23 +25,27 @@ Electron 拥有 `$DSH_HOME/profiles/desktop`。其 `dependencies` 包含 pnpm 本地启动页面展示启动状态及可用恢复操作。产品渲染进程使用 Web 应用的 HTTP API。独立插件窗口接收结构化的列表、安装、移除、更新和检查更新操作;两个渲染进程都不会获得文件系统、原始 Electron IPC、shell 或任意 pnpm 参数访问权。 +产品 UI 保留 Web 操作,包括通过共享认证 HTTP 路由执行的“打开方式…”。Desktop 通过 profile overlay 提供原生目录选择器。 + Electron 根据应用 locale 选择类型化的英文或中文桌面壳文案,并以英文作为 fallback。菜单、原生对话框、启动页与插件管理渲染进程使用同一 locale 数据;仓库的 Client UI i18n gate 会检查这些桌面源文件。 ### 运行时与插件激活 签名资源中的 `resources/dsh/desktop-runtime.json` 绑定 shell 版本、内置 Node 版本、平台、架构、共享包版本和最终文件清单。启动读取元数据,并检查共享包记录。发布 schema、shell 版本、目标兼容性和文件完整性在打包时验证。首次启动不会把核心包复制到 profile 存储或通过 pnpm 安装核心包。 -1. 主窗口在 profile 准备或后端启动前显示本地加载页。新 profile 创建清单和共享包链接,保留无关文件,然后启动一次实际后端。未变化的启动复用 profile,不扫描已安装插件的清单。 -2. 兼容的应用升级在当前 profile 中刷新共享链接,不检查插件的 peer 要求。插件文件、配置、版本和锁文件留在原处;不运行 pnpm。 +1. 主窗口在 profile 准备或后端启动前显示本地加载页。共享 profile 初始化创建缺失的 manifest、空用户 patch 与 pnpm workspace 文件,不覆盖现有文件。实际 Host 仅启动一次,并通过共享 profile runner 补全缺失的模块链接。 +2. 应用升级时,共享 profile runner 刷新其拥有的模块链接,不检查插件 peer 要求。插件文件、配置、版本与锁文件保留原位;不运行 pnpm。 3. 内置 Node 版本、平台或架构变化时保留已安装插件。原生兼容性问题在加载时报错,可通过 pnpm 修复。 4. 插件添加、更新和删除使用内置 pnpm 及其正常的用户和 profile 配置。Desktop 不覆盖 registry、npmrc、缓存或 store,新 profile 不添加构建许可列表或严格构建设置。插件管理页提供可取消的行内版本表单;版本和范围交给 pnpm,也允许提交已安装版本以重装。包规格交给 pnpm,包括本地目录、Git、tarball 和别名。相对路径从 Desktop profile 目录解析。声明 `dsh.bundle.patch` 的包作为 bundle 启用;普通依赖安装后不自动启用。Desktop 不扫描插件依赖图,也不在 Host 启动前验证 patch 文件。自定义 profile 元数据和 bundle 顺序会保留。已安装元数据不可读时,仍能列出、禁用和删除依赖;无法读取已安装版本时,列表使用依赖规格。 5. 插件变更在直接修改当前 profile 前停止后端。准备成功后启动 Host。包操作或 Host 启动失败会保留已修改文件并报告错误。Desktop 不创建 staging 目录、激活日志或回滚副本。 +CLI 与 Desktop 共用已安装依赖清单及 bundle 列表协调逻辑。bundle 声明遵循与启动一致的安装目录优先解析顺序。CLI 操作自动启用已安装 bundle;Desktop 更新后保留通过 UI 禁用的 bundle 状态。两条路径都不要求已安装元数据可读才能列出或移除依赖。 + 加载页不依赖 Host。错误页提供重启和重装指导。运行时资源支持 profile 恢复时,即可禁用插件和重置 Desktop,包括开发模式;早期初始化失败只提供重启。应用菜单仍提供插件管理器入口。插件修改不自动回滚。 重置删除 `$DSH_HOME/profiles/desktop` 中除所持事务锁外的所有条目,然后初始化内置 profile。它删除 Desktop 配置和已安装第三方包,不保留备份。共享任务、设置和 Harness-home `.env` 保持不变。壳资源和 preload 失败时使用独立文档显示可用恢复操作和诊断;其控件不依赖 preload。 -包事务独占持有 `$DSH_HOME/profiles/desktop/lock`,直到 pnpm 进程退出。重置保留目录及其锁,直到初始化和 Host 启动完成。共享链接在 macOS/Linux 使用目录软链接,在 Windows 使用 junction;清理只移除链接,不删除其目标。共享包使用文件系统的规范路径识别,因此 Windows 路径大小写变化不会单独触发 profile 激活。原生构建遵循 pnpm 的构建配置。发布准备阶段拥有独立的构建许可列表。 +包事务独占 `$DSH_HOME/profiles/desktop/lock` 直到 pnpm 进程退出。pnpm 运行前,共享模块补全 helper 仅移除其拥有的链接,并保留 pnpm 管理的目录;Host 在启动时重新创建所需链接。重置保留 profile 目录与锁,直到初始化和 Host 启动结束。链接清理保留目标目录。原生构建遵循 pnpm 配置的构建策略;发布准备负责独立的构建时许可列表。 ## 开发 @@ -196,7 +200,6 @@ pnpm run prepare:desktop ## 已知限制 -- Desktop 禁用 Web 的「在本地应用中打开…」操作,因为其 Host 插件依赖 HTTP 路由,而 Desktop 不提供 `webServer`。 - 发布签名、公证、更新托管和跨上一版本的已安装产物验证需要生产发布环境。 - 依赖的生命周期脚本遵循 pnpm 的构建权限;Desktop 不提供单独的审批对话框。 - 桌面壳与 CLI dsh 共享 `$DSH_HOME` 下的会话、设置、凭据、工作区和存储,但可执行包、插件激活和锁文件彼此隔离。 diff --git a/apps/desktop/package.json b/apps/desktop/package.json index ef0f3ae71b..2050d2ced1 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -34,6 +34,7 @@ }, "devDependencies": { "@aws-sdk/client-s3": "3.1067.0", + "@deepseek-ai/dsh-app-boot": "workspace:^", "@deepseek-ai/dsh-home-paths": "workspace:^", "@electron/notarize": "2.5.0", "@types/js-yaml": "^4.0.9", diff --git a/apps/desktop/scripts/smoke-runtime.ts b/apps/desktop/scripts/smoke-runtime.ts index 9a0f79113d..c241598fe5 100644 --- a/apps/desktop/scripts/smoke-runtime.ts +++ b/apps/desktop/scripts/smoke-runtime.ts @@ -5,7 +5,6 @@ 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 } from '../src/profile-packages.ts' import type { DesktopRuntimeDescriptor } from '../src/runtime-tree.ts' /** @@ -46,7 +45,6 @@ export function apply(ctx) { manifest.dsh.profile.bundles.push(pluginName) writeFileSync(join(profile, 'package.json'), JSON.stringify(manifest)) writeFileSync(join(profile, 'cordis.patch.yml'), '- id: webserver\n config:\n host: 127.0.0.1\n port: 0\n') - linkDesktopHostPackages(profile, root, runtime) const ready = await host.start() const login = await fetch(ready.url, { redirect: 'manual' }) const cookie = login.headers.getSetCookie().map(value => value.split(';')[0]).join('; ') diff --git a/apps/desktop/src/profile-packages.ts b/apps/desktop/src/profile-packages.ts index 0273e6a15d..bf9d98e0a3 100644 --- a/apps/desktop/src/profile-packages.ts +++ b/apps/desktop/src/profile-packages.ts @@ -1,31 +1,16 @@ -/** Desktop-owned host links and applied runtime identity. */ +/** One-time removal of package links recorded by Desktop profile management. */ -import { createHash } from 'node:crypto' -import { existsSync, lstatSync, mkdirSync, readFileSync, readlinkSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs' +import { lstatSync, readFileSync, readlinkSync, unlinkSync } from 'node:fs' import { dirname, isAbsolute, join, resolve } from 'node:path' -import { desktopRuntimeId, runtimePath, type DesktopRuntimeDescriptor } from './runtime-tree.ts' -/** Applied runtime identity and the only links Desktop may replace. */ +/** Legacy Desktop package-link ownership file. */ export const DESKTOP_PROFILE_STATE = 'desktop-runtime-state.json' -/** Durable ownership of a package-directory link. */ -export interface DesktopPackageLink { +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 { @@ -40,76 +25,32 @@ function stat(path: string): ReturnType | undefined { } /** - * Read profile state without interpreting an unpublished predecessor format. + * Remove recorded links still owned by Desktop and delete their legacy state file. + * Installed directories, changed links, and links beneath redirected package directories are retained. * @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') - } +export function migrateDesktopProfileLinks(profile: string): void { + const statePath = join(profile, DESKTOP_PROFILE_STATE) + if (stat(statePath) === undefined) return + const value: unknown = JSON.parse(readFileSync(statePath, 'utf8')) + if (!record(value) || !Array.isArray(value.links)) throw new Error('desktop profile: invalid legacy package links') 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') + throw new Error('desktop profile: invalid legacy package 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)) { - continue + const modules = join(profile, 'node_modules') + if (stat(modules)?.isDirectory() === true) { + for (const link of links) { + const path = join(modules, link.name) + if (dirname(path) !== modules && stat(dirname(path))?.isDirectory() !== true) continue + if (stat(path)?.isSymbolicLink() === true + && resolve(dirname(path), readlinkSync(path)) === resolve(link.target)) { + unlinkSync(path) + } } - unlinkSync(path) } -} - -/** - * Supply missing profile packages from 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 - .filter(entry => stat(join(profile, 'node_modules', entry.name)) === undefined) - .map(entry => ({ name: entry.name, target: runtimePath(root, entry.path) })) - for (const link of links) { - const path = join(profile, 'node_modules', 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 }) + unlinkSync(statePath) } diff --git a/apps/desktop/src/project-manager.ts b/apps/desktop/src/project-manager.ts index 4cec30cc62..c7f685c80e 100644 --- a/apps/desktop/src/project-manager.ts +++ b/apps/desktop/src/project-manager.ts @@ -11,7 +11,6 @@ import { closeSync, readFileSync, readdirSync, - realpathSync, unlinkSync, writeFileSync, writeSync, @@ -25,11 +24,12 @@ import { import type { DesktopPaths } from './paths.ts' import { removeOwnedDirectory } from './owned-directory.ts' import type { DesktopRelease } from './release.ts' -import { desktopRuntimeId, readDesktopRuntime, type DesktopRuntimeDescriptor } from './runtime-tree.ts' +import { readDesktopRuntime, type DesktopRuntimeDescriptor } from './runtime-tree.ts' import { - desktopPluginLockHash, linkDesktopHostPackages, readDesktopProfileState, - unlinkDesktopHostPackages, -} from './profile-packages.ts' + initProfile, readProfileManifest, readProfilePlugins, reconcileProfilePlugins, + unlinkProfileModuleFallback, writeProfileBundles, +} from '@deepseek-ai/dsh-app-boot' +import { migrateDesktopProfileLinks } from './profile-packages.ts' /** Desktop plugin record derived from the installed profile. */ export interface DesktopPluginRecord { @@ -39,17 +39,6 @@ export interface DesktopPluginRecord { readonly enabled: boolean } -/** Installed desktop project manifest slice. */ -interface DesktopProjectManifest { - readonly [key: string]: unknown - readonly dependencies: Record - readonly dsh: { - readonly profile: { - readonly bundles: string[] - } - } -} - /** Exact executables the desktop shell bundles. */ export interface DesktopRuntimeExecutables { readonly node: string @@ -88,10 +77,6 @@ function writeJson(path: string, value: unknown): void { writeFileSync(path, `${JSON.stringify(value, undefined, 2)}\n`, { mode: 0o600 }) } -function readJson(path: string): unknown { - return JSON.parse(readFileSync(path, 'utf8')) -} - function workspaceFile(overrides: Readonly> = {}): string { const entries = Object.entries(overrides).sort(([left], [right]) => left.localeCompare(right)) const overrideSection = entries.length === 0 @@ -114,54 +99,6 @@ function migrateProfileSettings(projectDir: string): void { } } -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} - -function projectManifest(projectDir: string): DesktopProjectManifest { - const path = join(projectDir, 'package.json') - const value = readJson(path) - if (!isRecord(value)) throw new Error(`desktop project: ${path} must hold a JSON object`) - const manifest = value as { dependencies?: Record; dsh?: { profile?: { bundles?: string[] } } } - return { ...value, dependencies: manifest.dependencies ?? {}, - dsh: { ...manifest.dsh, profile: { ...manifest.dsh?.profile, bundles: manifest.dsh?.profile?.bundles ?? [] } } } -} - -function installedManifest(projectDir: string, name: string): Record | undefined { - let value: unknown - try { - value = readJson(join(projectDir, 'node_modules', name, 'package.json')) - } catch { - // Unreadable installed metadata must not prevent listing or removing a dependency. - return undefined - } - return isRecord(value) ? value : undefined -} - -function pluginRecords(projectDir: string): readonly DesktopPluginRecord[] { - const manifest = projectManifest(projectDir) - return Object.entries(manifest.dependencies).sort(([left], [right]) => left.localeCompare(right)).map(([name, spec]) => { - const installed = installedManifest(projectDir, name) - return { name, version: typeof installed?.version === 'string' ? installed.version : spec, - enabled: manifest.dsh.profile.bundles.includes(name) } - }) -} - -function writeProfileBundles(projectDir: string, bundles: readonly string[]): void { - const manifest = projectManifest(projectDir) - writeJson(join(projectDir, 'package.json'), { - ...manifest, - dsh: { ...manifest.dsh, profile: { ...manifest.dsh.profile, bundles } }, - }) -} - -function exportsPatch(projectDir: string, name: string): boolean { - const manifest = installedManifest(projectDir, name) - const dsh = manifest?.dsh - const bundle = isRecord(dsh) ? dsh.bundle : undefined - return isRecord(bundle) && bundle.patch !== undefined -} - /** Desktop npm project manager with direct writes and no rollback. */ export class DesktopProjectManager { private lockDescriptor: number | undefined @@ -179,7 +116,9 @@ export class DesktopProjectManager { /** Read the active desktop plugin inventory. */ listPlugins(): readonly DesktopPluginRecord[] { if (!existsSync(this.paths.profile)) return [] - return pluginRecords(this.paths.profile) + return readProfilePlugins(this.pluginLocation(this.paths.profile)).dependencies + .map(({ name, version, enabled }) => ({ name, version, enabled })) + .sort((left, right) => left.name.localeCompare(right.name)) } /** @@ -198,7 +137,6 @@ export class DesktopProjectManager { else unlinkSync(path) } createPluginProfile(this.paths.profile) - this.prepareProfile(this.paths.profile) await hooks.afterChange() }) } @@ -208,13 +146,6 @@ export class DesktopProjectManager { 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 - } - /** @returns Whether application resources support profile recovery. */ canRecoverProfile(): boolean { return this.descriptor !== undefined && existsSync(this.runtime.node) && existsSync(this.runtime.dsh) @@ -230,27 +161,17 @@ export class DesktopProjectManager { return readDesktopRuntime(this.runtime.dsh) } - private prepareProfile(projectDir: string): void { - linkDesktopHostPackages(projectDir, this.runtime.dsh, this.currentRuntime()) + private pluginLocation(profileDir: string) { + return { binName: 'dsh', profileDir, installAnchor: join(this.runtime.dsh, 'node_modules', DSH_PACKAGE, 'package.json') } } - /** Read release metadata and reconcile its external profile without installing core packages. */ - async applyRelease(): Promise { - return this.withLock(() => { - const target = this.readRuntime() - this.descriptor = target + /** Load application metadata and initialize missing profile files without installing packages. */ + async applyRelease(): Promise { + await this.withLock(() => { + this.descriptor = this.readRuntime() migrateProfileSettings(this.paths.profile) - const previous = readDesktopProfileState(this.paths.profile) - if (previous?.runtimeId === desktopRuntimeId(target) - && previous.lockHash === desktopPluginLockHash(this.paths.profile) - && 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 - } - if (!existsSync(join(this.paths.profile, 'package.json'))) createPluginProfile(this.paths.profile) - this.prepareProfile(this.paths.profile) - return true + migrateDesktopProfileLinks(this.paths.profile) + createPluginProfile(this.paths.profile) }) } @@ -261,52 +182,34 @@ export class DesktopProjectManager { if (!existsSync(this.paths.profile)) throw new Error('desktop project: active profile is not installed') 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 packagesChanged = mutation.type !== 'plugin-toggle' - if (packagesChanged) unlinkDesktopHostPackages(this.paths.profile) - try { + writeProfileBundles(this.paths.profile, readProfileManifest('dsh', this.paths.profile), DESKTOP_PROFILE_BUNDLES) + } else { await this.applyMutation(this.paths.profile, mutation) - } finally { - if (packagesChanged) linkDesktopHostPackages(this.paths.profile, this.runtime.dsh, this.currentRuntime()) } await hooks.afterChange() }) } private async applyMutation(projectDir: string, mutation: Exclude): Promise { - const before = projectManifest(projectDir) - const bundles = before.dsh.profile.bundles + const location = this.pluginLocation(projectDir) + const before = readProfilePlugins(location) + const bundles = before.manifest.dsh?.profile?.bundles ?? [] switch (mutation.type) { case 'plugin-add': case 'plugin-update': { - const dependencies = new Set(Object.keys(before.dependencies)) - const disabled = new Set([...dependencies].filter(name => !bundles.includes(name) && exportsPatch(projectDir, name))) const spec = mutation.type === 'plugin-add' ? mutation.spec : `${mutation.name}@${mutation.version}` + unlinkProfileModuleFallback(projectDir) await this.runPnpm(projectDir, ['add', '--', spec]) - const after = projectManifest(projectDir) - const installed = new Set(Object.keys(after.dependencies)) - const active = bundles.filter(name => !(dependencies.has(name) || installed.has(name)) - || (installed.has(name) && exportsPatch(projectDir, name))) - for (const name of installed) { - if (!active.includes(name) && !disabled.has(name) && exportsPatch(projectDir, name)) active.push(name) - } - writeProfileBundles(projectDir, active) + reconcileProfilePlugins({ ...location, before, preserveDisabled: true }) return } case 'plugin-remove': + unlinkProfileModuleFallback(projectDir) await this.runPnpm(projectDir, ['remove', '--', mutation.name]) - writeProfileBundles(projectDir, bundles.filter(name => name !== mutation.name)) + reconcileProfilePlugins({ ...location, before, preserveDisabled: true }) return case 'plugin-toggle': - writeProfileBundles(projectDir, mutation.enabled + writeProfileBundles(projectDir, before.manifest, mutation.enabled ? bundles.includes(mutation.name) ? bundles : [...bundles, mutation.name] : bundles.filter(name => name !== mutation.name)) return @@ -419,7 +322,7 @@ export class DesktopProjectManager { export function createRuntimeProjectMetadata(projectDir: string, release: DesktopRelease): void { mkdirSync(projectDir, { recursive: true, mode: 0o700 }) const packageSet = verifyDesktopCorePackageSet(projectDir, release.version) - const manifest: DesktopProjectManifest = { + const manifest = { name: PROJECT_NAME, private: true, version: '0.0.0', @@ -457,10 +360,5 @@ export function createDevelopmentProjectMetadata(projectDir: string, release: De /** 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 }) + initProfile(projectDir, DESKTOP_PROFILE_BUNDLES) } diff --git a/apps/desktop/src/runtime-tree.ts b/apps/desktop/src/runtime-tree.ts index 3e4c352cb6..b4ff994c1d 100644 --- a/apps/desktop/src/runtime-tree.ts +++ b/apps/desktop/src/runtime-tree.ts @@ -211,12 +211,3 @@ export async function verifyDesktopRuntime( } 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') -} diff --git a/apps/desktop/tests/plugin-pnpm.spec.ts b/apps/desktop/tests/plugin-pnpm.spec.ts index 37233e541c..c37fad74a7 100644 --- a/apps/desktop/tests/plugin-pnpm.spec.ts +++ b/apps/desktop/tests/plugin-pnpm.spec.ts @@ -7,6 +7,7 @@ import { join } from 'node:path' import { pathToFileURL } from 'node:url' import { c } from 'tar' import { expect, it } from 'vitest' +import { healIsolatedProfileModuleFallback, loadProfileDirectory } from '@deepseek-ai/dsh-app-boot' import { DesktopProjectManager, type DesktopProjectHooks } from '../src/project-manager.ts' import { resolveDesktopPaths } from '../src/paths.ts' import { runtimeFixture, writePackage } from './runtime-fixture.ts' @@ -45,7 +46,14 @@ it('installs a real pnpm graph and executes scripts approved by user configurati runtimeFixture(dsh) const pnpm = join(import.meta.dirname, '../node_modules/pnpm/bin/pnpm.mjs') const manager = new DesktopProjectManager(resolveDesktopPaths(join(root, '.dsh')), { node: process.execPath, pnpm, dsh }) - const hooks: DesktopProjectHooks = { beforeChange: async () => {}, afterChange: async () => {} } + const installAnchor = join(dsh, 'node_modules', '@deepseek-ai', 'dsh', 'package.json') + const hooks: DesktopProjectHooks = { + beforeChange: async () => {}, + afterChange: async () => { + const profile = loadProfileDirectory('desktop test', manager.paths.profile, installAnchor) + healIsolatedProfileModuleFallback({ installAnchor, profile }) + }, + } await manager.applyRelease() writeFileSync(join(manager.paths.profile, '.npmrc'), `registry=${origin}\n`) writeFileSync(join(manager.paths.profile, 'pnpm-workspace.yaml'), `packages:\n - .\nnodeLinker: hoisted\nautoInstallPeers: false\nstoreDir: ${JSON.stringify(join(root, 'store'))}\nallowBuilds:\n node-pty: true\n`) diff --git a/apps/desktop/tests/profile-packages.spec.ts b/apps/desktop/tests/profile-packages.spec.ts index 752312b3c8..fb1e294e00 100644 --- a/apps/desktop/tests/profile-packages.spec.ts +++ b/apps/desktop/tests/profile-packages.spec.ts @@ -1,48 +1,126 @@ -import { execFileSync } from 'node:child_process' -import { existsSync, mkdtempSync, rmSync, unlinkSync, writeFileSync } from 'node:fs' +import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readlinkSync, rmSync, rmdirSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { pathToFileURL } from 'node:url' +import { dirname, join } from 'node:path' import { afterEach, expect, it } from 'vitest' -import { createPluginProfile } from '../src/project-manager.ts' -import { linkDesktopHostPackages, unlinkDesktopHostPackages } from '../src/profile-packages.ts' -import { runtimeFixture, writePackage } from './runtime-fixture.ts' +import { DESKTOP_PROFILE_STATE, migrateDesktopProfileLinks } from '../src/profile-packages.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 }) }) +const symlinks: string[] = [] -it('loads one shared ESM instance from both host and external plugin while keeping ordinary dependencies private', () => { - const { dsh, 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"') - 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' }) +function fixture() { + const root = mkdtempSync(join(tmpdir(), 'desktop-profile-migration-')) + roots.push(root) + const profile = join(root, 'profile') + const target = join(root, 'runtime-package') + mkdirSync(join(profile, 'node_modules'), { recursive: true }) + mkdirSync(target) + return { root, profile, target } +} + +function link(target: string, path: string): void { + mkdirSync(dirname(path), { recursive: true }) + symlinkSync(target, path, process.platform === 'win32' ? 'junction' : 'dir') + symlinks.push(path) +} + +function writeState(profile: string, links: unknown): void { + writeFileSync(join(profile, DESKTOP_PROFILE_STATE), JSON.stringify({ + schemaVersion: 'obsolete', runtimeId: null, version: 8, lockHash: false, links, + })) +} + +afterEach(() => { + for (const path of symlinks.splice(0).reverse()) { + try { + if (lstatSync(path).isSymbolicLink()) unlinkSync(path) + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error + } + } + for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) }) -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('removes recorded links and state without interpreting obsolete runtime fields', () => { + const { profile, target } = fixture() + const packagePath = join(profile, 'node_modules', '@deepseek-ai', 'cordis') + link(target, packagePath) + writeFileSync(join(target, 'package.json'), '{"name":"@deepseek-ai/cordis"}') + writeState(profile, [{ name: '@deepseek-ai/cordis', target }]) + migrateDesktopProfileLinks(profile) + expect(existsSync(packagePath)).toBe(false) + expect(existsSync(join(profile, DESKTOP_PROFILE_STATE))).toBe(false) + expect(readFileSync(join(target, 'package.json'), 'utf8')).toContain('@deepseek-ai/cordis') + expect(() => { migrateDesktopProfileLinks(profile) }).not.toThrow() }) -it('preserves a pnpm package that replaced a managed link', () => { - const { profile } = fixture() - unlinkSync(join(profile, 'node_modules/@deepseek-ai/cordis')) - writePackage(join(profile, 'node_modules'), '@deepseek-ai/cordis') - expect(() =>{ unlinkDesktopHostPackages(profile) }).not.toThrow() - expect(existsSync(join(profile, 'node_modules/@deepseek-ai/cordis/package.json'))).toBe(true) + +it('removes an owned broken link without following its target', () => { + const { profile, target } = fixture() + const packagePath = join(profile, 'node_modules', 'plugin') + link(target, packagePath) + writeState(profile, [{ name: 'plugin', target }]) + rmdirSync(target) + migrateDesktopProfileLinks(profile) + expect(() => lstatSync(packagePath)).toThrow() + expect(existsSync(join(profile, DESKTOP_PROFILE_STATE))).toBe(false) +}) + +it('preserves a pnpm-installed directory replacing a recorded link', () => { + const { profile, target } = fixture() + const packagePath = join(profile, 'node_modules', 'plugin') + mkdirSync(packagePath) + writeFileSync(join(packagePath, 'package.json'), '{"name":"plugin","version":"2.0.0"}') + writeState(profile, [{ name: 'plugin', target }]) + migrateDesktopProfileLinks(profile) + expect(readFileSync(join(packagePath, 'package.json'), 'utf8')).toContain('2.0.0') + expect(existsSync(join(profile, DESKTOP_PROFILE_STATE))).toBe(false) +}) + +it('preserves changed and unrecorded package links', () => { + const { root, profile, target } = fixture() + const replacement = join(root, 'user-package') + mkdirSync(replacement) + const changed = join(profile, 'node_modules', 'changed') + const unrecorded = join(profile, 'node_modules', 'unrecorded') + link(replacement, changed) + link(target, unrecorded) + const changedTarget = readlinkSync(changed) + const unrecordedTarget = readlinkSync(unrecorded) + writeState(profile, [{ name: 'changed', target }]) + migrateDesktopProfileLinks(profile) + expect(readlinkSync(changed)).toBe(changedTarget) + expect(readlinkSync(unrecorded)).toBe(unrecordedTarget) +}) + +it('leaves an uninitialized profile untouched', () => { + const { root } = fixture() + const missingProfile = join(root, 'absent-profile') + migrateDesktopProfileLinks(missingProfile) + expect(existsSync(missingProfile)).toBe(false) +}) + +it.each(['../../outside', '../outside', '@scope/../../outside', '..\\outside'])('rejects escaping package name %s before removing any links', (name) => { + const { root, profile, target } = fixture() + const packagePath = join(profile, 'node_modules', 'owned') + const outside = join(root, 'outside') + link(target, packagePath) + link(target, outside) + writeState(profile, [{ name: 'owned', target }, { name, target }]) + expect(() => { migrateDesktopProfileLinks(profile) }).toThrow('invalid legacy package link') + expect(lstatSync(packagePath).isSymbolicLink()).toBe(true) + expect(lstatSync(outside).isSymbolicLink()).toBe(true) + expect(existsSync(join(profile, DESKTOP_PROFILE_STATE))).toBe(true) +}) + +it.each(['node_modules', 'node_modules/@scope'])('preserves package links beneath redirected %s', (parent) => { + const { root, profile, target } = fixture() + const external = join(root, 'external') + mkdirSync(external) + const packagePath = join(external, 'plugin') + link(target, packagePath) + if (parent === 'node_modules') rmdirSync(join(profile, 'node_modules')) + link(external, join(profile, parent)) + writeState(profile, [{ name: parent === 'node_modules' ? 'plugin' : '@scope/plugin', target }]) + migrateDesktopProfileLinks(profile) + expect(lstatSync(packagePath).isSymbolicLink()).toBe(true) + expect(existsSync(join(profile, DESKTOP_PROFILE_STATE))).toBe(false) }) diff --git a/apps/desktop/tests/project-manager.spec.ts b/apps/desktop/tests/project-manager.spec.ts index b40a7860aa..54a24181ce 100644 --- a/apps/desktop/tests/project-manager.spec.ts +++ b/apps/desktop/tests/project-manager.spec.ts @@ -1,4 +1,4 @@ -import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, unlinkSync, realpathSync, writeFileSync } from 'node:fs' +import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { pathToFileURL } from 'node:url' @@ -77,13 +77,13 @@ describe('desktop external plugin profile', () => { 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 expect(manager.applyRelease()).resolves.toBeUndefined() await manager.mutate({ type: 'plugins-disable-all' }, hooks()) - await expect(manager.applyRelease()).resolves.toBe(false) + await expect(manager.applyRelease()).resolves.toBeUndefined() expect(readFileSync(manifest, 'utf8')).toBe('{broken') await manager.resetConfiguration(hooks()) expect(existsSync(manifest)).toBe(false) - await expect(manager.applyRelease()).resolves.toBe(false) + await expect(manager.applyRelease()).resolves.toBeUndefined() }) it('disables every third-party bundle without reading a broken plugin patch declaration', async () => { @@ -102,7 +102,7 @@ describe('desktop external plugin profile', () => { }).dsh.profile.bundles).not.toContain('plugin') expect(existsSync(join(manager.paths.profile, 'node_modules/plugin/package.json'))).toBe(true) expect(calls(root)).toHaveLength(1) - await expect(manager.applyRelease()).resolves.toBe(false) + await expect(manager.applyRelease()).resolves.toBeUndefined() }) it('resets the entire profile without backups while retaining its lock and shared data', async () => { @@ -134,7 +134,7 @@ describe('desktop external plugin profile', () => { })) expect(manager.listPlugins()).toEqual([]) expect(existsSync(join(profile, 'node_modules/plugin'))).toBe(false) - expect(existsSync(join(profile, 'cordis.patch.yml'))).toBe(false) + expect(readFileSync(join(profile, 'cordis.patch.yml'), 'utf8')).toContain('[]') expect(existsSync(join(profile, '.env'))).toBe(false) expect(existsSync(join(profile, '.extra'))).toBe(false) expect(existsSync(join(profile, 'external-link'))).toBe(false) @@ -143,7 +143,7 @@ describe('desktop external plugin profile', () => { expect(readFileSync(homeEnvironment, 'utf8')).toBe('HOME_SETTING=retained') expect(readdirSync(profile).some(name => name.includes('backup'))).toBe(false) expect(calls(root)).toHaveLength(1) - await expect(manager.applyRelease()).resolves.toBe(false) + await expect(manager.applyRelease()).resolves.toBeUndefined() expect(existsSync(homeEnvironment)).toBe(true) }) @@ -227,34 +227,27 @@ describe('desktop external plugin profile', () => { 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) + await expect(manager.applyRelease()).resolves.toBeUndefined() expect(readFileSync(join(manager.paths.profile, '.DS_Store'), 'utf8')).toBe('metadata') expect(readFileSync(join(manager.paths.profile, 'user-file'), 'utf8')).toBe('retain') + expect(readFileSync(join(manager.paths.profile, 'cordis.patch.yml'), 'utf8')).toContain('[]') + expect(existsSync(join(manager.paths.profile, 'desktop-runtime-state.json'))).toBe(false) }) 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) + await expect(manager.applyRelease()).resolves.toBeUndefined() + await expect(manager.applyRelease()).resolves.toBeUndefined() expect(manager.listPlugins()).toEqual([]) expect(calls(root)).toEqual([]) - 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) + await expect(relaunched.applyRelease()).resolves.toBeUndefined() }) it.each(['changed', 'same-size', 'extra', 'missing'])('starts and reuses a profile without checking %s runtime bytes', async (operation) => { @@ -263,14 +256,14 @@ describe('desktop external plugin profile', () => { 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) + await expect(manager.applyRelease()).resolves.toBeUndefined() const relaunched = new DesktopProjectManager(manager.paths, manager.runtime) - await expect(relaunched.applyRelease()).resolves.toBe(false) + await expect(relaunched.applyRelease()).resolves.toBeUndefined() expect(existsSync(manager.paths.profile)).toBe(true) expect(calls(root)).toEqual([]) }) - it('installs plugins with pnpm script settings and restores host links', async () => { + it('installs plugins with pnpm script settings', async () => { const { root, manager } = setup() await manager.applyRelease() await manager.mutate({ type: 'plugin-add', spec: '@scope/plugin@2.0.0' }, hooks()) @@ -280,7 +273,7 @@ describe('desktop external plugin profile', () => { ]) expect(calls(root).every(call => call.registry === process.env.NPM_CONFIG_REGISTRY)).toBe(true) expect(JSON.parse(readFileSync(join(manager.paths.profile, 'package.json'), 'utf8'))).toMatchObject({ dependencies: { '@scope/plugin': '2.0.0' } }) - await expect(manager.applyRelease()).resolves.toBe(false) + await expect(manager.applyRelease()).resolves.toBeUndefined() expect(calls(root)).toHaveLength(1) }) @@ -288,11 +281,9 @@ describe('desktop external plugin profile', () => { const { manager } = setup() await manager.applyRelease() await manager.mutate({ type: 'plugin-add', spec: '@deepseek-ai/cordis@2.0.0' }, hooks()) - expect(manager.listPlugins()).toEqual([{ name: '@deepseek-ai/cordis', version: '2.0.0', enabled: true }]) - await expect(manager.applyRelease()).resolves.toBe(false) + expect(manager.listPlugins()).toEqual([{ name: '@deepseek-ai/cordis', version: '2.0.0', enabled: false }]) + await expect(manager.applyRelease()).resolves.toBeUndefined() await manager.mutate({ type: 'plugin-remove', name: '@deepseek-ai/cordis' }, hooks()) - expect(realpathSync(join(manager.paths.profile, 'node_modules/@deepseek-ai/cordis'))) - .toBe(realpathSync(join(manager.runtime.dsh, 'node_modules/@deepseek-ai/cordis'))) }) it('retains disabled plugin versions through updates and enables them explicitly', async () => { @@ -318,12 +309,11 @@ describe('desktop external plugin profile', () => { 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) + await expect(next.applyRelease()).resolves.toBeUndefined() expect(next.listPlugins()).toEqual(manager.listPlugins()) - expect(next.releaseVersion()).toBe('1.1.0') + expect(next.dshVersion()).toBe('1.1.0') expect(readFileSync(join(manager.paths.profile, 'cordis.patch.yml'), 'utf8')).toBe('[]\n') expect(calls(root)).toHaveLength(1) - 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') }) @@ -346,10 +336,10 @@ describe('desktop external plugin profile', () => { const dsh = join(root, 'next-major') runtimeFixture(dsh, '2.0.0') const next = new DesktopProjectManager(manager.paths, { ...manager.runtime, dsh }) - await expect(next.applyRelease()).resolves.toBe(true) - expect(next.releaseVersion()).toBe('2.0.0') + await expect(next.applyRelease()).resolves.toBeUndefined() + expect(next.dshVersion()).toBe('2.0.0') await next.mutate({ type: 'plugins-disable-all' }, hooks()) - expect(next.releaseVersion()).toBe('2.0.0') + expect(next.dshVersion()).toBe('2.0.0') expect(next.listPlugins()).toEqual([{ name: 'plugin', version: '1.0.0', enabled: false }]) }) @@ -368,7 +358,7 @@ describe('desktop external plugin profile', () => { expect(starts).toBe(phase === 'before' ? 0 : 1) }) - it('keeps partial package changes and restores host links after pnpm fails', async () => { + it('keeps partial package changes available for recovery after pnpm fails', async () => { const { root, manager } = setup() await manager.applyRelease() const failingPnpm = join(root, 'failing.mjs') @@ -382,8 +372,6 @@ describe('desktop external plugin profile', () => { 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'))) writeFileSync(join(manager.paths.profile, 'desktop-packages-pending'), '') await manager.applyRelease() await manager.mutate({ type: 'plugins-disable-all' }, hooks({ afterChange: async () => { starts++ } })) diff --git a/apps/desktop/tests/runtime-fixture.ts b/apps/desktop/tests/runtime-fixture.ts index 81648dfc5f..ad36c50eb9 100644 --- a/apps/desktop/tests/runtime-fixture.ts +++ b/apps/desktop/tests/runtime-fixture.ts @@ -26,12 +26,20 @@ export function writePackage(modules: string, name: string, fields: Record [dependency, version])) } : {}), + ...(bundle ? { dsh: { bundle: { patch: './bundle.yml' } } } : {}), + }) + if (bundle) writeFileSync(join(path, 'bundle.yml'), '[]\n') + } 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 }) diff --git a/apps/desktop/tests/runtime-tree.spec.ts b/apps/desktop/tests/runtime-tree.spec.ts index 04a5145d00..ae974dc5b1 100644 --- a/apps/desktop/tests/runtime-tree.spec.ts +++ b/apps/desktop/tests/runtime-tree.spec.ts @@ -3,7 +3,7 @@ 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 { DESKTOP_RUNTIME_FILE, readDesktopRuntime, runtimePath, verifyDesktopRuntime } from '../src/runtime-tree.ts' import { runtimeFixture } from './runtime-fixture.ts' const roots: string[] = [] @@ -19,7 +19,7 @@ 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)) + expect(await verifyDesktopRuntime(join(root, 'moved'), '1.0.0')).toEqual(before) }) it.each(['changed', 'same-size', 'extra', 'missing'])('checks %s runtime bytes only during build verification', async (operation) => { const dsh = join(fixture(), 'dsh') diff --git a/apps/desktop/tsconfig.json b/apps/desktop/tsconfig.json index 963a3f71c5..6811108afd 100644 --- a/apps/desktop/tsconfig.json +++ b/apps/desktop/tsconfig.json @@ -6,6 +6,7 @@ }, "include": ["src"], "references": [ + { "path": "../../packages/boot/app-boot" }, { "path": "../../packages/util/home-paths" } ] } diff --git a/docs/architecture.i18n.yaml b/docs/architecture.i18n.yaml index e71254886c..4040214e4b 100644 --- a/docs/architecture.i18n.yaml +++ b/docs/architecture.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/architecture.md -architecture.md: 2a3c291c5acb7e94bd1f666609af901e928671bc -architecture.zh.md: 0eea56b18ae79b297178dfb831ce78e5aed66699 +architecture.md: 95a134253612a78001feaa8990a67810618a2755 +architecture.zh.md: 26f9399c9e36b98e16a458c9b9c4078708b11acf diff --git a/docs/architecture.md b/docs/architecture.md index 2a3c291c5a..95a1342536 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -48,9 +48,9 @@ The Python SDK follows the same application architecture. Its runtime wheel pack ## Desktop application -The [Electron desktop application](../apps/desktop/README.md) carries its exact dsh production runtime in signed application resources. The reserved `$DSH_HOME/profiles/desktop` contains external plugins and links to host-owned packages; compatible upgrades retain plugin files and refresh these links without installing core dependencies. CLI profiles share supported product data under `$DSH_HOME`, while executable packages, plugin activation, lockfiles, and package-manager state remain separate. +The [Electron desktop application](../apps/desktop/README.md) carries its exact dsh production runtime in signed resources and owns the reserved `$DSH_HOME/profiles/desktop`. Shared profile helpers initialize its files, reconcile installed bundles, and project missing dependencies without replacing pnpm-owned packages. CLI and Desktop share product data, while executable packages, activation choices, and lockfiles remain separate. The public CLI cannot manage Desktop’s profile. -Electron starts the private Desktop Host package under its bundled upstream Node.js process; that package loads the bundled dsh backend and matching client graph together with enabled profile plugins. Unary RPC, Remote streams, and version-matched client assets cross versioned framed byte pipes with Node IPC reserved for lifecycle control, then reach the renderer through the secure `dsh-app://` protocol; the desktop composition opens no Web server or loopback port. Only shell-owned UI can run plugin transactions through the bundled pnpm and its private `$DSH_HOME/desktop/pnpm/store`. +Electron starts the private Desktop Host under bundled upstream Node.js. The Host invokes the shared CLI profile runner and complete Web application; Electron loads its authenticated HTTP URL. Web serves RPC, streams, and client assets, while Node IPC carries readiness, fatal errors, and shutdown. Desktop defaults to port `19387`; profile configuration can override it. Shell-owned UI runs plugin transactions through bundled pnpm with normal user and profile configuration. ## Core packages diff --git a/docs/architecture.zh.md b/docs/architecture.zh.md index 0eea56b18a..26f9399c9e 100644 --- a/docs/architecture.zh.md +++ b/docs/architecture.zh.md @@ -48,9 +48,9 @@ Python SDK 遵循相同的应用架构。其运行时 wheel 把普通 `dsh` CLI ## 桌面应用 -[Electron 桌面应用](../apps/desktop/README.zh.md)在签名应用资源中携带精确版本的 dsh 生产运行时。保留的 `$DSH_HOME/profiles/desktop` 保存外部插件和指向宿主拥有包的链接;兼容升级保留插件文件并刷新这些链接,无需安装核心依赖。CLI profile 共享 `$DSH_HOME` 下受支持的产品数据,而可执行包、插件激活、锁文件和包管理器状态保持独立。 +[Electron 桌面应用](../apps/desktop/README.zh.md)在签名资源中携带精确匹配的 dsh 生产运行时,并拥有保留的 `$DSH_HOME/profiles/desktop`。共享 profile helper 初始化其文件、协调已安装 bundle,并补全缺失依赖而不替换 pnpm 拥有的包。CLI 与 Desktop 共享产品数据,可执行包、启用选择与锁文件保持独立。公开 CLI 不能管理 Desktop profile。 -Electron 通过内置的上游 Node.js 进程启动私有 Desktop Host 包;该包加载内置 dsh 后端、匹配的客户端图和已启用的 profile 插件。一元 RPC、Remote stream 与版本匹配的客户端资源经带版本的分帧字节管道传输,Node IPC 只保留生命周期控制,再通过安全的 `dsh-app://` 协议到达渲染进程;因此桌面组合不会开放 Web server 或 loopback 端口。只有壳自有 UI 能通过内置 pnpm 及其私有 `$DSH_HOME/desktop/pnpm/store` 执行插件事务。 +Electron 使用内置上游 Node.js 启动私有 Desktop Host。Host 调用共享 CLI profile runner 与完整 Web 应用,Electron 加载其认证 HTTP URL。Web 提供 RPC、流及客户端资源,Node IPC 承载就绪、致命错误与关闭。Desktop 默认端口为 `19387`,profile 配置可覆盖。壳拥有的 UI 通过内置 pnpm 执行插件事务,并遵循正常用户与 profile 配置。 ## 核心包 diff --git a/packages/boot/app-boot/README.i18n.yaml b/packages/boot/app-boot/README.i18n.yaml index 2437c21556..6be387cd6b 100644 --- a/packages/boot/app-boot/README.i18n.yaml +++ b/packages/boot/app-boot/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 packages/boot/app-boot/README.md -README.md: eeb0f682ac2a3fe9092c5b7cd132e04b4871b2aa -README.zh.md: 75b8b832eaeef365247ea3d8a5c417a04567e9bb +README.md: 2ba6cd6e2b191e0c48cf245db42f39fe605546b9 +README.zh.md: 6dc40e4de84374e6eaf7e631d43368044efae002 diff --git a/packages/boot/app-boot/README.md b/packages/boot/app-boot/README.md index eeb0f682ac..2ba6cd6e2b 100644 --- a/packages/boot/app-boot/README.md +++ b/packages/boot/app-boot/README.md @@ -49,6 +49,8 @@ Import profile and bundle declaration types from [`@deepseek-ai/dsh-package-mani A profile is how one dsh installation ships different app surfaces: `web`, `headless`, `acp`, `sdk`, and `sdk-minimal` start distinct compositions from the same launcher. A profile lives at `$DSH_HOME/profiles/` and combines installable bundles, its own `cordis.patch.yml`, and `patchReload: live | startup`; omitted reload policy keeps the historical `live` default for custom profiles. The shipped `web` template uses live reload, while the other shipped templates apply patches only at startup. `sdk-minimal` names only its standalone bundle; the other templates retain base-plus-mode stacks. `dsh --profile --from-default-profile