Merge pull request #4967 from deepseek-harness/fix/desktop-main-bundle-order

build(desktop): bundle the main process after the workspace tsdown pass
This commit is contained in:
winewill authored and GitHub committed 2026-09-24 00:44:55 +08:00
commit 3bcf1bfc7c
29 files changed
+612 -26

No files matched your search

@@ -48,6 +48,7 @@ The command orchestration shape is:
pnpm run build:
tsc -b tsconfig.host.json
tsdown --env.DSH_BUILD_FACE host
pnpm --filter @deepseek-ai/dsh-desktop run bundle
tsc -b tsconfig.client.json
tsdown --env.DSH_BUILD_FACE client
pnpm run build:web
@@ -48,6 +48,7 @@ Status: implemented
pnpm run build:
tsc -b tsconfig.host.json
tsdown --env.DSH_BUILD_FACE host
pnpm --filter @deepseek-ai/dsh-desktop run bundle
tsc -b tsconfig.client.json
tsdown --env.DSH_BUILD_FACE client
pnpm run build:web
@@ -0,0 +1,19 @@
# Bilingual-pair consistency record for 2026-09-22-desktop-main-bundle-after-workspace-tsdown.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/process/2026-09-22-desktop-main-bundle-after-workspace-tsdown.md
/agent-note-bundle-the-desktop-main-process-after-the-workspace-tsdown-pass:
en: 47f6a531ef05a7be
zh: 18dc33bcd916e2b5
/agent-note-bundle-the-desktop-main-process-after-the-workspace-tsdown-pass/problem:
en: dc5156548e545037
zh: 72010884a2a27877
/agent-note-bundle-the-desktop-main-process-after-the-workspace-tsdown-pass/decision:
en: 9b3c9c696207b13e
zh: 4996ad87dd07d839
/agent-note-bundle-the-desktop-main-process-after-the-workspace-tsdown-pass/alternatives-considered:
en: a15cfe689823ae57
zh: 1d691cd335bdcb87
/agent-note-bundle-the-desktop-main-process-after-the-workspace-tsdown-pass/consequences:
en: e46c28e2ba972cfb
zh: 70d4076a89e0b2ec
@@ -0,0 +1,29 @@
# Agent Note: Bundle the Desktop main process after the workspace tsdown pass
Status: implemented
English | [中文](2026-09-22-desktop-main-bundle-after-workspace-tsdown.zh.md)
## Problem
A macOS Desktop package built from a fresh worktree crashed at launch with `ERR_MODULE_NOT_FOUND: Cannot find package '@deepseek-ai/dsh-home-paths' imported from app.asar/lib/main.js`. The packaging log showed why: rolldown had reported `[UNRESOLVED_IMPORT] Could not resolve '@deepseek-ai/dsh-home-paths' … treating it as an external dependency`, and the same for `@deepseek-ai/dsh-app-boot` and `@deepseek-ai/dsh-deepseek-account`. The three packages are workspace devDependencies of `apps/desktop` that the main-process bundle must inline, because electron-builder copies only the manifest's `dependencies` into `app.asar/node_modules`.
The root tsdown config builds every matched workspace member concurrently (`Promise.all` over the resolved configs in tsdown 0.22, with no dependency ordering), and `apps/desktop` was one of those members. Its bundle resolved the three packages through their `exports` to `lib/index.js` files that other concurrent builds had not written yet. On a checkout that had been built before, the stale `lib/` outputs existed and the bundle inlined them, which is why the defect surfaced only on a clean tree; `clean: false` in both configs kept it hidden. The broken bundle was also smaller (189 KB instead of 315 KB) and the packaging run passed every existing check, because the runtime payload smoke exercises the dsh runtime, not the Electron main process.
## Decision
`apps/desktop` leaves the root tsdown `workspace` list. The root `build:lib:host` script runs the Host tsdown pass and then `pnpm --filter @deepseek-ai/dsh-desktop run bundle`, so the main bundle resolves workspace `lib/` outputs that already exist. The package's own `build` script keeps the same `tsc -b` then `bundle` order for local use. A standalone run of the Desktop config produces byte-identical output to the former workspace-mode run: the config was already self-contained, and the root plugins contributed nothing to it.
The Desktop config also asserts the invariant the crash violated. [`desktop-bundle-imports`](../../../../apps/desktop/scripts/desktop-bundle-imports.mjs) is a rolldown plugin on every Desktop bundle whose `moduleParsed` hook fails the build when a module imports a bare specifier the packaged application cannot resolve, whether through a static import, a dynamic `import()`, or a `require()` call: the main bundle may import `electron`, Node builtins, and the manifest's `dependencies`; a sandboxed preload only `electron`, `events`, `timers`, and `url`, the modules Electron's sandbox `require` polyfill resolves. The hook reads each module's import records, where an external import keeps its bare specifier and a bundled one carries an absolute id; chunk metadata (`imports`/`dynamicImports`) omits external `import()` and `require()` targets and cannot serve the check. The check names the actual requirement rather than the symptom, so it also rejects a workspace package moved out of `dependencies` or a broken `exports` entry, and a rejected bundle writes no output.
## Alternatives considered
**Declare the three packages as runtime `dependencies` so electron-builder ships them in the asar.** This is how `@deepseek-ai/cordis` and `@deepseek-ai/dsh-api-gateway` reach the asar today, and it removes the ordering problem. `dsh-app-boot` would bring a large dependency tree into `app.asar/node_modules`, duplicating the copy already inside the packed dsh runtime and enlarging the payload the runtime file policy must screen.
**Fail on rolldown's `UNRESOLVED_IMPORT` warning** through `inputOptions.onLog` or `failOnWarn`. It catches only the unresolved case and would not have covered a dependency misdeclared as a devDependency, which produces a resolved, inlined bundle when the output exists and an external import when it does not. The packaged-imports check covers both with one rule.
**Order the workspace build by dependency graph.** tsdown offers no such ordering, and every other member either inlines nothing from the workspace or externalizes declared `dependencies`, which need no ordering. One extra step for the one package that needs it is smaller than a general scheduler.
## Consequences
A clean checkout, including CI and a fresh worktree, produces the same Desktop main bundle as a long-lived one. A missing or misdeclared runtime import now fails `pnpm run build` and every packaging command with the importing module and the offending specifiers, before signing and notarization spend their time. The Host build gains one sequential step of about a second on a development machine. `docs/development.md` lists the desktop bundle step in the root build order, `scripts/wine-windows-gates.sh` mirrors it, and the [Desktop README](../../../../apps/desktop/README.md#bundled-workspace-dependencies) owns the import rule.
@@ -0,0 +1,29 @@
# Agent Note:Desktop 主进程在工作区 tsdown 阶段之后再打 bundle
Status: implemented
[English](2026-09-22-desktop-main-bundle-after-workspace-tsdown.md) | 中文
## 问题
从全新 worktree 打出的 macOS Desktop 安装包启动即崩:`ERR_MODULE_NOT_FOUND: Cannot find package '@deepseek-ai/dsh-home-paths' imported from app.asar/lib/main.js`。打包日志给出了原因:rolldown 报告了 `[UNRESOLVED_IMPORT] Could not resolve '@deepseek-ai/dsh-home-paths' … treating it as an external dependency`,`@deepseek-ai/dsh-app-boot` 与 `@deepseek-ai/dsh-deepseek-account` 也是同样情况。这三个包是 `apps/desktop` 的工作区 devDependencies,主进程 bundle 必须把它们内联,因为 electron-builder 只把清单中的 `dependencies` 复制进 `app.asar/node_modules`。
根 tsdown 配置并发构建所有匹配到的 workspace 成员(tsdown 0.22 对解析出的配置做 `Promise.all`,没有任何依赖排序),而 `apps/desktop` 是其中一员。它的 bundle 通过这三个包的 `exports` 解析到 `lib/index.js`,而其他并发构建此时还没有写出这些文件。在此前构建过的检出目录里,陈旧的 `lib/` 产物存在,bundle 会把它们内联,因此缺陷只在干净树上出现;两份配置里的 `clean: false` 一直掩盖着它。坏的 bundle 也更小(189 KB 而不是 315 KB),并且打包流程通过了所有已有检查,因为运行时载荷 smoke 检验的是 dsh 运行时,不是 Electron 主进程。
## 决策
`apps/desktop` 退出根 tsdown 的 `workspace` 列表。根 `build:lib:host` 脚本先跑 Host tsdown 阶段,再执行 `pnpm --filter @deepseek-ai/dsh-desktop run bundle`,让主进程 bundle 解析的是已经存在的工作区 `lib/` 产物。该包自己的 `build` 脚本为本地使用保留同样的先 `tsc -b` 再 `bundle` 的顺序。单独运行 Desktop 配置得到的产物与此前 workspace 模式下的产物逐字节一致:该配置本来就是自足的,根配置的插件没有为它贡献任何内容。
Desktop 配置同时断言这次崩溃所违反的不变量。[`desktop-bundle-imports`](../../../../apps/desktop/scripts/desktop-bundle-imports.mjs) 是挂在每个 Desktop bundle 上的 rolldown 插件,其 `moduleParsed` 钩子在某个模块以静态 import、动态 `import()` 或 `require()` 导入了打包应用无法解析的裸说明符时让构建失败:主进程 bundle 可以导入 `electron`、Node 内置模块与清单的 `dependencies`;沙箱 preload 只能导入 `electron`、`events`、`timers` 与 `url`,即 Electron 沙箱 `require` polyfill 能解析的模块。该钩子读取每个模块的导入记录,其中外部导入保留裸说明符、被打包的导入带有绝对 id;chunk 元数据(`imports`/`dynamicImports`)不包含外部的 `import()` 与 `require()` 目标,无法用于这项检查。这项检查陈述的是真正的要求而非症状,因此它同样拒绝被移出 `dependencies` 的工作区包或损坏的 `exports` 条目,且被拒绝的 bundle 不写出任何产物。
## 备选方案
**把这三个包声明为运行时 `dependencies`,让 electron-builder 装进 asar。** `@deepseek-ai/cordis` 与 `@deepseek-ai/dsh-api-gateway` 今天就是这样进入 asar 的,这也消除了顺序问题。但 `dsh-app-boot` 会把一棵很大的依赖树带进 `app.asar/node_modules`,与 packed dsh 运行时内已有的副本重复,并扩大运行时文件策略必须筛查的载荷。
**通过 `inputOptions.onLog` 或 `failOnWarn` 让 rolldown 的 `UNRESOLVED_IMPORT` warning 直接失败。** 它只覆盖未解析这一种情况,覆盖不了被误声明为 devDependency 的依赖:产物存在时它会被解析并内联,不存在时才留成外部导入。打包导入检查用一条规则同时覆盖两者。
**按依赖图给 workspace 构建排序。** tsdown 不提供这种排序,而其他每个成员要么不从工作区内联任何内容,要么把已声明的 `dependencies` 留成外部导入,都不需要排序。为唯一需要它的包多加一步,比通用调度器更小。
## 后果
干净的检出目录(包括 CI 与全新 worktree)产出的 Desktop 主进程 bundle 与长期使用的检出目录一致。缺失或误声明的运行时导入现在会让 `pnpm run build` 和每条打包命令在签名与公证耗时之前失败,并报出导入方模块与违规说明符。Host 构建多出一个串行步骤,在开发机上约一秒。`docs/development.md` 在根构建顺序中列出了 desktop bundle 步骤,`scripts/wine-windows-gates.sh` 与之保持一致,导入规则由 [Desktop README](../../../../apps/desktop/README.zh.md#bundled-workspace-dependencies) 负责。
+5 -5
View File
@@ -7,10 +7,10 @@
zh: d936a91a17efd1da
/deepseek-harness-desktop/key-technical-decisions:
en: 069fdfd72d2ea26a
zh: 81c683ada1fe3e8d
zh: 76ae549d43c99bb4
/deepseek-harness-desktop/key-technical-decisions/bundled-workspace-dependencies:
en: c2eb16f568cd8554
zh: 686d64af17b10375
en: 31cbb7452be8e1ad
zh: 502ec556e2ec301e
/deepseek-harness-desktop/installation-ownership:
en: 8307baf6c5b691d0
zh: 86e46b9552017ff6
@@ -36,8 +36,8 @@
en: 7d72469be4975afe
zh: 2f644b582cb581be
/deepseek-harness-desktop/package/upload-updates:
en: 7828da306d42ed2e
zh: 0b8bc61c5f612dcb
en: c64d7fe2fe2534b7
zh: 2188e1ae99ab4b33
/deepseek-harness-desktop/package/unsigned-windows-test-installer:
en: cfd5780dd26a8e46
zh: f7a16b1ede793b7b
+3 -1
View File
@@ -32,6 +32,8 @@ The macOS PNG uses an inset rounded background for legacy ICNS packaging, with r
### Bundled workspace dependencies
electron-builder copies only the manifest's `dependencies` into `app.asar/node_modules`, so the Electron main bundle `lib/main.js` inlines its workspace devDependencies and leaves `electron`, Node builtins, and those `dependencies` as its only bare imports; a sandboxed preload may leave only `electron`, `events`, `timers`, and `url`, the modules its `require` polyfill resolves. The main bundle resolves the inlined packages from their `lib/` output, so the root `build:lib:host` bundles `apps/desktop` after the concurrent workspace tsdown pass, and [`desktop-bundle-imports`](scripts/desktop-bundle-imports.mjs) fails any Desktop bundle whose static, dynamic, or `require()` import the packaged application cannot resolve. Without that check an import rolldown could not resolve ships as an external specifier and fails at launch with `ERR_MODULE_NOT_FOUND`. The [bundle-order decision](../../.agents/notes/implemented/process/2026-09-22-desktop-main-bundle-after-workspace-tsdown.md) records the alternatives.
Signed Windows packaging scans the primary runtime and application production dependencies for PE content, including files without a conventional extension. The final scan covers the entire unpacked application. Directory links, malformed `MZ` files and non-PE `.exe`, `.dll` or `.pyd` files stop packaging; data files beginning with `MZ` are also rejected unless they contain a valid PE header. It preserves valid vendor signatures and signs unsigned code before sealing runtime hashes or executing smoke checks. Public-key inspection uses batches of 32 files with at most four processes; hardware-token signing remains serial, and each new signature must match the configured certificate and carry a timestamp. Hardware signing and verification failures stop the run; isolated timestamp requests follow the bounded policy below. Electron-builder preserves copied runtime executables only after signature and exact-byte verification. A final PE-signature audit and a fresh-cache ASAR payload and Host smoke must pass before the release completion record is written. Development, preparation-only and unsigned builds do not use the hardware token and can be blocked by Windows code-integrity policy; no build mode disables that policy. Passing smoke checks does not establish compatibility with every enterprise policy.
Desktop carries independent Python, Node.js and pnpm distributions. Python includes numpy, pandas, python-docx, python-pptx, openpyxl, Pillow, lxml and XlsxWriter with their complete dependencies. The `load_workspace_dependencies` tool installs this payload offline on first use under `$DSH_HOME/dsh-runtimes/dsh-primary-runtime` (normally `~/.dsh/dsh-runtimes/dsh-primary-runtime`) and returns absolute interpreter, pnpm script and library paths plus `pythonDistributions`, the bundled distribution names and versions. The version report excludes user-installed additions. Office tasks prefer these libraries unless user or workspace instructions select another environment. Execute the pnpm script with the returned Node executable. The returned Node library directory is reserved for bundled libraries, not pnpm's global installation directory.
@@ -263,7 +265,7 @@ Mac packaging reads three tuning fields from `.env.macos`:
The proxy fields are independent and reject URL credentials, paths, queries and fragments. Empty values preserve inherited networking. An explicit download proxy replaces child-process proxy variables and bypasses local hosts only; it does not change system settings. Windows and standalone `release:pack` retain their existing concurrency defaults. Company proxy addresses belong in the ignored local file; see internal documentation for addresses.
Apple tooling uses the active macOS network service's HTTP/HTTPS proxies. Configured notarization routing checks proxy reachability, saves that service's settings, enables the proxy around both artifact lanes, and restores the saved settings after both lanes settle. An originally disabled proxy with an empty server and port zero is restored by disabling it; the temporary server and port may remain stored but inactive. Directory-only builds apply it to App notarization after the signed directory build. This temporarily affects other applications and requires permission to change system proxies; PAC, auto-discovery, SOCKS and authenticated proxy configurations must be disabled first. Packaging and recovery acquire the same per-user POSIX file lock before reading recovery data or changing proxies; process exit releases ownership, while the lock file remains in place. This prevents overlapping proxy transactions across checkouts; other users and network-setting tools must not change these settings concurrently. SIGINT/SIGTERM wait for active work before restoration. After forced termination or a restoration error, stop any remaining notarization processes and run `pnpm --dir apps/desktop run restore:mac-proxy`; the saved record remains until restoration succeeds. Configuration checks validate URL syntax without changing system settings or contacting the proxy.
Apple tooling uses the active macOS network service's HTTP/HTTPS proxies. Configured notarization routing checks proxy reachability, saves that service's settings, enables the proxy around both artifact lanes, and restores the saved settings after both lanes settle. An originally disabled proxy with an empty server and port zero is restored by disabling it; the temporary server and port may remain stored but inactive. Directory-only builds apply it to App notarization after the signed directory build. This temporarily affects other applications and requires permission to change system proxies; PAC, auto-discovery, SOCKS and authenticated proxy configurations must be disabled first. Packaging and recovery acquire the same per-user POSIX file lock before reading recovery data or changing proxies; process exit releases ownership, while the lock file remains in place. The lock loads `@deepseek-ai/node-addon-system/flock` at first use rather than at script start, so `check:package` and the packaging entry load on a checkout that has not built `native/system`; when the host addon binary or the entry's JavaScript is missing at lock time, the loader runs `pnpm run build:native-system` and `pnpm --dir native/system run build:ts` before locking, so recovery works on such a checkout as well. This prevents overlapping proxy transactions across checkouts; other users and network-setting tools must not change these settings concurrently. SIGINT/SIGTERM wait for active work before restoration. After forced termination or a restoration error, stop any remaining notarization processes and run `pnpm --dir apps/desktop run restore:mac-proxy`; the saved record remains until restoration succeeds. Configuration checks validate URL syntax without changing system settings or contacting the proxy.
### Unsigned Windows test installer
+5 -1
View File
@@ -30,8 +30,12 @@ macOS“文件”菜单显示已接受的单键绑定(包括方向键),并
macOS PNG 使用带留白的圆角底板,供传统 ICNS 打包使用,包含最高 1024 像素的表示。它是扁平图标,并非 Icon Composer 文档。Apple 的[应用图标指南](https://developer.apple.com/design/human-interface-guidelines/app-icons)要求向 Icon Composer 提供未遮罩的图层;这些输入需要在 macOS 上单独导出,不能复用已做圆角的 ICNS 图案。发布前须在支持的 macOS 版本中验收 Finder 和 Dock 的显示效果。
<a id="bundled-workspace-dependencies"></a>
### 内置工作区依赖
electron-builder 只把清单中的 `dependencies` 复制进 `app.asar/node_modules`,因此 Electron 主进程 bundle `lib/main.js` 内联其工作区 devDependencies,裸导入只剩 `electron`、Node 内置模块与这些 `dependencies`;沙箱 preload 只能留下 `electron`、`events`、`timers` 与 `url`,即其 `require` polyfill 能解析的模块。主进程 bundle 从被内联包的 `lib/` 产物解析它们,所以根 `build:lib:host` 在并发的工作区 tsdown 阶段之后才为 `apps/desktop` 打 bundle,并由 [`desktop-bundle-imports`](scripts/desktop-bundle-imports.mjs) 让任何静态、动态或 `require()` 导入无法在打包应用内解析的 Desktop bundle 直接失败。没有这项检查时,rolldown 无法解析的导入会作为外部说明符进入产物,并在启动时以 `ERR_MODULE_NOT_FOUND` 失败。[bundle 顺序决策](../../.agents/notes/implemented/process/2026-09-22-desktop-main-bundle-after-workspace-tsdown.zh.md)记录了备选方案。
Windows 签名打包按 PE 文件内容扫描第一方运行时和应用生产依赖,包括没有常规扩展名的文件。最终扫描覆盖整个解包应用。目录链接、格式错误的 `MZ` 文件以及非 PE 的 `.exe`、`.dll` 或 `.pyd` 文件会使打包停止;以 `MZ` 开头的数据文件也会被拒绝,除非包含有效 PE 头。它保留有效的上游签名,并在记录运行时哈希或执行冒烟检查前为未签名代码补签。公钥验签每个进程处理最多 32 个文件,同时最多运行四个进程;硬件令牌签名仍串行执行,每个新签名必须匹配配置的证书且带时间戳。硬件签名或验签失败会停止本轮执行;独立的时间戳请求遵循下文的有界重试规则。electron-builder 只有在验签和逐字节比对通过后,才保留复制后运行时可执行文件的签名。写入发布完成记录前,必须通过最终 PE 签名检查,以及使用全新缓存的 ASAR 载荷和 Host 冒烟检查。开发、仅准备和未签名构建不使用硬件令牌,可能被 Windows 代码完整性策略阻止;任何构建模式都不会关闭该策略。冒烟检查通过不代表兼容所有企业策略。
Desktop 携带独立的 Python、Node.js 和 pnpm 分发包。Python 包含 numpy、pandas、python-docx、python-pptx、openpyxl、Pillow、lxml、XlsxWriter 及其完整依赖。`load_workspace_dependencies` 工具首次使用时,将该产物离线安装到 `$DSH_HOME/dsh-runtimes/dsh-primary-runtime`(通常为 `~/.dsh/dsh-runtimes/dsh-primary-runtime`),并返回解释器、pnpm 脚本和库目录的绝对路径,以及记录内置分发包名称与版本的 `pythonDistributions`。版本报告不包含用户自行安装的包。Office 任务默认使用这些库,用户或工作区指令指定其他环境时遵循其要求。pnpm 脚本通过返回的 Node 可执行文件运行。返回的 Node 库目录为随包交付的库预留,不是 pnpm 的全局安装目录。
@@ -263,7 +267,7 @@ Mac 打包从 `.env.macos` 读取三个调优字段:
两个代理字段互相独立,拒绝 URL 中的凭证、路径、查询参数和片段。空值沿用继承的网络设置。显式下载代理会替换子进程的代理变量,仅绕过本地主机;它不修改系统设置。Windows 与独立 `release:pack` 保持现有并发默认值。公司代理地址仅写入 Git 忽略的本地文件;具体地址参见内部文档。
Apple 工具使用 macOS 当前活动网络服务的 HTTP/HTTPS 代理。配置公证代理后,打包会检查代理可达性、保存该服务的设置,在两条产物任务期间启用代理,并在两条任务均结束后恢复原设置。对于原本关闭、服务器为空且端口为零的代理,恢复时仅关闭代理;临时服务器和端口可能保留,但不生效。仅生成目录的打包会在签名目录构建完成后的 App 公证期间启用代理。这会临时影响其他应用,并要求修改系统代理的权限;必须先禁用 PAC、自动发现、SOCKS 及需要认证的代理配置。打包和恢复在读取恢复记录或修改代理前获取同一个用户级 POSIX 文件锁;进程退出会释放锁的持有权,锁文件保留。这会阻止不同 checkout 的代理事务重叠;其他用户及网络设置工具不得同时修改这些设置。SIGINT/SIGTERM 会等待活动任务结束后恢复。强制终止或恢复失败后,先停止残留公证进程,再运行 `pnpm --dir apps/desktop run restore:mac-proxy`;保存的记录会保留到恢复成功。配置检查仅验证 URL 语法,不修改系统设置或连接代理。
Apple 工具使用 macOS 当前活动网络服务的 HTTP/HTTPS 代理。配置公证代理后,打包会检查代理可达性、保存该服务的设置,在两条产物任务期间启用代理,并在两条任务均结束后恢复原设置。对于原本关闭、服务器为空且端口为零的代理,恢复时仅关闭代理;临时服务器和端口可能保留,但不生效。仅生成目录的打包会在签名目录构建完成后的 App 公证期间启用代理。这会临时影响其他应用,并要求修改系统代理的权限;必须先禁用 PAC、自动发现、SOCKS 及需要认证的代理配置。打包和恢复在读取恢复记录或修改代理前获取同一个用户级 POSIX 文件锁;进程退出会释放锁的持有权,锁文件保留。该锁在首次使用时才加载 `@deepseek-ai/node-addon-system/flock`,而不是在脚本启动时加载,因此 `check:package` 和打包入口在未构建 `native/system` 的 checkout 上也能加载;加锁时若宿主 addon 二进制或入口的 JavaScript 缺失,加载器会先运行 `pnpm run build:native-system` 和 `pnpm --dir native/system run build:ts` 再加锁,因此恢复命令在这样的 checkout 上同样可用。这会阻止不同 checkout 的代理事务重叠;其他用户及网络设置工具不得同时修改这些设置。SIGINT/SIGTERM 会等待活动任务结束后恢复。强制终止或恢复失败后,先停止残留公证进程,再运行 `pnpm --dir apps/desktop run restore:mac-proxy`;保存的记录会保留到恢复成功。配置检查仅验证 URL 语法,不修改系统设置或连接代理。
### 未签名 Windows 测试安装包
+2 -1
View File
@@ -8,7 +8,8 @@
"main": "lib/main.js",
"scripts": {
"test:installer": "node scripts/test-windows-installer.mjs",
"build": "tsc -b && tsdown",
"build": "tsc -b && pnpm run bundle",
"bundle": "tsdown",
"dev": "tsx scripts/dev.ts",
"start": "tsx scripts/dev.ts --skip-build",
"test:updates:local": "pnpm run build && node scripts/test-local-updater.mjs",
@@ -0,0 +1,46 @@
import type { Rolldown } from 'tsdown'
/** Bare specifiers one Desktop bundle may leave for the runtime to resolve. */
export interface BundleImportPolicy {
/** Package names present at runtime, matched by package name so subpaths pass. */
readonly packages: ReadonlySet<string>
/**
* Whether Node builtins resolve at runtime: true for the Electron main
* process; false for sandboxed preloads, whose `require` polyfill offers only
* the modules listed in `packages`.
*/
readonly nodeBuiltins: boolean
}
/**
* Package name of a bare import specifier.
* @param specifier - Bare specifier as rolldown reports it, such as `@scope/name/subpath`.
* @returns The package name without its subpath.
*/
export function importPackageName(specifier: string): string
/**
* Whether a module id rolldown reports is a bare specifier, i.e. an import the
* bundle leaves external. Bundled modules carry absolute ids; virtual modules
* start with `\0`.
* @param id - Module id from `importedIds` or `dynamicallyImportedIds`.
* @returns True for a bare specifier.
*/
export function isBareSpecifier(id: string): boolean
/**
* Bare imports the packaged application cannot resolve.
* @param imports - External specifiers a module imports statically, dynamically, or through `require()`.
* @param policy - What this bundle may leave external.
* @returns Offending specifiers in import order, each once.
*/
export function unpackagedImports(imports: readonly string[], policy: BundleImportPolicy): string[]
/**
* Rolldown plugin that fails a bundle whose external imports the packaged
* application cannot resolve. The failure names the importing module and every
* offending specifier, and no output is written.
* @param policy - What this bundle may leave external.
* @returns The plugin.
*/
export function packagedImportsPlugin(policy: BundleImportPolicy): Rolldown.Plugin
@@ -0,0 +1,90 @@
/**
* Keep every bare import a Desktop bundle leaves to the runtime resolvable
* inside the packaged application.
*
* electron-builder copies only the manifest's `dependencies` into
* `app.asar/node_modules`, so a bare import of anything else bundles without
* complaint and fails at launch with `ERR_MODULE_NOT_FOUND`. The main-process
* bundle inlines its workspace devDependencies; when one of their `lib/`
* outputs is missing at bundle time, rolldown reports `UNRESOLVED_IMPORT` as a
* warning and keeps the specifier as an external import, which is exactly the
* broken artifact. This check fails the bundle instead of the installed
* application.
*
* The check runs in `moduleParsed`, where rolldown reports every import record
* of a module: static imports, dynamic `import()`, and `require()` calls. A
* bundled import resolves to an absolute module id; an external one keeps its
* bare specifier. Chunk metadata (`imports`/`dynamicImports`) omits external
* `import()` and `require()` targets, so it cannot serve this check.
*/
import { isBuiltin } from 'node:module'
import { isAbsolute, relative } from 'node:path'
/**
* Bare specifiers one Desktop bundle may leave for the runtime to resolve.
* @typedef {object} BundleImportPolicy
* @property {ReadonlySet<string>} packages - Package names present at runtime, matched by package name so subpaths pass.
* @property {boolean} nodeBuiltins - Whether Node builtins resolve at runtime (true for the Electron main process; false for sandboxed preloads, whose `require` polyfill offers only the modules listed in `packages`).
*/
/**
* Package name of a bare import specifier.
* @param {string} specifier - Bare specifier as rolldown reports it, such as `@scope/name/subpath`.
* @returns {string} The package name without its subpath.
*/
export function importPackageName(specifier) {
const segments = specifier.split('/')
return specifier.startsWith('@') ? segments.slice(0, 2).join('/') : segments[0]
}
/**
* Whether a module id rolldown reports is a bare specifier, i.e. an import the
* bundle leaves external. Bundled modules carry absolute ids; virtual modules
* start with `\0`.
* @param {string} id - Module id from `importedIds` or `dynamicallyImportedIds`.
* @returns {boolean} True for a bare specifier.
*/
export function isBareSpecifier(id) {
return !id.startsWith('.') && !id.startsWith('\0') && !isAbsolute(id)
}
/**
* Bare imports the packaged application cannot resolve.
* @param {readonly string[]} imports - External specifiers a module imports statically, dynamically, or through `require()`.
* @param {BundleImportPolicy} policy - What this bundle may leave external.
* @returns {string[]} Offending specifiers in import order, each once.
*/
export function unpackagedImports(imports, policy) {
const offending = new Set()
for (const specifier of imports) {
if (policy.nodeBuiltins && isBuiltin(specifier)) continue
if (policy.packages.has(importPackageName(specifier))) continue
offending.add(specifier)
}
return [...offending]
}
/**
* Rolldown plugin that fails a bundle whose external imports the packaged
* application cannot resolve. The failure names the importing module and every
* offending specifier, and no output is written.
* @param {BundleImportPolicy} policy - What this bundle may leave external.
* @returns {import('tsdown').Rolldown.Plugin} The plugin.
*/
export function packagedImportsPlugin(policy) {
const allowed = [...policy.packages].join(', ') + (policy.nodeBuiltins ? ', and Node builtins' : '')
return {
name: 'desktop-packaged-imports',
moduleParsed(info) {
const external = [...info.importedIds, ...info.dynamicallyImportedIds].filter(isBareSpecifier)
const offending = unpackagedImports(external, policy)
if (offending.length === 0) return
this.error(
`desktop bundle: ${relative(process.cwd(), info.id)} imports ${offending.join(', ')}, which the packaged application does not ship. `
+ `This bundle may leave only ${allowed} as bare imports; anything else must be bundled, `
+ 'which requires its lib/ output to exist before this bundle runs (pnpm run build:lib:host).',
)
},
}
}
+94
View File
@@ -0,0 +1,94 @@
/** Load the POSIX flock entry on first use so packaging entry scripts start on a checkout that has not built `native/system`. */
import { spawn } from 'node:child_process'
import { once } from 'node:events'
import { existsSync, readFileSync } from 'node:fs'
import { createRequire } from 'node:module'
import { dirname, join, resolve } from 'node:path'
type FlockEntry = typeof import('@deepseek-ai/node-addon-system/flock')
const REPOSITORY_ROOT = resolve(import.meta.dirname, '..', '..', '..')
/** Root package script that compiles the host addon, then the `native/system` script that emits the entry's JavaScript. */
const BUILD_COMMANDS: readonly (readonly string[])[] = [
['run', 'build:native-system'],
['--dir', 'native/system', 'run', 'build:ts'],
]
const BUILD_COMMAND_TEXT = BUILD_COMMANDS.map(args => `pnpm ${args.join(' ')}`).join(' && ')
/** Loader steps; tests replace the module import, the addon probe, and the build. */
export interface FlockEntryLoaderSteps {
/** Import `@deepseek-ai/node-addon-system/flock`; rejects with `ERR_MODULE_NOT_FOUND` while its `lib/` is unbuilt. */
readonly importEntry: () => Promise<FlockEntry>
/** Whether every binary the host platform package declares in `prebuilds.json` exists. */
readonly hostAddonBuilt: () => boolean
/** Compile the host addon and emit the entry's JavaScript; rejects when a build fails. */
readonly build: () => Promise<void>
}
function isModuleNotFound(error: unknown): boolean {
return (error as NodeJS.ErrnoException | undefined)?.code === 'ERR_MODULE_NOT_FOUND'
}
/**
* Create a memoized loader that imports the flock entry, building `native/system` once when its entry or host addon is missing.
* @param steps - Module import, addon probe, and build used by the loader.
* @returns Loader that resolves the same entry on every call; a failed load is retried by the next call.
*/
export function createFlockEntryLoader(steps: FlockEntryLoaderSteps): () => Promise<FlockEntry> {
let loading: Promise<FlockEntry> | undefined
const load = async (): Promise<FlockEntry> => {
let entry: FlockEntry | undefined
try {
entry = await steps.importEntry()
} catch (error) {
if (!isModuleNotFound(error)) throw error
}
if (entry !== undefined && steps.hostAddonBuilt()) return entry
process.stderr.write(`desktop package: flock addon is not built; running ${BUILD_COMMAND_TEXT}\n`)
await steps.build()
return steps.importEntry()
}
return () => {
loading ??= load().catch((error: unknown) => { loading = undefined; throw error })
return loading
}
}
function hostAddonBuilt(): boolean {
const { platform, arch } = process
// flock itself rejects other platforms; the probe only reports missing builds for supported ones.
if (platform !== 'darwin' && platform !== 'linux') return true
const entryManifest = createRequire(import.meta.url).resolve('@deepseek-ai/node-addon-system/package.json')
let prebuilds: string
try {
prebuilds = createRequire(entryManifest).resolve(`@deepseek-ai/node-addon-system-${platform}-${arch}/prebuilds.json`)
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'MODULE_NOT_FOUND') throw error
return false
}
const manifest = JSON.parse(readFileSync(prebuilds, 'utf8')) as { readonly binaries: readonly { readonly path: string }[] }
return manifest.binaries.every(binary => existsSync(join(dirname(prebuilds), binary.path)))
}
async function buildNativeSystem(): Promise<void> {
const pnpmEntry = process.env.npm_execpath
if (pnpmEntry === undefined || pnpmEntry === '') {
throw new Error(`desktop package: flock addon is not built; run ${BUILD_COMMAND_TEXT} or invoke this script through a pnpm package command`)
}
for (const args of BUILD_COMMANDS) {
const child = spawn(process.execPath, [pnpmEntry, ...args], { cwd: REPOSITORY_ROOT, stdio: 'inherit' })
const [code, signal] = await once(child, 'close') as [number | null, NodeJS.Signals | null]
if (code !== 0) throw new Error(`desktop package: pnpm ${args.join(' ')} exited with ${String(code ?? signal)}`)
}
}
/**
* Load `@deepseek-ai/node-addon-system/flock`, building the host addon and the entry's JavaScript through pnpm when either is missing.
* @returns The flock entry; rejects when a build fails or the script did not run under pnpm.
*/
export const loadFlockEntry = createFlockEntryLoader({
importEntry: () => import('@deepseek-ai/node-addon-system/flock'),
hostAddonBuilt,
build: buildNativeSystem,
})
@@ -5,7 +5,7 @@ import { closeSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync } f
import { connect } from 'node:net'
import { homedir } from 'node:os'
import { dirname, join, resolve } from 'node:path'
import { tryLockExclusive } from '@deepseek-ai/node-addon-system/flock'
import { loadFlockEntry } from './flock-entry.ts'
interface ProxyState {
readonly enabled: boolean
@@ -50,6 +50,7 @@ const operations: ProxyOperations = {
}
async function withProxyLock<T>(lock: string, action: () => Promise<T>): Promise<T> {
const { tryLockExclusive } = await loadFlockEntry()
mkdirSync(dirname(lock), { recursive: true, mode: 0o700 })
// Keep this inode across transactions: unlinking it would allow two independent locks.
const fd = openSync(`${lock}.flock`, 'a', 0o600)
@@ -0,0 +1,121 @@
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { Rolldown } from 'tsdown'
import { afterAll, describe, expect, it } from 'vitest'
import {
importPackageName,
isBareSpecifier,
packagedImportsPlugin,
unpackagedImports,
type BundleImportPolicy,
} from '../scripts/desktop-bundle-imports.mjs'
const MAIN: BundleImportPolicy = {
packages: new Set(['electron', 'electron-updater', '@deepseek-ai/dsh-api-gateway']),
nodeBuiltins: true,
}
const PRELOAD: BundleImportPolicy = { packages: new Set(['electron', 'events', 'timers', 'url']), nodeBuiltins: false }
describe('desktop bundle imports', () => {
it('names the package behind a bare specifier', () => {
expect(importPackageName('electron-updater/out/electronHttpExecutor.js')).toBe('electron-updater')
expect(importPackageName('@deepseek-ai/dsh-api-gateway/stream-protocol')).toBe('@deepseek-ai/dsh-api-gateway')
expect(importPackageName('ws')).toBe('ws')
})
it('tells external specifiers from bundled and virtual module ids', () => {
expect(isBareSpecifier('electron')).toBe(true)
expect(isBareSpecifier('@deepseek-ai/dsh-home-paths')).toBe(true)
expect(isBareSpecifier('node:fs')).toBe(true)
expect(isBareSpecifier('./helper.js')).toBe(false)
expect(isBareSpecifier(join(tmpdir(), 'lib', 'index.js'))).toBe(false)
expect(isBareSpecifier('\0rolldown/runtime')).toBe(false)
})
it('accepts Node builtins and packaged dependencies, including their subpaths, for the main process', () => {
expect(unpackagedImports([
'node:fs/promises',
'crypto',
'electron',
'electron-updater/out/electronHttpExecutor.js',
'@deepseek-ai/dsh-api-gateway/stream-protocol',
], MAIN)).toEqual([])
})
it('rejects Node builtins outside the sandbox polyfill for a preload', () => {
expect(unpackagedImports(['electron', 'events', 'url', 'node:fs', 'crypto'], PRELOAD)).toEqual(['node:fs', 'crypto'])
})
it('reports each specifier the packaged application cannot resolve once, in import order', () => {
expect(unpackagedImports([
'@deepseek-ai/dsh-home-paths',
'ws',
'@deepseek-ai/dsh-home-paths',
'electron',
], MAIN)).toEqual(['@deepseek-ai/dsh-home-paths', 'ws'])
})
})
describe('packaged imports plugin', () => {
const root = mkdtempSync(join(tmpdir(), 'dsh-desktop-bundle-imports-'))
const entries = {
static: ['import { app } from "electron";', 'import { resolveDshHome } from "@deepseek-ai/dsh-home-paths";', 'export const home = resolveDshHome(app);'],
dynamic: ['import { app } from "electron";', 'export const home = () => import("@deepseek-ai/dsh-home-paths").then(m => m.resolveDshHome(app));'],
require: ['import { app } from "electron";', 'export const home = () => require("@deepseek-ai/dsh-home-paths").resolveDshHome(app);'],
builtin: ['import { contextBridge } from "electron";', 'import { readFileSync } from "node:fs";', 'contextBridge.exposeInMainWorld("x", readFileSync);'],
} as const
for (const [name, lines] of Object.entries(entries)) writeFileSync(join(root, `${name}.js`), lines.join('\n'))
afterAll(() => {
rmSync(root, { recursive: true, force: true })
})
async function generate(entry: keyof typeof entries, policy: BundleImportPolicy, format: 'esm' | 'cjs' = 'esm'): Promise<Rolldown.RolldownOutput> {
// Every import stays external, which is what an unresolved workspace lib/ output produces.
const bundle = await Rolldown.rolldown({
input: join(root, `${entry}.js`),
platform: 'node',
external: () => true,
logLevel: 'silent',
plugins: [packagedImportsPlugin(policy)],
})
try {
return await bundle.generate({ format })
} finally {
await bundle.close()
}
}
const unshipped = /imports @deepseek-ai\/dsh-home-paths, which the packaged application does not ship/u
it('fails the bundle whose static import the packaged application does not ship', async () => {
await expect(generate('static', { ...MAIN, packages: new Set(['electron']) })).rejects.toThrow(unshipped)
})
it('fails the bundle whose dynamic import() the packaged application does not ship', async () => {
await expect(generate('dynamic', { ...MAIN, packages: new Set(['electron']) })).rejects.toThrow(unshipped)
})
it('fails the CommonJS bundle whose require() the packaged application does not ship', async () => {
await expect(generate('require', { ...MAIN, packages: new Set(['electron']) }, 'cjs')).rejects.toThrow(unshipped)
})
it('fails a preload bundle that requires a Node builtin the sandbox does not polyfill', async () => {
await expect(generate('builtin', PRELOAD, 'cjs')).rejects.toThrow(
/builtin\.js imports node:fs, which the packaged application does not ship\. /u,
)
await expect(generate('builtin', PRELOAD, 'cjs')).rejects.toThrow(
/This bundle may leave only electron, events, timers, url as bare imports/u,
)
})
it('passes the bundles whose external imports are all packaged', async () => {
const policy = { ...MAIN, packages: new Set(['electron', '@deepseek-ai/dsh-home-paths']) }
for (const entry of ['static', 'dynamic'] as const) {
const output = await generate(entry, policy)
expect(output.output.map(chunk => chunk.fileName)).toEqual([`${entry}.js`])
}
const output = await generate('require', policy, 'cjs')
expect(output.output.map(chunk => chunk.fileName)).toEqual(['require.js'])
})
})
+114
View File
@@ -0,0 +1,114 @@
import { spawn } from 'node:child_process'
import { once } from 'node:events'
import { copyFile, mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { pathToFileURL } from 'node:url'
import { expect, it, vi } from 'vitest'
import { createFlockEntryLoader } from '../scripts/flock-entry.ts'
type Entry = Awaited<ReturnType<ReturnType<typeof createFlockEntryLoader>>>
const entry = { tryLockExclusive: vi.fn() } as Entry
const BUILD_TEXT = 'pnpm run build:native-system && pnpm --dir native/system run build:ts'
function notFound(): NodeJS.ErrnoException {
return Object.assign(new Error("Cannot find module 'lib/flock.js'"), { code: 'ERR_MODULE_NOT_FOUND' })
}
function steps(overrides: Partial<Parameters<typeof createFlockEntryLoader>[0]> = {}) {
return {
importEntry: vi.fn(overrides.importEntry ?? (async () => entry)),
hostAddonBuilt: vi.fn(overrides.hostAddonBuilt ?? (() => true)),
build: vi.fn(overrides.build ?? (async () => {})),
}
}
function quietStderr(): () => void {
const spy = vi.spyOn(process.stderr, 'write').mockReturnValue(true)
return () => { spy.mockRestore() }
}
it('returns the imported entry without building and memoizes it', async () => {
const used = steps()
const load = createFlockEntryLoader(used)
expect(await load()).toBe(entry)
expect(await load()).toBe(entry)
expect(used.importEntry).toHaveBeenCalledTimes(1)
expect(used.hostAddonBuilt).toHaveBeenCalledTimes(1)
expect(used.build).not.toHaveBeenCalled()
})
it('builds once and imports again when the JavaScript entry is missing', async () => {
const order: string[] = []
const used = steps({
importEntry: async () => {
order.push('import')
if (order.length === 1) throw notFound()
return entry
},
build: async () => { order.push('build') },
})
const written: string[] = []
const stderr = vi.spyOn(process.stderr, 'write').mockImplementation((chunk) => { written.push(String(chunk)); return true })
try {
const load = createFlockEntryLoader(used)
expect(await load()).toBe(entry)
expect(await load()).toBe(entry)
} finally { stderr.mockRestore() }
expect(order).toEqual(['import', 'build', 'import'])
expect(written).toEqual([expect.stringContaining(BUILD_TEXT)])
})
it('builds when the entry imports but the host addon binary is missing', async () => {
const used = steps({ hostAddonBuilt: () => false })
const restore = quietStderr()
try {
expect(await createFlockEntryLoader(used)()).toBe(entry)
} finally { restore() }
expect(used.build).toHaveBeenCalledTimes(1)
expect(used.importEntry).toHaveBeenCalledTimes(2)
})
it('propagates other import errors without building', async () => {
const used = steps({ importEntry: async () => { throw new Error('addon binding failed') } })
await expect(createFlockEntryLoader(used)()).rejects.toThrow('addon binding failed')
expect(used.build).not.toHaveBeenCalled()
})
it('propagates a build failure, does not import again, and retries on the next call', async () => {
const used = steps({
importEntry: async () => { throw notFound() },
build: async () => { throw new Error('tsc exited with 2') },
})
const restore = quietStderr()
try {
const load = createFlockEntryLoader(used)
await expect(load()).rejects.toThrow('tsc exited with 2')
expect(used.importEntry).toHaveBeenCalledTimes(1)
used.importEntry.mockResolvedValueOnce(entry)
expect(await load()).toBe(entry)
} finally { restore() }
expect(used.build).toHaveBeenCalledTimes(1)
})
it('loads the proxy module where the addon package cannot be resolved', async () => {
// A directory outside every node_modules tree stands in for a checkout whose native/system is unbuilt.
const root = await mkdtemp(join(tmpdir(), 'flock-entry-test-'))
try {
for (const name of ['macos-notarization-proxy.ts', 'flock-entry.ts']) {
await copyFile(new URL(`../scripts/${name}`, import.meta.url), join(root, name))
}
const child = spawn(process.execPath, ['--input-type=module', '-e', `
const module = await import(${JSON.stringify(pathToFileURL(join(root, 'macos-notarization-proxy.ts')).href)});
process.stdout.write(Object.keys(module).sort().join(','));
`], { stdio: ['ignore', 'pipe', 'pipe'], env: { PATH: process.env.PATH } })
let stdout = ''
let stderr = ''
child.stdout.setEncoding('utf8').on('data', (chunk: string) => { stdout += chunk })
child.stderr.setEncoding('utf8').on('data', (chunk: string) => { stderr = (stderr + chunk).slice(-8192) })
const [code] = await once(child, 'close') as [number | null]
expect(code, stderr).toBe(0)
expect(stdout).toBe('restoreMacOSNotarizationProxy,withMacOSNotarizationProxy')
} finally { await rm(root, { recursive: true, force: true }) }
})
+18
View File
@@ -1,8 +1,24 @@
import { defineConfig } from 'tsdown'
import { build } from 'vite'
import { fileURLToPath } from 'node:url'
import { readFileSync } from 'node:fs'
import { readFile } from 'node:fs/promises'
import { repositoryClientBuildEnvironment, resolveClientBuildEnvironment } from '../../scripts/client-build-environment.ts'
import { packagedImportsPlugin } from './scripts/desktop-bundle-imports.mjs'
// This config runs after the workspace tsdown pass, not inside it: the main bundle inlines
// workspace devDependencies from their lib/ output, which the concurrent workspace pass does
// not order ahead of this package (root package.json build:lib:host).
const manifest = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8')) as {
dependencies: Record<string, string>
}
/** electron-builder ships the manifest `dependencies` next to the main bundle; Electron provides `electron` and Node. */
const mainProcessImports = { packages: new Set(['electron', ...Object.keys(manifest.dependencies)]), nodeBuiltins: true }
/**
* The `require` polyfill of a sandboxed preload resolves only these modules
* (Electron: Process Sandboxing, "Preload scripts").
*/
const preloadImports = { packages: new Set(['electron', 'events', 'timers', 'url']), nodeBuiltins: false }
const REPOSITORY_ROOT = fileURLToPath(new URL('../..', import.meta.url))
@@ -19,6 +35,7 @@ const clientVersionDefine = { 'process.env.DSH_CLIENT_VERSION': JSON.stringify(c
export default defineConfig([
{
entry: ['lib/types/main.js'],
plugins: [packagedImportsPlugin(mainProcessImports)],
define: clientVersionDefine,
onSuccess: async () => {
await build({
@@ -63,6 +80,7 @@ export default defineConfig([
...(['preload-app', 'preload-welcome', 'preload-platform-account', 'preload-mandatory', 'preload-update-dialog'] as const).map(name => ({
// Sandboxed Electron preloads run as CommonJS even though the application package is ESM.
entry: { [name]: `lib/types/${name}.js` },
plugins: [packagedImportsPlugin(preloadImports)],
outDir: 'lib',
format: 'cjs' as const,
codeSplitting: false,
+2 -2
View File
@@ -12,8 +12,8 @@
en: e29f1d7026291075
zh: 15e361e797d44fce
/api-gateway/strict-generation-pipeline:
en: 06c84cb25fb6c940
zh: d639c6e0bd271759
en: cb8da81a92acfa52
zh: be5f3c268f8571df
/api-gateway/runtime-invocation:
en: 2a2fed340aaa926c
zh: 46bb1f500c870a76
+1 -1
View File
@@ -98,7 +98,7 @@ The API Gateway package owns the Host dispatcher and Client Remote endpoint as p
The root build runs `build:lib:host`, `build:lib:client`, and `build:web` in order. The Host lib phase first runs `tsc -b tsconfig.host.json`, then `tsdown --env.DSH_BUILD_FACE host`; the normal Host Project Reference graph compiles the Typert generator, which runs during this tsdown pass with the Host aggregate as its only `ts.Program` seed. The Client lib phase then runs `tsc -b tsconfig.client.json` and `tsdown --env.DSH_BUILD_FACE client`, consuming the newly generated Remote Client declarations and runtime contributions without starting Typert again.
Both tsdown passes receive the complete workspace and bundle only JavaScript emitted to `lib/types` by the corresponding tsc phase. The root config does not scan Client artifacts, classify package names, or pass a maintained filter to tsdown; package-local configs return entries for the current phase based on `DSH_BUILD_FACE`. An ordinary Client plugin produces both its Node loader entry and browser bundle during the Client phase.
Both tsdown passes match `vendor/*`, `packages/*/*`, and `apps/cli`, the Host pass also `apps/desktop-host` ([build order](development.md#typescript-project-layout)), and both bundle only JavaScript emitted to `lib/types` by the corresponding tsc phase. The root config does not scan Client artifacts, classify package names, or pass a maintained filter to tsdown; package-local configs return entries for the current phase based on `DSH_BUILD_FACE`. An ordinary Client plugin produces both its Node loader entry and browser bundle during the Client phase.
`api/remotes`, `api/gateway`, `api/session-controller`, and `api/workspace-controller` (plus `client/connection`) split TypeScript faces. `api/remotes`' Client project depends on `/remote` declarations generated for business packages during Host tsdown; root aggregates and direct consumers must reference each split package's `tsconfig.host.json` or `tsconfig.client.json` respectively. `api-remotes`' `clientBundle(..., { hostPhase: true })` produces its Host entry during Host tsdown and leaves only the browser entry for Client tsdown. The Agent/Session lookup policy lives in `@deepseek-ai/dsh-api-session-controller`, not in `api-remotes`.
+1 -1
View File
@@ -98,7 +98,7 @@ API Gateway 包同时拥有 Host dispatcher 与 Client Remote endpoint 两个对
根构建依次执行 `build:lib:host`、`build:lib:client` 与 `build:web`。Host lib 阶段先运行 `tsc -b tsconfig.host.json`,再运行 `tsdown --env.DSH_BUILD_FACE host`;Typert generator 由正常 Host Project Reference 图编译,并在这次 tsdown 中以 Host aggregate 为唯一 `ts.Program` 种子运行。Client lib 阶段随后运行 `tsc -b tsconfig.client.json` 与 `tsdown --env.DSH_BUILD_FACE client`,使用刚生成的 Remote Client 声明和运行时贡献,但不再次启动 Typert。
两次 tsdown 都接收完整 workspace,且都只打包 `lib/types` 中由对应 tsc 阶段发射的 JavaScript。根配置不扫描 Client 产物、不按包名分类,也不向 tsdown 传维护式 filter;各包的本地配置根据 `DSH_BUILD_FACE` 返回当前阶段的入口。普通 Client 插件在 Client 阶段一起生成 Node loader 入口与 browser bundle。
两次 tsdown 都匹配 `vendor/*`、`packages/*/*` 与 `apps/cli`,Host 阶段另外匹配 `apps/desktop-host`([构建顺序](development.zh.md#typescript-project-layout)),且都只打包 `lib/types` 中由对应 tsc 阶段发射的 JavaScript。根配置不扫描 Client 产物、不按包名分类,也不向 tsdown 传维护式 filter;各包的本地配置根据 `DSH_BUILD_FACE` 返回当前阶段的入口。普通 Client 插件在 Client 阶段一起生成 Node loader 入口与 browser bundle。
`api/remotes`、`api/gateway`、`api/session-controller` 与 `api/workspace-controller`(外加 `client/connection`)都拆分 TypeScript face。`api/remotes` 的 Client project 依赖业务包在 Host tsdown 中生成的 `/remote` 声明;根 aggregate 与直接消费方必须分别引用各拆分包自己的 `tsconfig.host.json` 或 `tsconfig.client.json`。`api-remotes` 的 `clientBundle(..., { hostPhase: true })` 让 Host 入口在 Host tsdown 中生成,让 Client tsdown 只生成 browser 入口。Agent/Session lookup 策略位于 `@deepseek-ai/dsh-api-session-controller`,而非 `api-remotes`。
+2 -2
View File
@@ -21,8 +21,8 @@
en: 3221d1076554001f
zh: 29f166be6a5c04d9
/development-guide/contributor-reference/typescript-project-layout:
en: 37441690bae1ebf4
zh: 498777f8f25b6940
en: de9ab4baab0c5c91
zh: cde7e8ab4f698fcb
/development-guide/contributor-reference/environment-variables:
en: dba2c72ee6ffa930
zh: b65c27fbb9129ec8
+2 -1
View File
@@ -74,12 +74,13 @@ The root build follows the generated dependency order:
```sh
tsc -b tsconfig.host.json
tsdown --env.DSH_BUILD_FACE host
pnpm --filter @deepseek-ai/dsh-desktop run bundle
tsc -b tsconfig.client.json
tsdown --env.DSH_BUILD_FACE client
pnpm run build:web
```
Both tsdown passes use the same complete workspace match. They neither scan build artifacts to discover Client packages nor maintain a Host/Client package filter list. Package-local tsdown configs select entries for the current phase through `DSH_BUILD_FACE`: an ordinary Client plugin produces both its Node loader and browser bundle during the Client phase; `api-remotes` uses `hostPhase: true` to produce its Host entry early and only its browser bundle during the Client phase. Tsdown consumes only the JavaScript emitted to `lib/types` by the preceding tsc phase.
Both tsdown passes match `vendor/*`, `packages/*/*`, and `apps/cli`; the Host pass also matches `apps/desktop-host`. They neither scan build artifacts to discover Client packages nor maintain a Host/Client package filter list. Package-local tsdown configs select entries for the current phase through `DSH_BUILD_FACE`: an ordinary Client plugin produces both its Node loader and browser bundle during the Client phase; `api-remotes` uses `hostPhase: true` to produce its Host entry early and only its browser bundle during the Client phase. Tsdown consumes only the JavaScript emitted to `lib/types` by the preceding tsc phase. Tsdown builds the matched workspace members concurrently, so `apps/desktop`, whose main bundle inlines workspace devDependencies from their `lib/` output, bundles in its own step after the Host pass ([Desktop README](../apps/desktop/README.md#bundled-workspace-dependencies)).
Typert runs only during Host tsdown, seeded by `tsconfig.host.json`. It analyzes Host types and generates both Host reflection artifacts and the Host-for-Client Remote projection; Client tsdown does not start Typert. Consequently, `pnpm run typecheck` runs the complete Host lib phase before Client tsc, while `pnpm run build` continues through Client tsdown and the Web build.
+2 -1
View File
@@ -78,12 +78,13 @@ Host 与 Client 保持两个 aggregate program,是因为两侧在相同键下
```sh
tsc -b tsconfig.host.json
tsdown --env.DSH_BUILD_FACE host
pnpm --filter @deepseek-ai/dsh-desktop run bundle
tsc -b tsconfig.client.json
tsdown --env.DSH_BUILD_FACE client
pnpm run build:web
```
两次 tsdown 都使用同一组完整 workspace 匹配,不扫描构建产物来发现 Client 包,也不维护 Host/Client 包过滤表。包内 tsdown 配置根据 `DSH_BUILD_FACE` 决定当前阶段的入口:普通 Client 插件在 Client 阶段同时生成 Node loader 与 browser bundle;`api-remotes` 通过 `hostPhase: true` 提前生成 Host 入口,再在 Client 阶段只生成 browser bundle。tsdown 只消费 `lib/types` 中由前置 tsc 发射的 JavaScript。
两次 tsdown 都匹配 `vendor/*`、`packages/*/*` 与 `apps/cli`,Host 阶段另外匹配 `apps/desktop-host`;两者都不扫描构建产物来发现 Client 包,也不维护 Host/Client 包过滤表。包内 tsdown 配置根据 `DSH_BUILD_FACE` 决定当前阶段的入口:普通 Client 插件在 Client 阶段同时生成 Node loader 与 browser bundle;`api-remotes` 通过 `hostPhase: true` 提前生成 Host 入口,再在 Client 阶段只生成 browser bundle。tsdown 只消费 `lib/types` 中由前置 tsc 发射的 JavaScript。tsdown 并发构建匹配到的 workspace 成员;`apps/desktop` 的主进程 bundle 需要从工作区 devDependencies 的 `lib/` 产物内联这些包,因此在 Host 阶段之后单独一步打 bundle([Desktop README](../apps/desktop/README.zh.md#bundled-workspace-dependencies))。
Typert 只在 Host tsdown 中以 `tsconfig.host.json` 为种子运行。它分析 Host 类型并生成 Host 反射产物及 Host-for-Client Remote 投影;Client tsdown 不启动 Typert。`pnpm run typecheck` 因此先执行完整 Host lib 阶段,再运行 Client tsc;`pnpm run build` 继续执行 Client tsdown 和 Web 构建。
+1 -1
View File
@@ -22,7 +22,7 @@
"build:bench": "npm run build:native-system && npm run build:lib && tsdown --config benchmarks/tsdown.config.ts",
"build:official": "tsx scripts/build.ts --profile official",
"build:lib": "pnpm run build:lib:host && pnpm run build:lib:client",
"build:lib:host": "node --max-old-space-size=4096 ./node_modules/typescript/bin/tsc -b tsconfig.host.json && tsdown --env.DSH_BUILD_FACE host",
"build:lib:host": "node --max-old-space-size=4096 ./node_modules/typescript/bin/tsc -b tsconfig.host.json && tsdown --env.DSH_BUILD_FACE host && pnpm --filter @deepseek-ai/dsh-desktop run bundle",
"build:lib:client": "tsc -b tsconfig.client.json && tsdown --env.DSH_BUILD_FACE client",
"build:web": "pnpm --filter @deepseek-ai/dsh-web-frontend run build",
"build:desktop": "pnpm --filter @deepseek-ai/dsh-desktop run build",
+2 -2
View File
@@ -18,8 +18,8 @@
en: 8df3db7ca8cc6110
zh: e872f6333ead59c4
/deepseek-ai-dsh-client-shortcuts/understand-the-implementation:
en: b8d3d177181359f6
zh: d5dfec9df8b13494
en: adfd258f490cacb1
zh: 44c080babc54c6a9
/deepseek-ai-dsh-client-shortcuts/further-exploration:
en: 8fe02ef5221e434d
zh: 3aabfcfeb6d49a0e
+2
View File
@@ -45,6 +45,8 @@ Bindings activate after the first read. Failed reads preserve the last accepted
<details>
<summary>Implementation internals — click to expand</summary>
The Host build emits the Node entry and `./protocol` before Desktop bundles its keyboard integration; the Client pass emits the browser bundle.
Windows and macOS Desktop intercept complete accepted combinations before local handlers and forward them through the trusted preload. Desktop startup requires the native keyboard bridge on every platform. On Windows and macOS, only native input dispatches configurable commands; DOM input continues to feed fixed actions. The adapter intercepts a key release only when it intercepted that key’s initial press. Default and user-saved bindings have identical priority, including over modal controls. Other environments dispatch after local handlers and respect their declared regions. Composition, dead keys, AltGraph, and consumed input pass through; macOS Web can consume a bound Option+Command+N reported as a dead key outside composition without guarding the next input. Web and Linux modal layers block background commands. Owned repeats remain consumed without rerunning the action. The context carries the original DOM input element, including elements inside a shadow root. Owners synchronously resolve their target and retain responsibility for action errors. `ctx.shortcuts.closeWindow()` owns the Desktop keyboard bridge and sends its current accepted revision; Web calls and bridge request failures reject. The pure `./protocol` export has no React, DOM, or Electron dependency and shares validation and serialized persistence between adapters. Explicit overrides displace conflicting new defaults; conflicting explicit overrides are all disabled. Desktop rejects stale revisions and restricts IPC to the current product window and top frame. Rejected adapter calls are logged and returned as save failures; errors while publishing an accepted command catalog propagate to the caller.
DOM fixed-input observers receive composition and consumption flags before application dispatch. Consuming an event makes it unavailable to subsequent observers and commands. Focus, pointer, window blur, composition, modal changes, and locally stopped propagation reset pending DOM sequences. Native chords reset on window blur, focused-frame or configuration changes, composition, recording, and modifier release. Electron can omit keyups after native interception; completing a native binding discards held-key state, so each chord activation needs two fresh presses. Releasing a modifier clears held-key state because macOS may omit character keyup events while Command is held. The adapter removes its listeners and modal observer when disposed; one feature's observer failure does not prevent the remaining observers from receiving input.
+2
View File
@@ -45,6 +45,8 @@ Windows 和 macOS Desktop 接受一至两个不同的受支持非修饰键,可
<details>
<summary>实现细节——点击展开</summary>
Host 构建在 Desktop 打包键盘集成之前生成 Node 入口和 `./protocol`;Client 阶段生成浏览器 bundle。
Windows 和 macOS Desktop 在局部处理器之前拦截已接受的完整组合,通过可信 preload 转发。所有平台的 Desktop 启动都要求原生键盘桥接。Windows 和 macOS 的可配置命令只由原生输入分发;DOM 输入继续交给固定操作。适配器仅拦截初次按下事件已被拦截的按键的松开事件。默认绑定与用户保存的绑定优先级一致,均优先于模态控件。其他环境在局部处理器之后分发,并遵守声明的区域。输入法组合、死键、AltGraph 和已消费的输入继续传递;macOS Web 可在输入法组合之外消费已绑定且报告为死键的 Option+Command+N,不保护后续输入。Web 和 Linux 的模态层阻止后台命令。已接管的重复事件仍被消费,但不重复执行。上下文携带原始 DOM 输入元素,包括 shadow root 内的元素。owner 同步解析目标,并负责操作错误。`ctx.shortcuts.closeWindow()` 统一持有 Desktop 键盘桥接,并携带当前已接受的 revision;Web 调用和桥接请求错误均返回失败。纯 `./protocol` 导出不依赖 React、DOM 或 Electron,在两个适配器间共享校验和串行持久化。显式覆盖取代冲突的新默认值;互相冲突的显式覆盖全部禁用。Desktop 拒绝过期版本,并将 IPC 限制在当前产品窗口和顶层 frame。适配器调用被拒绝时会记录日志并返回保存失败;发布已接受命令目录时的错误会向调用方抛出。
DOM 固定输入观察者在应用分发前收到输入法组合和消费标记。消费事件后,后续观察者和命令不能使用它。焦点、指针、窗口失焦、输入法组合、模态变化和局部停止传播会重置待完成的 DOM 序列。原生双键状态在窗口失焦、焦点 frame 或配置变化、输入法组合、录制和修饰键释放时重置。Electron 在原生拦截后可能省略 keyup;原生绑定完成时立即清空按住状态,因此每次触发双键组合都需要重新按下两个键。释放修饰键会清空按住状态,因为 macOS 在按住 Command 时可能省略字符键的 keyup。适配器释放时移除监听器和模态观察者;单个功能观察者失败不妨碍其他观察者接收输入。
+5 -1
View File
@@ -1,3 +1,7 @@
import { clientBundle } from '../tsdown.client.ts'
export default clientBundle('@deepseek-ai/dsh-client-shortcuts', ['lib/types/index.js', 'lib/types/protocol.js'])
export default clientBundle(
'@deepseek-ai/dsh-client-shortcuts',
['lib/types/index.js', 'lib/types/protocol.js'],
{ hostPhase: true },
)
+6 -3
View File
@@ -239,12 +239,14 @@ cat "$scratch/logs/smoke.log"
grep -q '^smoke: win32 x64' "$scratch/logs/smoke.log" || { echo 'wine-windows-gates: Windows Node smoke did not report win32 x64' >&2; exit 1; }
# ---- the two blocking surfaces, concurrently ------------------------------
# The build preserves the face order from package.json: compile and bundle the
# Host face before compiling and bundling the Client face.
# The build mirrors the root build:lib:host and build:lib:client scripts:
# compile and bundle the Host face, bundle apps/desktop from the Host lib/
# outputs, then compile and bundle the Client face.
# Both statuses are captured so one failure cannot hide the other's result.
build_gate() {
wine_node "$scratch/logs/host-tsc.log" --max-old-space-size=4096 "$tsc_js" -b tsconfig.host.json --pretty false || return $?
wine_node "$scratch/logs/host-tsdown.log" "$tsdown_js" --env.DSH_BUILD_FACE host || return $?
(cd apps/desktop && wine_node "$scratch/logs/desktop-tsdown.log" "../../$tsdown_js") || return $?
wine_node "$scratch/logs/client-tsc.log" "$tsc_js" -b tsconfig.client.json --pretty false || return $?
wine_node "$scratch/logs/client-tsdown.log" "$tsdown_js" --env.DSH_BUILD_FACE client
}
@@ -272,9 +274,10 @@ report() {
for log in "$@"; do tail -n 200 "$log" >&2 || true; done
fi
}
report 'build (Host tsc/tsdown, Client tsc/tsdown)' "$build_status" \
report 'build (Host tsc/tsdown, desktop tsdown, Client tsc/tsdown)' "$build_status" \
"$scratch/logs/host-tsc.log" \
"$scratch/logs/host-tsdown.log" \
"$scratch/logs/desktop-tsdown.log" \
"$scratch/logs/client-tsc.log" \
"$scratch/logs/client-tsdown.log"
report 'production site (vitepress build)' "$site_status" "$scratch/logs/site.log"
+5 -2
View File
@@ -11,14 +11,17 @@ function isBuildFaceClient(value: unknown): boolean {
* The ordinary workspace build consumes JavaScript emitted by the Host
* TypeScript project and runs Typert. The Client pass selects packages that
* declare a browser bundle and lets their package-local configs emit both
* their Node loader entry and browser artifact.
* their Node loader entry and browser artifact. `apps/desktop` bundles after
* this pass (root package.json `build:lib:host`): its main bundle inlines
* workspace devDependencies from their lib/ output, and tsdown builds
* workspace members concurrently without ordering them.
*/
export default defineConfig(({ env }) => {
const client = isBuildFaceClient(env?.DSH_BUILD_FACE)
return {
workspace: client
? ['vendor/*', 'packages/*/*', 'apps/cli']
: ['vendor/*', 'packages/*/*', 'apps/cli', 'apps/desktop', 'apps/desktop-host'],
: ['vendor/*', 'packages/*/*', 'apps/cli', 'apps/desktop-host'],
entry: client ? '' : ['lib/types/{index,invariant,startup}.js'],
outDir: 'lib',
format: ['esm'],