Merge origin/master into worktree/conditional-tools
This commit is contained in:
commit
aa0bc561df
225 files changed
+6471
-1346
No files matched your search
+2
-2
@@ -33,8 +33,8 @@
|
||||
en: a244f6a88fdabf3d
|
||||
zh: e4feedb7297f4865
|
||||
/agent-note-typert-gateway-targeted-method-calls/three-artifact-kinds-and-two-typescript-programs:
|
||||
en: a5134745815f762f
|
||||
zh: 99b6a905abd58e6a
|
||||
en: c5bcd6eb76bf3d42
|
||||
zh: 9df2fbb364643186
|
||||
/agent-note-typert-gateway-targeted-method-calls/the-remote-package-entry:
|
||||
en: 75e977fe0fb71d59
|
||||
zh: 00760c79da173cb7
|
||||
|
||||
@@ -215,7 +215,7 @@ Host lib build
|
||||
→ Vite 构建 Web
|
||||
```
|
||||
|
||||
The top-level `build` runs the step graph in `scripts/build.ts`, which completes the Host bundle and the Remote artifacts before starting Client TypeScript compilation. `build:lib` remains the complete serial lib build for `build:bench`, and its Host half `build:lib:host` serves `typecheck` and the vendor release workflows. A clean build must not depend on stale `.d.ts` files from an earlier build.
|
||||
The top-level `build` runs the step graph in `scripts/build.ts`, which completes the Host bundle and the Remote artifacts before starting Client TypeScript compilation. `build:lib` remains the complete serial lib build for `build:bench`, and its Host half `build:lib:host` serves the vendor release workflows. `typecheck` writes the Remote artifacts through `scripts/generate-typert.ts`, beside Host compilation, before Client TypeScript compilation. A clean build must not depend on stale `.d.ts` files from an earlier build.
|
||||
|
||||
Compiler-backed repository gates that resolve the consumer surface have the same prerequisite even when their primary inputs are source files. The public `typecheck`, `lint`, and `doc-typecheck` commands run the Host contract pass first. The gate scheduler may use their `*:contracts-ready` variants only after an explicit Typert-contract or complete-build dependency, so parallel lanes neither read missing declarations nor run concurrent generators against the same outputs.
|
||||
|
||||
|
||||
@@ -215,7 +215,7 @@ Host lib build
|
||||
→ Vite 构建 Web
|
||||
```
|
||||
|
||||
顶层 `build` 运行 `scripts/build.ts` 中的步骤图,先完成 Host bundle 与 Remote artifact,再启动 Client TypeScript 编译。`build:lib` 仍是 `build:bench` 使用的完整串行 lib 构建,其 Host 部分 `build:lib:host` 供 `typecheck` 与 vendor 发布 workflow 使用。一次干净构建不能依赖上次残留的 `.d.ts`。
|
||||
顶层 `build` 运行 `scripts/build.ts` 中的步骤图,先完成 Host bundle 与 Remote artifact,再启动 Client TypeScript 编译。`build:lib` 仍是 `build:bench` 使用的完整串行 lib 构建,其 Host 部分 `build:lib:host` 供 vendor 发布 workflow 使用。`typecheck` 与 Host 编译并行,经 `scripts/generate-typert.ts` 写出 Remote artifact,再启动 Client TypeScript 编译。一次干净构建不能依赖上次残留的 `.d.ts`。
|
||||
|
||||
即使主要输入是源文件,需要通过编译器解析消费方 surface 的仓库门禁也有相同的前置条件。公共 `typecheck`、`lint` 和 `doc-typecheck` 命令会先执行 Host 约定 pass。门禁调度器仅可在显式的 Typert 约定依赖或完整构建依赖完成后使用对应的 `*:contracts-ready` 变体,使并行 lane 既不会读取缺失的声明,也不会针对同一输出并发运行多个生成器。
|
||||
|
||||
|
||||
+2
-2
@@ -24,8 +24,8 @@
|
||||
en: e9f140cd22670dfa
|
||||
zh: bf85cfe9c12a0345
|
||||
/agent-note-package-and-update-the-electron-desktop-application/security-and-release-policy:
|
||||
en: 97ee608e96fc3602
|
||||
zh: 932b98e7d344cd87
|
||||
en: 36559f9179764da7
|
||||
zh: f1d39a6438ca520c
|
||||
/agent-note-package-and-update-the-electron-desktop-application/implementation:
|
||||
en: 041a6d35ed61b149
|
||||
zh: 617c6b90a6f4fa4d
|
||||
|
||||
+1
-1
@@ -81,7 +81,7 @@ Test releases require `DOWNLOAD_TEST_RELEASE_ID` from the platform dotenv file.
|
||||
|
||||
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 package and upload commands read release settings from the Git-ignored target `.env.windows` or `.env.macos`; subprocesses receive the fields selected by orchestration. The target file exclusively owns release fields so stale shell or system credentials cannot override local selection, and loading does not mutate the parent environment. Packaging validates the mode-specific application ID, update origin, signing identity, and local files before builds, downloads, or release-record cleanup; macOS also requires one complete notarization strategy. The separate `check:package` command runs the same validation without accessing the token or Apple; actual signing and notarization still verify authentication. Configuration loading rejects missing or malformed identifiers and incomplete notarization credentials, while macOS release 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. The fixed-target installer command uses [isolated App copies for parallel notarization](../process/2026-09-09-parallel-macos-notarization.md): the ZIP contains a stapled App, while the signed DMG carries the ticket covering its unstapled inner App. The DMG artifact-completion hook requires the configured identity, a valid ticket, and Gatekeeper acceptance. Both artifact lanes must succeed before the command promotes their outputs and writes the release completion record; directory-only commands still notarize and staple the App. DMG blockmaps are disabled because macOS updates consume the signed ZIP, and stapling would otherwise invalidate an already-generated DMG blockmap.
|
||||
Electron release artifacts are signed; macOS artifacts are notarized. Release package and upload commands read release settings from the Git-ignored target `.env.windows` or `.env.macos`; subprocesses receive the fields selected by orchestration. Windows packaging can instead select a machine-owned public `presets/<preset>.env`, plus `secrets/windows-signing.env` for signed builds; unsigned and preparation-only modes omit the signing file. The selected files exclusively own release fields so stale shell or system credentials cannot override local selection, and loading does not mutate the parent environment. Packaging validates the mode-specific application ID, update origin, signing identity, and local files before builds, downloads, or release-record cleanup; macOS also requires one complete notarization strategy. The separate `check:package` command runs the same validation without accessing the token or Apple; actual signing and notarization still verify authentication. Configuration loading rejects missing or malformed identifiers and incomplete notarization credentials, while macOS release 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. The fixed-target installer command uses [isolated App copies for parallel notarization](../process/2026-09-09-parallel-macos-notarization.md): the ZIP contains a stapled App, while the signed DMG carries the ticket covering its unstapled inner App. The DMG artifact-completion hook requires the configured identity, a valid ticket, and Gatekeeper acceptance. Both artifact lanes must succeed before the command promotes their outputs and writes the release completion record; directory-only commands still notarize and staple the App. DMG blockmaps are disabled because macOS updates consume the signed ZIP, and stapling would otherwise invalidate an already-generated DMG blockmap.
|
||||
|
||||
The [pinned osx-sign patch](../../../../patches/@[email protected]) 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.
|
||||
|
||||
|
||||
+1
-1
@@ -81,7 +81,7 @@ Electron 更新只使用一个 `electron-updater` 发布流和签名 `electron-b
|
||||
|
||||
核心 dsh 和私有 Desktop Host 只来自签名应用的资源树。插件安装把包规格交给 pnpm,包括本地和远程来源,但不接受原始 pnpm 命令。pnpm 负责依赖解析和 profile 的 `allowBuilds` 策略;Host 加载已启用的 bundle。
|
||||
|
||||
Electron 发布产物必须签名;macOS 产物必须公证。发布打包与上传命令从 Git 忽略的目标 `.env.windows` 或 `.env.macos` 读取发布配置,子进程通过编排器选择的环境字段接收配置。目标文件是发布字段的唯一来源,避免旧的 shell 或系统凭据覆盖本地选择;配置加载不修改父进程环境。打包在构建、下载或清理发布记录前校验该模式必需的应用 ID、更新地址、签名身份及本地文件,macOS 还要求一套完整公证凭据。单独的 `check:package` 执行同一校验而不访问 Token 或 Apple;凭据真实性仍由实际签名与公证验证。配置加载会拒绝缺失或格式错误的标识符和不完整的公证凭据,macOS 发布打包还会强制签名,避免证书发现过程静默选择其他已安装身份或生成未签名发布。运行时准备会验证每个内嵌 Mach-O 文件的精确 Authority 与 Team ID,以及时间戳和 hardened-runtime 标记。签名后钩子会执行 Apple 的深度严格应用验证,并要求同一叶证书 Authority 与 Team ID 完全匹配,验证通过后才继续生成产物。固定目标安装包命令使用[隔离的 App 副本并行公证](../process/2026-09-09-parallel-macos-notarization.zh.md):ZIP 包含已钉票的 App,签名 DMG 则携带覆盖其中未钉票 App 的票据。DMG 的 artifact-completion hook 要求其使用配置的身份、具备有效票据并通过 Gatekeeper。只有两条产物流都成功,命令才会移入其输出并写入发布完成记录;仅生成目录的命令仍会公证 App 并钉票。macOS 更新使用签名 ZIP,因此 DMG 不生成 blockmap;否则钉票会让已经生成的 DMG blockmap 失效。
|
||||
Electron 发布产物必须签名;macOS 产物必须公证。发布打包与上传命令从 Git 忽略的目标 `.env.windows` 或 `.env.macos` 读取发布配置,子进程通过编排器选择的环境字段接收配置。Windows 打包也可选择机器管理的公开 `presets/<preset>.env`,签名构建另读 `secrets/windows-signing.env`;未签名和仅准备模式不读取签名文件。所选文件是发布字段的唯一来源,避免旧的 shell 或系统凭据覆盖本地选择;配置加载不修改父进程环境。打包在构建、下载或清理发布记录前校验该模式必需的应用 ID、更新地址、签名身份及本地文件,macOS 还要求一套完整公证凭据。单独的 `check:package` 执行同一校验而不访问 Token 或 Apple;凭据真实性仍由实际签名与公证验证。配置加载会拒绝缺失或格式错误的标识符和不完整的公证凭据,macOS 发布打包还会强制签名,避免证书发现过程静默选择其他已安装身份或生成未签名发布。运行时准备会验证每个内嵌 Mach-O 文件的精确 Authority 与 Team ID,以及时间戳和 hardened-runtime 标记。签名后钩子会执行 Apple 的深度严格应用验证,并要求同一叶证书 Authority 与 Team ID 完全匹配,验证通过后才继续生成产物。固定目标安装包命令使用[隔离的 App 副本并行公证](../process/2026-09-09-parallel-macos-notarization.zh.md):ZIP 包含已钉票的 App,签名 DMG 则携带覆盖其中未钉票 App 的票据。DMG 的 artifact-completion hook 要求其使用配置的身份、具备有效票据并通过 Gatekeeper。只有两条产物流都成功,命令才会移入其输出并写入发布完成记录;仅生成目录的命令仍会公证 App 并钉票。macOS 更新使用签名 ZIP,因此 DMG 不生成 blockmap;否则钉票会让已经生成的 DMG blockmap 失效。
|
||||
|
||||
[固定版本的 osx-sign 补丁](../../../../patches/@[email protected])在两种已发布模块构建中使用 `lstat`,因此 Framework 的文件和目录别名不会触发重复签名。选定的上游版本能够跳过这些别名前,仍需保留该补丁。PAK 文件由外层 bundle 签名记录完整性;逐个签名会增加串行时间戳请求,但不会增加资源完整性保护。Desktop 保留全部语言文件,只跳过其单独签名。可执行代码仍使用 Developer ID 签名、安全时间戳和 hardened runtime。[签名器遍历回归测试](../../../../apps/desktop/tests/macos-signing-walk.spec.ts)使用真实 Framework 别名执行已安装依赖;发布验收仍要求严格应用验证、公证和启动。
|
||||
|
||||
|
||||
+6
-6
@@ -9,14 +9,14 @@
|
||||
en: 837ebb0071a5611b
|
||||
zh: 23d0f0713889ead6
|
||||
/agent-note-writer-acquisition-for-blank-session-reuse/decision:
|
||||
en: 7f2676feb224e7ea
|
||||
zh: babfda5b31dfd0fe
|
||||
en: a54db0d4a97aa9b8
|
||||
zh: a52d257b657fe99b
|
||||
/agent-note-writer-acquisition-for-blank-session-reuse/alternatives-considered:
|
||||
en: 2a67a53f7f396ba8
|
||||
zh: 6df6ccc071fb0de2
|
||||
/agent-note-writer-acquisition-for-blank-session-reuse/consequences:
|
||||
en: 2e1f1894337689a2
|
||||
zh: d0cab07cc48083ee
|
||||
en: 8307612b7476e8f3
|
||||
zh: 87fa39e58d33d4f1
|
||||
/agent-note-writer-acquisition-for-blank-session-reuse/verification:
|
||||
en: 4680e845e2ab294e
|
||||
zh: ea5890c5ffb09831
|
||||
en: 4367d55ae9dce5c1
|
||||
zh: c610626f4e15eb77
|
||||
@@ -10,7 +10,7 @@ Two Hosts sharing Session storage can select the same blank Session when opening
|
||||
|
||||
## Decision
|
||||
|
||||
The Session catalog includes persisted blanks. Startup restoration selects the saved blank; ordinary Workspace navigation selects the first eligible unarchived member in catalog order. Explicit-id `session.create` resumes that Session and acquires its writer before opening history. Only `session/writer-held` triggers creation of a new Session. Other errors propagate. Concurrent Workspace connects in one Client share the acquisition and fallback. Later navigation cancels a pending startup selection.
|
||||
The Session catalog includes persisted blanks. Startup restoration selects the saved blank; ordinary Workspace navigation selects the first eligible unarchived member in catalog order. Explicit-id `session.create` names that Session; the Host resumes it and acquires its writer before opening history, and creates a new Session when another owner holds the writer ([reuse and preset rules](../bug-fix/2026-09-29-reused-blank-runs-requested-preset.md)). Other errors propagate. A Workspace connect in one Client joins the latest in-flight connect to that Workspace only when both request the same preset. Later navigation cancels a pending startup selection.
|
||||
|
||||
The Agent retains the acquired handle throughout its lifetime. Checking ownership and releasing a probe lock would leave a race before resume. No PID or process identity enters persisted data or the Remote schema.
|
||||
|
||||
@@ -28,8 +28,8 @@ This decision extends the blank-reuse policy in the [Client Session scope refere
|
||||
|
||||
## Consequences
|
||||
|
||||
A Host can reuse its own live blank or reclaim an unowned persisted blank with its slash state. Separate Hosts create distinct blanks while existing writers remain held. A held selected blank causes fresh creation even when another blank is free; navigation does not search for another candidate. No cleanup is added. Opening the same established conversation from two Hosts can still encounter writer contention. Unknown projection hints remain visible without cold body scans; automatic reuse requires known blank metadata. A non-contention acquisition failure aborts New Session and is currently reported only to the console; hidden blanks have no recovery action in this flow.
|
||||
A Host can reuse its own live blank or reclaim an unowned persisted blank with its slash state. Separate Hosts create distinct blanks while existing writers remain held. A held selected blank causes fresh creation even when another blank is free; navigation does not search for another candidate. No cleanup is added. Opening the same established conversation from two Hosts can still encounter writer contention. Unknown projection hints remain visible without cold body scans; automatic reuse requires known blank metadata. A non-contention acquisition failure aborts the navigation; a hero Workspace pick or explicit draft preparation reports it as a notice and startup restoration only to the console, and a hidden blank that fails this way has no recovery action in this flow.
|
||||
|
||||
## Verification
|
||||
|
||||
Navigation tests cover saved selection, single-candidate contention fallback, non-contention failures, overlapping acquisition, and superseding navigation. A shipped Web-composition test holds a real persistence writer, verifies fresh creation despite another free blank, and reclaims the released selected blank with its plan state. The fresh-round-trip recorded Session scenario reloads its blank before submitting the recorded prompt.
|
||||
Navigation tests cover saved selection, opening the Session the Host returns for a held candidate, non-contention failures, overlapping acquisition, and superseding navigation. A shipped Web-composition test holds a real persistence writer, verifies fresh creation despite another free blank, and reclaims the released selected blank with its plan state. The fresh-round-trip recorded Session scenario reloads its blank before submitting the recorded prompt.
|
||||
+3
-3
@@ -10,7 +10,7 @@ Status: implemented
|
||||
|
||||
## Decision
|
||||
|
||||
Session 列表包含持久化空白会话。启动恢复选择已保存的空白会话;普通 Workspace 导航按列表顺序选择第一个符合条件且未归档的成员。显式 ID 的 `session.create` 会恢复该 Session,并在打开历史前取得写锁。只有 `session/writer-held` 会触发新建 Session。其他错误返回调用方。同一 Client 的并发 Workspace 连接共享获取与回退过程。后续导航会取消尚未完成的启动选择。
|
||||
Session 列表包含持久化空白会话。启动恢复选择已保存的空白会话;普通 Workspace 导航按列表顺序选择第一个符合条件且未归档的成员。显式 ID 的 `session.create` 指明该 Session;Host 恢复它并在打开历史前取得写锁,写锁被其他写者持有时改为新建 Session([复用与 preset 规则](../bug-fix/2026-09-29-reused-blank-runs-requested-preset.zh.md))。其他错误返回调用方。同一 Client 中的 Workspace 连接仅在与该 Workspace 最近一次进行中的连接请求相同 preset 时与之合并。后续导航会取消尚未完成的启动选择。
|
||||
|
||||
Agent 在整个生命周期内持有取得的句柄。检查占用后释放探测锁,会在恢复前留下竞态。持久化数据与 Remote schema 均不引入 PID 或进程身份。
|
||||
|
||||
@@ -28,8 +28,8 @@ Agent 在整个生命周期内持有取得的句柄。检查占用后释放探
|
||||
|
||||
## Consequences
|
||||
|
||||
Host 可以复用自己的活动空白会话,也可以接管无人占用的持久化空白会话并保留其 slash 状态。现有写锁被持有时,不同 Host 创建不同的空白会话。所选空白会话被占用时,即使另有空闲空白会话也会新建;导航不再寻找其他候选。不增加清理逻辑。两个 Host 打开同一个已有对话时仍可能遇到写锁争用。未知投影提示仍可见且不扫描冷日志正文;自动复用要求已知的空白元数据。非锁争用的获取错误会中止新建会话,目前只报告到控制台;此流程没有针对隐藏空白会话的恢复操作。
|
||||
Host 可以复用自己的活动空白会话,也可以接管无人占用的持久化空白会话并保留其 slash 状态。现有写锁被持有时,不同 Host 创建不同的空白会话。所选空白会话被占用时,即使另有空闲空白会话也会新建;导航不再寻找其他候选。不增加清理逻辑。两个 Host 打开同一个已有对话时仍可能遇到写锁争用。未知投影提示仍可见且不扫描冷日志正文;自动复用要求已知的空白元数据。非锁争用的获取错误会中止该次导航;在 hero 中选择工作区或显式准备草稿时以提示展示该错误,启动恢复只报告到控制台,以此方式失败的隐藏空白会话在此流程中没有恢复操作。
|
||||
|
||||
## Verification
|
||||
|
||||
导航测试覆盖已保存选择、单候选锁争用回退、其他错误、重叠获取以及后续导航替代。实际 Web 组合测试持有真实持久化写锁,验证另有空闲空白会话时仍新建,并接管已释放的所选空白会话及其 plan 状态。fresh-round-trip 的录制 Session 场景在提交已录制的提示词前刷新空白会话。
|
||||
导航测试覆盖已保存选择、为被占用候选打开 Host 返回的 Session、其他错误、重叠获取以及后续导航替代。实际 Web 组合测试持有真实持久化写锁,验证另有空闲空白会话时仍新建,并接管已释放的所选空白会话及其 plan 状态。fresh-round-trip 的录制 Session 场景在提交已录制的提示词前刷新空白会话。
|
||||
+2
-2
@@ -9,8 +9,8 @@
|
||||
en: 725f773bb350218e
|
||||
zh: dd8fbc09ef48208d
|
||||
/agent-note-declarative-agent-presets-and-retained-revisions/decision:
|
||||
en: 53fd72bf4bbe4eb3
|
||||
zh: 406eee6e4f818e7c
|
||||
en: 88edb925b556300c
|
||||
zh: c6f05b641513d768
|
||||
/agent-note-declarative-agent-presets-and-retained-revisions/alternatives-considered:
|
||||
en: 09f40eab4659e9f6
|
||||
zh: 7a70da0d0ae6845b
|
||||
|
||||
@@ -16,7 +16,7 @@ The registry owns each revision's scope and Loader tree. Agents link their own s
|
||||
|
||||
The Web editor and `agent_preset` tool accept only child plugin YAML. Saving writes the active profile's user patch, preserving display metadata and unrelated configuration. Revision checks and profile locking prevent overwriting concurrent saves; validation rejects a higher-priority override that would defeat the edit. Persistence and activation outcomes are reported separately. Tool writes require approval or full access because configuration executes in the Host.
|
||||
|
||||
Session data continues to record the preset identity. Restart resolves that identity against current configuration and rejects a missing definition. Old executable revisions are process-local, not serialized. New sessions without an explicit preset resolve `selectedDefault`; Client choice filtering and default correction follow [the preset UI policy](../../../../packages/client/ui-agent-preset/README.md).
|
||||
Session data continues to record the preset identity. Restart resolves that identity against current configuration and rejects a missing definition; reusing a blank Session for a new conversation does not resolve it ([decision](../bug-fix/2026-09-29-reused-blank-runs-requested-preset.md)). Old executable revisions are process-local, not serialized. New sessions without an explicit preset resolve `selectedDefault`; Client choice filtering and default correction follow [the preset UI policy](../../../../packages/client/ui-agent-preset/README.md).
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ Preset 目录重复承担 Cordis 配置的所有权。独立的发现、元数
|
||||
|
||||
Web 编辑器与 `agent_preset` 工具只接受子插件 YAML。保存写入当前 profile 的用户补丁,保留显示元数据和无关配置。版本检查和 profile 锁防止覆盖并发保存;验证拒绝会使编辑失效的更高优先级覆盖。持久化与激活结果分别报告。配置在 Host 中执行,因此工具写入需要批准或完全访问权限。
|
||||
|
||||
会话数据继续记录 preset 标识。重启时根据当前配置解析该标识,定义缺失则拒绝恢复。旧的可执行代际仅保留在进程内,不会序列化。未显式指定 preset 的新会话解析 `selectedDefault`;客户端选项过滤和默认值修正遵循[预设 UI 策略](../../../../packages/client/ui-agent-preset/README.zh.md)。
|
||||
会话数据继续记录 preset 标识。重启时根据当前配置解析该标识,定义缺失则拒绝恢复;为新对话复用空白会话时不解析该标识([决策](../bug-fix/2026-09-29-reused-blank-runs-requested-preset.zh.md))。旧的可执行代际仅保留在进程内,不会序列化。未显式指定 preset 的新会话解析 `selectedDefault`;客户端选项过滤和默认值修正遵循[预设 UI 策略](../../../../packages/client/ui-agent-preset/README.zh.md)。
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
# Bilingual-pair consistency record for 2026-10-11-chat-group-tree-exchanges.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/architecture/2026-10-11-chat-group-tree-exchanges.md
|
||||
/agent-note-chat-group-tree-positions-and-exchanges:
|
||||
en: b26212eda152d6c6
|
||||
zh: a801a75ee0c07911
|
||||
/agent-note-chat-group-tree-positions-and-exchanges/problem:
|
||||
en: 84858bc0e1e268ab
|
||||
zh: 39ebb2979968d6cc
|
||||
/agent-note-chat-group-tree-positions-and-exchanges/decision:
|
||||
en: c8c4091863dec269
|
||||
zh: 57a0f26683867350
|
||||
/agent-note-chat-group-tree-positions-and-exchanges/why-mark-the-opening-rather-than-the-notice:
|
||||
en: db8d77cd773ad646
|
||||
zh: ab2f03b8fc58e952
|
||||
/agent-note-chat-group-tree-positions-and-exchanges/alternatives-considered:
|
||||
en: 635ddcb04fefe8e2
|
||||
zh: 360c171ccb613ed5
|
||||
/agent-note-chat-group-tree-positions-and-exchanges/consequences:
|
||||
en: c8cfdc3009b19b12
|
||||
zh: 36c541cd9692057d
|
||||
/agent-note-chat-group-tree-positions-and-exchanges/testing:
|
||||
en: 0d7f5281e66b0c39
|
||||
zh: 5be221de46e9e0f7
|
||||
@@ -0,0 +1,51 @@
|
||||
# Agent Note: Chat group-tree positions and exchanges
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-10-11-chat-group-tree-exchanges.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
On next message folding kept only the last Turn of the loaded timeline expanded. A Turn woken by a notice (a settled subagent, goal round, schedule, or background job) is not submitted by this Client, yet its arrival made the preceding Turn historical and folded it. No own-input driver computed the exact remaining room for that fold, so the scroll layer reserved generic bottom space and a reader following the tail saw blank space. In the recorded Session the notice woke the next Turn 13–15 ms after the previous Turn ended; the minimal reproduction left 596 px blank that had not recovered after five seconds.
|
||||
|
||||
## Decision
|
||||
|
||||
A notice is neither body text nor a user message: folding and bottom advancement ignore it. The bottom changes from the last Turn to the latest exchange.
|
||||
|
||||
- **Group-tree positions.** `ChatConversationViewNode.groupTree` declares a Node's position in the group tree, typed `ChatGroupTree = 'exchange' | 'turn' | 'process'` and ordered outermost first; a Node at a position also stands outside every inner grouping. `isAtOrOutside(node, position)` is the single reader of that order. Only `exchange` is read today; `turn` and `process` are reserved for migrating the `TURN_PROCESS_INDEPENDENT_KINDS` and process-group `INDEPENDENT` kind lists later without changing what `exchange` means.
|
||||
- **Exchanges.** A Turn holding an `exchange` Node opens an exchange, which lasts until the next opening Turn. The business message Definition marks only human input claimed in Step 1 (`user` or `steering`) as `exchange`; notices and later steering carry no position.
|
||||
- **Mechanism.** `GroupTreeSegments(position)` splits the loaded Turns at the Turns holding a Node at that position. The latest segment starts at the last opening Turn, or at the first loaded Turn when the window holds none. It counts per Turn incrementally without scanning loaded Nodes, and a start move returns only the Turns that entered or left the latest segment. The Chat Builder's `bottomSource` is "the Node is visible and belongs to the latest exchange".
|
||||
|
||||
As a result, a notice-woken Turn no longer folds earlier Turns, so no room is reserved; the human's next ordinary message folds the whole exchange through the own-input path.
|
||||
|
||||
## Why mark the opening rather than the notice
|
||||
|
||||
The host claims the waking input right after `turn/start`, assembles the system prompt, and only then logs `step/start` and `user/message`; the recorded Session spent 187 ms in that gap. Marking only the notice leaves the new Turn untagged during the gap, so the bottom still advances and the previous Turn folds and then reopens. Marking the human opening and letting unmarked Turns continue the exchange keeps the gap inert.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**Tag the notice as a continuation.** The 187 ms gap above makes it fold and reopen, and a claim that mixes a notice with human input needs extra classification.
|
||||
|
||||
**Name opening kinds in a list (`user`, `steering`).** A kind cannot separate Step 1 steering from mid-Turn steering, so a human steering into a notice-woken Turn would wrongly fold the previous exchange.
|
||||
|
||||
**Publish Turn-level Location data.** Only one Context may publish a key for a Turn, while opening input comes from several message Contexts; aggregating per Turn would repeat the inbox claim classification in a new Definition and read every Turn on each update.
|
||||
|
||||
**Declare a business role (`input`, `notice`) on Nodes.** That places business semantics in the grouping mechanism; group-tree positions describe structure only, and each business Definition chooses its position.
|
||||
|
||||
**Correct the scroll room for folds not caused by own input.** Notices should not fold at all, and correcting the room would not remove that unnecessary fold; it remains a residual issue for human input from another tab.
|
||||
|
||||
**Migrate both kind lists now.** That reaches well beyond this defect; the type reserves the positions and the migration is separate work.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Notice-woken Turns no longer cause a fold, reserved room, or blank space, and the grouping mechanism reads declared positions instead of naming kinds.
|
||||
- Under On next message, a long run of notice-woken Turns (up to 31 goal-mode Turns in sampled Sessions) stays expanded until the human types again.
|
||||
- When the loaded window holds no opening Turn, every loaded Turn belongs to the latest exchange.
|
||||
- Human input from another tab folds when its `user/message` arrives, about 200 ms later than the former `turn/start` fold; that fold still uses generic room and is unchanged here.
|
||||
|
||||
## Testing
|
||||
|
||||
- `packages/client/ui-chat/tests/group-tree-segments.client.spec.ts`: position order, segmentation, count fallback, and the empty window.
|
||||
- `packages/client/ui-chat/tests/chat-node-bottom.client.spec.ts`: latest-exchange membership and notification scope.
|
||||
- `packages/client/ui-chat/tests/conversation-node-definitions.client.spec.ts`: a real assembler across an opening Turn, mid-Turn steering, the pre-Step gap, a notice wake, and an idle steer.
|
||||
- `apps/web/tests/notice-wake-tail.e2e.ts`: after a long Turn a notice wakes the next Turn; the long Turn stays expanded through the pre-Step gap and after the notice reply, and a following reader sees the notice and the reply.
|
||||
@@ -0,0 +1,51 @@
|
||||
# Agent Note: Chat 分组树位置与交互段
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-10-11-chat-group-tree-exchanges.md) | 中文
|
||||
|
||||
## Problem
|
||||
|
||||
「下次发送时收起」原本只让已加载时间线的最后一个 Turn 保持展开。由通知唤醒的 Turn(子 agent 完成、Goal Round、定时任务、后台作业)不是本客户端提交的,它一出现,上一轮就被当作历史折叠。这次折叠没有自己输入的驱动来计算精确的剩余补白,滚动层只能按通用规则预留底部空间,正在跟尾的读者因此看到一片空白。录制的真实 Session 中,通知在上一轮结束后 13–15 ms 唤醒新轮次;最小复现里空白高 596 px,五秒后仍未恢复。
|
||||
|
||||
## Decision
|
||||
|
||||
通知不算正文,也不算用户消息:折叠和推进底部时都忽略它。底部从"最后一个 Turn"改为"最新交互段"。
|
||||
|
||||
- **分组树位置。** `ChatConversationViewNode.groupTree` 声明节点在分组树中的位置,类型为 `ChatGroupTree = 'exchange' | 'turn' | 'process'`,由外到内有序;站在某个位置的节点同时也站在所有内层分组之外。`isAtOrOutside(node, position)` 是读取这一顺序的唯一入口。目前只读取 `exchange`;`turn` 和 `process` 预留给以后把 `TURN_PROCESS_INDEPENDENT_KINDS` 与过程组 `INDEPENDENT` 两份 kind 名单迁移过来,届时不改变 `exchange` 的含义。
|
||||
- **交互段。** 含 `exchange` 节点的 Turn 开启一个交互段,交互段持续到下一个开启 Turn。业务层的 message Definition 只给 Step 1 中被认领的真人输入(`user` 或 `steering`)标 `exchange`;通知和之后的 steering 不标。
|
||||
- **机制。** `GroupTreeSegments(position)` 按含该位置节点的 Turn 切分已加载的 Turn,最新一段从最后一个开启 Turn 开始,窗口中没有开启 Turn 时从第一个已加载 Turn 开始。它按 Turn 增量计数,不扫描已加载节点;起点移动时只返回进入或离开最新一段的 Turn。Chat Builder 的 `bottomSource` 为"节点可见且属于最新交互段"。
|
||||
|
||||
结果是:通知唤醒的 Turn 不再折叠前面的 Turn,没有折叠就没有补白;真人下一次普通输入时,整个交互段经由自己输入的路径一起折叠。
|
||||
|
||||
## 为什么标开头而不是标通知
|
||||
|
||||
Host 在 `turn/start` 之后立即认领唤醒输入,然后组装系统提示,再写 `step/start` 和 `user/message`。录制的 Session 中这段间隔为 187 ms。只给通知打标的话,这段时间新 Turn 还没有标签,底部照样推进,上一轮会先折叠再展开。把标签放在真人开头上、未标的 Turn 默认续接,空白间隔里什么都不会发生。
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**给通知打"续接"标签。** 上面那 187 ms 的间隔会让它先折后展;同一次认领里通知和真人输入并存时还要额外判断。
|
||||
|
||||
**按 kind 写一张开启名单(`user`、`steering`)。** kind 区分不了 Step 1 的 steering 与 Turn 中途的 steering,真人往通知唤醒的 Turn 里插话时会错误地折叠前一个交互段。
|
||||
|
||||
**发布到 Turn 级 Location data。** 同一 Turn 的同一个 key 只允许一个 Context 发布,而开启输入来自多个消息 Context;改成按 Turn 汇总就得在新的 Definition 里重复 inbox 认领分类,并且每次都要读取所有 Turn。
|
||||
|
||||
**节点声明业务角色(`input`、`notice`)。** 这会把业务语义放进分组机制;分组树位置只描述结构,业务 Definition 自行决定位置。
|
||||
|
||||
**修正非自身输入折叠时的滚动补白。** 通知本来就不应触发折叠,修补白不能消除这次不必要的折叠;它仍是另一个标签页里真人输入的残留问题。
|
||||
|
||||
**这次就迁移两份 kind 名单。** 改动面明显超出这次缺陷;类型先预留位置,迁移另做。
|
||||
|
||||
## Consequences
|
||||
|
||||
- 通知唤醒的 Turn 不再产生折叠、补白和空白;分组机制读取节点声明的位置,而不是点名 kind。
|
||||
- 「下次发送时收起」下,一长串通知唤醒的 Turn(抽样会话中 Goal 模式最长 31 轮)会一直展开,直到真人再次输入。
|
||||
- 已加载窗口里没有开启 Turn 时,所有已加载 Turn 都属于最新交互段。
|
||||
- 另一个标签页里的真人输入在它的 `user/message` 到达时才折叠,比原来在 `turn/start` 时晚约 200 ms;这类折叠仍使用通用补白,本次没有修改。
|
||||
|
||||
## Testing
|
||||
|
||||
- `packages/client/ui-chat/tests/group-tree-segments.client.spec.ts`:位置顺序、切分、计数回退与空窗口。
|
||||
- `packages/client/ui-chat/tests/chat-node-bottom.client.spec.ts`:最新交互段的成员与通知范围。
|
||||
- `packages/client/ui-chat/tests/conversation-node-definitions.client.spec.ts`:真实 assembler 下的开轮、中途 steering、Step 1 前的间隔、通知唤醒与空闲 steer。
|
||||
- `apps/web/tests/notice-wake-tail.e2e.ts`:长 Turn 之后由通知唤醒,在 Step 1 前的间隔和通知回复之后,上一轮都保持展开,跟尾读者看到通知与回复。
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
# Bilingual-pair consistency record for 2026-09-29-reused-blank-runs-requested-preset.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/bug-fix/2026-09-29-reused-blank-runs-requested-preset.md
|
||||
/agent-note-a-reused-blank-session-runs-the-requested-preset:
|
||||
en: 06173bc82e1d9f59
|
||||
zh: 637352fd92142310
|
||||
/agent-note-a-reused-blank-session-runs-the-requested-preset/problem:
|
||||
en: 7514025504dc2ddd
|
||||
zh: 96249d3472005023
|
||||
/agent-note-a-reused-blank-session-runs-the-requested-preset/decision:
|
||||
en: e396c291f742a5f3
|
||||
zh: c67be0fd305215fe
|
||||
/agent-note-a-reused-blank-session-runs-the-requested-preset/alternatives-considered:
|
||||
en: ae99345e8df800e4
|
||||
zh: a4d0c257c4216337
|
||||
/agent-note-a-reused-blank-session-runs-the-requested-preset/consequences:
|
||||
en: bc7dda06670b4d96
|
||||
zh: 24f381b8cb6ed3f8
|
||||
/agent-note-a-reused-blank-session-runs-the-requested-preset/testing:
|
||||
en: 1aefca569f5dce81
|
||||
zh: 527c9aacf5a2f6b8
|
||||
@@ -0,0 +1,37 @@
|
||||
# Agent Note: A reused blank Session runs the requested preset
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-09-29-reused-blank-runs-requested-preset.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
Web New Session, Workspace navigation, and startup restoration reused a blank Session by naming it in `session.create`. The Host resumed that Session under the preset its log recorded, so a new conversation inherited the preset the blank had been created or switched under. When that preset was no longer declared, such as a removed or renamed definition or a legacy `$DSH_HOME/.agent-presets/<id>/` directory that nothing reads any more, every New Session in that Workspace and every startup restoration of that draft failed with `agent-preset/not-found` although the default preset was valid (issue #2566). A blank created under an earlier default silently kept that default. The client retried only `session/writer-held`, so the stale blank stayed first in line.
|
||||
|
||||
## Decision
|
||||
|
||||
`session.create` returns a Session for a new conversation. A named `sessionId` is a reuse candidate that the Host verifies: it must not have started a turn, must belong to the requested directory, must be an unarchived member of the requested Workspace, and must not be written by another owner. For a persisted candidate the Host repeats the started check under the writer it acquires. Requests naming one identity run in arrival order, including their preset resolution, and the directory and ownership checks precede that resolution. The reused Session runs the requested `agentPreset`, or the configured default when the request names none; the Host does not resolve the recorded preset for reuse. When the target differs, a live Session switches through the preset registry's `select`, and a persisted Session mounts the target in its unpublished resume setup and appends `agent-preset/selected` there, so the log names the composition before the Agent is published. A candidate that has started, fails placement, or is written by another owner stays unchanged, and the Host creates a new Session; the response names the Session used. An explicit request for an undeclared preset still fails with `agent-preset/not-found`, and resuming a started Session still resolves its recorded identity.
|
||||
|
||||
The Web client names the first eligible blank when it connects a Workspace or prepares an explicit draft, and passes the preset a flow knows before it starts, such as the creator entry's `cordis`; a plain New Session creates a fresh Session instead. Startup restoration names the saved blank with the preset its log recorded, reloading the Session's projections first because listed values are cached hints that can lag the log after an unclean Host exit, so a draft keeps its selection; after `agent-preset/not-found` or `agent-preset/invalid` it asks again without a preset, and the draft continues under the default. When the Host declines a named blank, the client reloads that Session's projections, because stale cached list metadata can still mark a started conversation blank and hide it from the Session tree.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**Fall back to the default only when the recorded preset is missing.** This removes the failure but keeps an inherited preset whenever it still resolves, so a New Session after a default change runs the old default.
|
||||
|
||||
**Retry `agent-preset/not-found` in the client.** The stale blank stays the first reuse candidate, so later New Sessions fail once before creating another Session, and startup restoration and other callers still fail.
|
||||
|
||||
**Skip blanks whose preset is missing from the roster.** Navigation would need the roster, stale Sessions would never be repaired, and other callers would still fail.
|
||||
|
||||
**Let the Host choose the blank.** The Host would scan the catalog on every request, while the client already holds the ordered catalog; verification under the writer covers a stale client view.
|
||||
|
||||
**Keep a restored draft's preset on the Host when it resolves.** A request that names a blank without a preset would then mean "keep" for restoration and "default" for New Session. Passing the recorded preset gives each request one meaning.
|
||||
|
||||
## Consequences
|
||||
|
||||
A reused blank runs the default or the preset its flow names, including after the default changes or a definition disappears. A preset picked on a draft survives a page reload but not a later Workspace connection or draft preparation that reuses the draft, and reusing a draft that another tab shows changes that tab's preset too. Writer contention no longer reaches the client: the Host creates the replacement Session. A blank whose first prompt was accepted but whose turn has not started still counts as blank, as it does for `select`. A declined stale blank is corrected only in the client that named it, until the Session is next activated. The preset registry's `select` leaves a blank Session that records the requested preset and runs its current revision unchanged, so a client that also selects that preset after the creation request adds no second record.
|
||||
|
||||
This note replaces the client-side contention fallback of [Writer acquisition for blank Session reuse](../architecture/2026-09-17-process-local-blank-sessions.md); writer acquisition and candidate order remain as decided there.
|
||||
|
||||
## Testing
|
||||
|
||||
Session Controller tests cover live and persisted reuse, a recorded preset that is no longer declared, named presets, started and overtaken Sessions, writer contention, Workspace placement, storage failures, arrival order when an earlier preset resolves later, and directory checks before preset resolution. Workspace navigation tests cover restoration with and without a usable recorded preset, restoration when the listed preset lags the log, connection coalescing that a different preset request supersedes, and the projection reload for a declined blank; the preset plugin tests cover the creator entry, and the registry tests cover a repeated selection with and without a replaced definition. The shipped Web composition test reuses a blank recorded under an undeclared preset under the default when startup connects its Workspace and when startup restores it, keeps a restored draft's declared preset, and checks the durable `agent-preset/selected` record; the stale blank cache scenario checks that startup opens a new Session and still lists the declined conversation.
|
||||
@@ -0,0 +1,37 @@
|
||||
# Agent Note: 被复用的空白会话运行请求的 preset
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-09-29-reused-blank-runs-requested-preset.md) | 中文
|
||||
|
||||
## Problem
|
||||
|
||||
Web 的新建会话、工作区导航与启动恢复过去通过在 `session.create` 中指明空白会话来复用它。Host 过去按日志记录的 preset 恢复该会话,因此新对话继承了空白会话创建时或切换后的 preset。当该 preset 已不再声明时,例如定义被删除或改名,或是如今已无人读取的旧版 `$DSH_HOME/.agent-presets/<id>/` 目录,即使默认 preset 有效,该工作区中的每次新建会话以及该草稿的每次启动恢复都会以 `agent-preset/not-found` 失败(issue #2566)。在更早默认值下创建的空白会话则会静默保留那个旧默认值。客户端只对 `session/writer-held` 重试,因此过期的空白会话始终排在复用候选首位。
|
||||
|
||||
## Decision
|
||||
|
||||
`session.create` 返回一个用于新对话的会话。请求指明的 `sessionId` 是由 Host 核实的复用候选:它必须尚未开始任何轮次、属于请求的目录、是请求的工作区中未归档的成员,且未被其他写者占用。对于持久化候选,Host 会在取得写锁后再次检查它是否已开始。指明同一标识的请求按到达顺序执行,preset 解析也包含在内,且目录与归属检查先于该解析。被复用的会话运行请求的 `agentPreset`,请求未指明时运行配置的默认 preset;Host 复用时不解析记录的 preset。目标与当前不同时,活动会话通过 preset 注册表的 `select` 切换;持久化会话在尚未发布的恢复 setup 中挂载目标 preset,并在同一处追加 `agent-preset/selected`,使日志在 Agent 发布前就写明其组成。已开始、不满足归属或被其他写者占用的候选保持不变,Host 改为新建会话;响应指明实际使用的会话。显式请求未声明的 preset 仍以 `agent-preset/not-found` 失败,恢复已开始的会话仍解析其记录的标识。
|
||||
|
||||
Web 客户端在连接工作区或显式准备草稿时指明第一个符合条件的空白会话,并传入流程在开始前已确定的 preset,例如创造模式入口的 `cordis`;普通新建会话则直接新建 Session。启动恢复指明已保存的空白会话及其日志记录的 preset,并先重新加载该会话的投影,因为列表中的值是缓存提示,Host 非正常退出后可能落后于日志,从而使草稿保留其选择;遇到 `agent-preset/not-found` 或 `agent-preset/invalid` 后改为不带 preset 再请求一次,草稿在默认 preset 下继续。Host 拒绝复用某个指明的空白会话时,客户端会重新读取该会话的投影,因为过期的列表缓存元数据可能仍把已开始的对话标为空白,并把它从会话树中隐藏。
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**只在记录的 preset 缺失时回退到默认值。** 这能消除失败,但只要继承的 preset 仍可解析就会保留它,因此默认值变更后的新建会话仍运行旧默认值。
|
||||
|
||||
**在客户端重试 `agent-preset/not-found`。** 过期的空白会话仍是第一个复用候选,之后每次新建会话都会先失败一次再新建,启动恢复和其他调用方仍会失败。
|
||||
|
||||
**跳过 preset 不在列表中的空白会话。** 导航需要读取 preset 列表,过期会话永远得不到修复,其他调用方仍会失败。
|
||||
|
||||
**由 Host 选择空白会话。** Host 每次请求都要扫描会话列表,而客户端已持有排好序的列表;在写锁下的核实足以覆盖客户端视图过期的情况。
|
||||
|
||||
**恢复草稿时由 Host 在记录的 preset 可解析时保留它。** 这样一个指明空白会话但未带 preset 的请求,在恢复时表示「保留」,在新建会话时表示「默认」。传入记录的 preset 让每个请求只有一种含义。
|
||||
|
||||
## Consequences
|
||||
|
||||
被复用的空白会话运行默认 preset 或其流程指明的 preset,默认值变更或定义消失之后也是如此。在草稿上选择的 preset 在刷新页面后仍保留,但之后复用该草稿的工作区连接或草稿准备不会保留它;复用另一个标签页正在显示的草稿也会改变那个标签页的 preset。写锁争用不再到达客户端:由 Host 新建替代会话。首条提示词已被接受但轮次尚未开始的空白会话仍算空白,与 `select` 一致。被拒绝复用的过期空白会话只在指明它的客户端中得到纠正,直到该会话下次被激活。若空白会话已记录所请求的 preset 且正运行其当前版本,preset 注册表的 `select` 不做改动,因此客户端在创建请求之后再选择同一 preset 也不会追加第二条记录。
|
||||
|
||||
本注记取代 [复用空白 Session 时获取写锁](../architecture/2026-09-17-process-local-blank-sessions.zh.md) 中的客户端锁争用回退;写锁获取与候选顺序仍按该决策执行。
|
||||
|
||||
## Testing
|
||||
|
||||
Session Controller 测试覆盖活动会话与持久化会话的复用、记录的 preset 已不再声明、指明的 preset、已开始与被抢先开始的会话、写锁争用、工作区归属、存储失败、较早请求的 preset 解析较慢时仍按到达顺序执行,以及目录检查先于 preset 解析。工作区导航测试覆盖记录的 preset 可用与不可用时的恢复、列表中的 preset 落后于日志时的恢复、被不同 preset 请求取代的连接不再合并,以及被拒绝的空白会话的投影重读;preset 插件测试覆盖创造模式入口,注册表测试覆盖定义未替换与已替换时的重复选择。实际 Web 组合测试在启动连接工作区与启动恢复时,把记录了未声明 preset 的空白会话复用到默认 preset 下,验证恢复的草稿保留已声明的 preset,并检查持久化的 `agent-preset/selected` 记录;过期空白缓存场景验证启动时打开新会话,并仍列出被拒绝复用的对话。
|
||||
+6
-6
@@ -9,14 +9,14 @@
|
||||
en: e6929494e60041a2
|
||||
zh: 15bec8e8baabcab2
|
||||
/agent-note-generated-third-party-notices/decision:
|
||||
en: 11f3362b0f45debb
|
||||
zh: 5953b0848b940b67
|
||||
en: e0a339aa86f13898
|
||||
zh: 9ab0c7de7bb185b5
|
||||
/agent-note-generated-third-party-notices/testing:
|
||||
en: 194f87f780991068
|
||||
zh: 58096d2339576d20
|
||||
/agent-note-generated-third-party-notices/alternatives-considered:
|
||||
en: 093ddc027e296bf0
|
||||
zh: 6b9e64d99dcefa11
|
||||
en: 7e9d8d7864503e46
|
||||
zh: 5b93a1130cfab260
|
||||
/agent-note-generated-third-party-notices/consequences:
|
||||
en: 860b806c5d393c98
|
||||
zh: 51b4ca11e2d3802a
|
||||
en: ed2210ac6c133e6c
|
||||
zh: 7957cb33da842642
|
||||
@@ -14,9 +14,7 @@ A hand-written inventory answers none of those durably. Roughly a hundred rows o
|
||||
|
||||
[`THIRD_PARTY_NOTICES.md`](../../../../THIRD_PARTY_NOTICES.md) is generated by [`scripts/gen-third-party-notices.ts`](../../../../scripts/gen-third-party-notices.ts) from the workspace manifests, `vendor/README.md`, the `pyproject.toml` files, `pnpm-workspace.yaml`, and the [shared runtime lock](../../../../scripts/primary-runtime/lock.json). The root README pair links the file from its License section.
|
||||
|
||||
**Freshness is maintained, not merely enforced.** A pre-commit job regenerates the file and stages it whenever a generator input is staged — any manifest, a workspace declaration, the root or shared runtime lock file, `vendor/README.md`, a `pyproject.toml`, the generator itself, or the script holding the build-time pin — so an unrelated dependency edit never has to come back and rerun a generator. The committed bytes are then asserted inside [`scripts/gen-third-party-notices.spec.ts`](../../../../scripts/gen-third-party-notices.spec.ts), which the test lane already runs — the check adds no gate process, no scheduler slot, and no separate CI step. `pnpm run verify-third-party-notices` remains available for a standalone check.
|
||||
|
||||
One trigger gap is accepted rather than worked around: lefthook inspects only files present on disk, so **deleting** a manifest runs no job, and removing a package reaches the assertion in the test lane instead. Reconstructing the staged file list to include deletions does not work — lefthook filters the list against the working tree either way. The assertion is the backstop for exactly this case.
|
||||
**The test lane enforces freshness.** The committed bytes are asserted inside [`scripts/gen-third-party-notices.spec.ts`](../../../../scripts/gen-third-party-notices.spec.ts), which the test lane already runs, including the required `node 24 / coverage` pull-request lane — the check adds no gate process, no scheduler slot, and no separate CI step. A contributor who changes a generator input — any manifest, a workspace declaration, the root or shared runtime lock file, `vendor/README.md`, a `pyproject.toml`, the generator itself, or the script holding the build-time pin — runs `pnpm run gen-third-party-notices`; `pnpm run verify-third-party-notices` remains available for a standalone check. No Git hook regenerates the file: browser inputs make every package source file a generator input, so a hook would run the 16-second generator on nearly every commit, while few commits change the output.
|
||||
|
||||
The file discloses **direct** dependencies by default; complete npm and Python SDK closures remain in their lock files. Two separately distributed payload sets receive explicit entries: the official Claude executable packages declared by `@anthropic-ai/claude-agent-sdk`, and every distribution in the shared runtime lock's `pythonPackages`. Bundled entries include normalized names, exact versions, and recorded license metadata; missing metadata, duplicate normalized names and conflicting normalized versions fail generation. The shared wheel set is independent of the `python/` manifests, so scanning only those manifests would omit the packaged Office libraries. Bundled distributions also pass the runtime license check, including the permissive `MIT-CMU` and `PSF-2.0` identifiers declared by Pillow and typing-extensions.
|
||||
|
||||
@@ -38,7 +36,7 @@ The Claude distribution tests prove that only the exact direct SDK identity bypa
|
||||
|
||||
**Keep the hand-written file and review it at release time.** Reviewing a hundred derived rows by eye is exactly the work a generator does correctly, and the file's own claim — that it lists every direct dependency — would be unverified between releases.
|
||||
|
||||
**Verify through a dedicated `doc-sync` gate.** That is how every other generated artifact here is checked, and it was the first shape of this change. It costs a gate process and a scheduler slot in a matrix that is already long, and — worse — its only failure mode is telling a contributor, minutes after they pushed an unrelated dependency bump, to go rerun a generator. Regenerating at commit time removes the interruption, and the assertion inside a spec the test lane already runs keeps the guarantee at no additional CI cost.
|
||||
**Verify through a dedicated `doc-sync` gate.** That is how every other generated artifact here is checked, and it was the first shape of this change. It costs a gate process and a scheduler slot in a matrix that is already long, while the assertion inside a spec the test lane already runs reports the same staleness at no additional CI cost.
|
||||
|
||||
**Enumerate the full transitive closure.** The closure is thousands of packages, already recorded in the lock files with exact versions, and would bury the direct dependencies that a reader actually evaluates. The file points at the lock files and the `pnpm licenses list` renderer instead.
|
||||
|
||||
@@ -52,7 +50,7 @@ The Claude distribution tests prove that only the exact direct SDK identity bypa
|
||||
|
||||
## Consequences
|
||||
|
||||
A dependency edit now carries a regenerated notices file into the same commit. Contributors pay one generator run — about a second — on commits that touch a manifest, and nothing on any other commit. Committing with hooks disabled defers the cost to a test-lane failure that names the command.
|
||||
Commits pay no generator run. A dependency or browser-import edit that leaves the notices stale fails the test lane with an error that names the regeneration command.
|
||||
|
||||
The generator needs an installed tree, which makes it heavier than a pure-source generator, and a new package with unusable published metadata needs an `OVERRIDES` entry rather than silently rendering a blank license. Both failures are loud and name the remedy.
|
||||
|
||||
|
||||
@@ -14,9 +14,7 @@ Status: implemented
|
||||
|
||||
[`THIRD_PARTY_NOTICES.md`](../../../../THIRD_PARTY_NOTICES.md) 由 [`scripts/gen-third-party-notices.ts`](../../../../scripts/gen-third-party-notices.ts) 依据各工作区 manifest、`vendor/README.md`、`pyproject.toml`、`pnpm-workspace.yaml` 与 [共享运行时锁文件](../../../../scripts/primary-runtime/lock.json)生成。根 README 双语两侧都从「许可证」一节链到该文件。
|
||||
|
||||
**新鲜度会得到维护,而非仅靠校验。** 只要暂存了生成器的任一输入——任何 manifest、工作区声明、根锁文件或共享运行时锁文件、`vendor/README.md`、某个 `pyproject.toml`、生成器自身,或持有构建期 pin 的脚本——pre-commit 任务就会重新生成该文件并将其暂存,改依赖的人不必事后再折返跑一次生成器。已提交的字节随后由 [`scripts/gen-third-party-notices.spec.ts`](../../../../scripts/gen-third-party-notices.spec.ts) 断言,而测试 lane 本就会跑这个文件——这项校验不增加门禁进程、不占调度位、也不新增 CI 步骤。需要单独校验时,`pnpm run verify-third-party-notices` 仍然可用。
|
||||
|
||||
有一处触发缺口是接受而非绕过的:lefthook 只检视磁盘上存在的文件,因此**删除** manifest 不会触发任何任务,移除一个包会落到测试 lane 的断言上。重构暂存文件列表以纳入删除的做法不成立——无论怎么给列表,lefthook 都会拿工作树过滤一遍。这个场景正由断言兜底。
|
||||
**新鲜度由测试 lane 保证。** 已提交的字节由 [`scripts/gen-third-party-notices.spec.ts`](../../../../scripts/gen-third-party-notices.spec.ts) 断言,而测试 lane 本就会跑这个文件,其中包括 PR 必过的 `node 24 / coverage` lane——这项校验不增加门禁进程、不占调度位、也不新增 CI 步骤。改动生成器任一输入——任何 manifest、工作区声明、根锁文件或共享运行时锁文件、`vendor/README.md`、某个 `pyproject.toml`、生成器自身,或持有构建期 pin 的脚本——的贡献者运行 `pnpm run gen-third-party-notices`;需要单独校验时,`pnpm run verify-third-party-notices` 仍然可用。没有 Git 钩子重新生成该文件:浏览器输入使每个包源码文件都成为生成器输入,钩子会让几乎每个提交都运行约 16 秒的生成器,而改变输出的提交很少。
|
||||
|
||||
文件默认只披露**直接**依赖;完整的 npm 与 Python SDK 闭包保留在各自锁文件中。两组独立分发的载荷会明确列出:`@anthropic-ai/claude-agent-sdk` 声明的官方 Claude 可执行包,以及共享运行时锁文件 `pythonPackages` 中的每个分发包。内置条目包含归一化名称、精确版本和已记录的许可证元数据;元数据缺失、归一化后名称重复或版本冲突都会使生成失败。共享 wheel 集合独立于 `python/` 下的 manifest,仅扫描后者会遗漏已打包的 Office 库。内置分发包同样通过运行时许可证检查,其中包括 Pillow 与 typing-extensions 声明的宽松许可证标识 `MIT-CMU` 和 `PSF-2.0`。
|
||||
|
||||
@@ -38,7 +36,7 @@ Claude 分发测试证明:只有精确匹配的直接 SDK 身份会绕过通
|
||||
|
||||
**保留手写文件,发版时人工过一遍。** 用肉眼审阅上百行推导数据,恰恰是生成器能做对的活;而且在两次发版之间,文件自称「列出全部直接依赖」这句话无人验证。
|
||||
|
||||
**用专门的 `doc-sync`(文档同步门禁)校验。** 仓库里其他生成产物都是这么把关的,本次改动最初也是这个形态。但它要在本已冗长的矩阵里再占一个门禁进程和一个调度位;更糟的是,它唯一的失败方式,就是在别人推完一个无关的依赖升级几分钟后,通知对方回去重跑一次生成器。改为提交时重新生成消除了这次打断,而把断言放进测试 lane 本就会跑的 spec 里,则以零额外 CI 成本保住了这项保证。
|
||||
**用专门的 `doc-sync`(文档同步门禁)校验。** 仓库里其他生成产物都是这么把关的,本次改动最初也是这个形态。但它要在本已冗长的矩阵里再占一个门禁进程和一个调度位,而测试 lane 本就会跑的 spec 里的断言能以零额外 CI 成本报告同样的过期。
|
||||
|
||||
**列出完整传递闭包。** 闭包有数千个包,锁文件里已带精确版本,铺开只会淹没读者真正要评估的直接依赖。文件转而指向锁文件与 `pnpm licenses list`。
|
||||
|
||||
@@ -52,7 +50,7 @@ Claude 分发测试证明:只有精确匹配的直接 SDK 身份会绕过通
|
||||
|
||||
## 后果
|
||||
|
||||
此后改动依赖时,重新生成的披露文件会随同一个提交入库。触及 manifest 的提交多付一次生成器运行——约一秒;其余提交不受影响。若禁用钩子提交,代价推迟为一次测试 lane 失败,其报错会指明补救命令。
|
||||
提交不运行生成器。改动依赖或浏览器侧 import 却未更新披露文件时,测试 lane 会失败,其报错会指明重新生成的命令。
|
||||
|
||||
生成器需要已安装的依赖树,因此比纯源码生成器更重;发布元数据不可用的新包需要补一条 `OVERRIDES`,而不是默默渲染出空白许可证。这两类失败都会明确报错并指出补救方式。
|
||||
|
||||
|
||||
+12
-12
@@ -15,26 +15,26 @@
|
||||
en: 174241330463841d
|
||||
zh: 7fe361c07e634053
|
||||
/agent-note-split-build-artifacts-and-build-check-with-build-running-both-concurrently/decision/steps-and-dependencies:
|
||||
en: 40f21a0941b9a23a
|
||||
zh: c9f1d702b804ecf2
|
||||
en: 43e78e255306cd43
|
||||
zh: a741d5ef1c7379f3
|
||||
/agent-note-split-build-artifacts-and-build-check-with-build-running-both-concurrently/decision/scheduling-failure-and-output:
|
||||
en: 4b324f92307d3691
|
||||
zh: e0cf4411a747f7e5
|
||||
/agent-note-split-build-artifacts-and-build-check-with-build-running-both-concurrently/decision/callers:
|
||||
en: af86d6dbe8d3b17c
|
||||
zh: 8e5fa596d6709b35
|
||||
en: 55c55eea07fdb459
|
||||
zh: ab78cdfa4d04a5e7
|
||||
/agent-note-split-build-artifacts-and-build-check-with-build-running-both-concurrently/decision/measurements:
|
||||
en: a5d74335200d1476
|
||||
zh: e817deb711f98504
|
||||
en: b3a753ac2aab6073
|
||||
zh: 19cbd0e32751896f
|
||||
/agent-note-split-build-artifacts-and-build-check-with-build-running-both-concurrently/decision/completeness-and-lossless-evidence:
|
||||
en: 7308ab88d2b0926f
|
||||
zh: 773ce413da90bcbc
|
||||
en: 3cd40e0db9a2c89a
|
||||
zh: 3f708be239779d0a
|
||||
/agent-note-split-build-artifacts-and-build-check-with-build-running-both-concurrently/decision/intentional-trade-offs-not-lossless:
|
||||
en: f3a5621dbfcd602d
|
||||
zh: f5beabfa81272ffb
|
||||
en: 14370bc5b54e1278
|
||||
zh: 7ac933092d3e9954
|
||||
/agent-note-split-build-artifacts-and-build-check-with-build-running-both-concurrently/alternatives-considered:
|
||||
en: 54905b912d17c74e
|
||||
zh: 86a298004c8024e3
|
||||
/agent-note-split-build-artifacts-and-build-check-with-build-running-both-concurrently/consequences:
|
||||
en: ce9135e424811303
|
||||
zh: 1737f084156211c3
|
||||
en: 083467f68d0f03ed
|
||||
zh: 93400e9994b8c645
|
||||
@@ -44,7 +44,7 @@ native → host-src ─┬─ host-check ─────────────
|
||||
└─ client-bundle → web ┘
|
||||
```
|
||||
|
||||
- client-src must follow host-bundle: Client packages import `@deepseek-ai/dsh-*/remote`, whose types `lib/typert.remote-client.d.ts` only Typert inside Host tsdown writes. host-check reads no Typert output; clean serial builds have always finished the Host aggregate check before Host tsdown.
|
||||
- client-src must follow host-bundle: Client packages import `@deepseek-ai/dsh-*/remote`, whose types `lib/typert.remote-client.d.ts` Typert writes, inside Host tsdown in these scopes and through `scripts/generate-typert.ts` in the typecheck scope. host-check reads no Typert output; clean serial builds have always finished the Host aggregate check before Host tsdown.
|
||||
- The artifact chain keeps the two non-data edges native → host-src and desktop-bundle → client-src; only the two check steps attach to the chain in parallel.
|
||||
- [`compile-referenced-projects.ts`](../../../../scripts/compile-referenced-projects.ts) owns the package-library step list `libraryBuildSteps`, the references argument construction `referencedProjectsCompilerArgs` (relative paths keep the command below Windows' command-line limit), and the aggregate-check arguments `aggregateCheckArgs`. The vendor release rehearsal (`host-libraries`) and CI benchmarks (`--noCheck`) run the same step list serially.
|
||||
- The check steps use project mode (`tsc -p`): it reads the declarations that references already emitted and compiles no reference, writing incremental state to the aggregates' existing `tsconfig.{host,client}.tsbuildinfo`. `build` and `build:check` run the same command, so their diagnostics are identical.
|
||||
@@ -63,9 +63,9 @@ native → host-src ─┬─ host-check ─────────────
|
||||
|---|---|---|
|
||||
| `build`, `build:official`, `Makefile` `build`, `scripts/publish-npm-baseline.ts`, `apps/desktop/scripts/package-target.ts`, `scripts/dev-bundle-registry.ts`, `release-publish.yml`, `sandbox.yml`, and the non-PR branches of `e2e.yml` and `release.yml` | `build` / `build:official` | Yes |
|
||||
| `test:web`, `test:web:refresh`, `test:web:perf`, `test:web:stress`, `apps/desktop` `test:updates:local`, `test:bench` / `build:bench` | `build`; `build:bench` runs `build:native-system`, `build:lib`, and the benchmark tsdown | Yes |
|
||||
| `typecheck` (run by the pre-push hook) | `build:lib:host` (Host `tsc -b tsconfig.host.json`, Host bundle, Desktop bundle) and Client `tsc -b tsconfig.client.json` | Yes |
|
||||
| `typecheck` (run by the pre-push hook) | `build.ts --scope typecheck`: host-src beside host-typert (the bundle-free, source-only Typert pass `generate-typert.ts`) → client-src, with `tsc -b tsconfig.{host,client}.json` after each face's package compilation; no bundle | Yes |
|
||||
| `dev:web` ([`scripts/dev-web.ts`](../../../../scripts/dev-web.ts)), `dev:desktop` (`apps/desktop/scripts/dev.ts`) | `build:artifacts` | None before launch; after `dev:web` launches, its `tsc -b tsconfig.client.json --watch` keeps checking the Client aggregate root program |
|
||||
| Prerequisite step of `lint`, `lint:fix`, `doc-typecheck`, and the CI Typert contracts gate | Host package compilation and the Host bundle (`compile-referenced-projects.ts host-libraries`), without the Desktop bundle | None |
|
||||
| Prerequisite step of `lint`, `lint:fix`, `doc-typecheck`, and the CI Typert contracts gate | Host package compilation beside the bundle-free Typert pass (`compile-referenced-projects.ts host-contracts`), without any bundle | None |
|
||||
| CI node 24 / snapshots and artifacts (`check:ci:consumers`), windows node 24 / build & observational (`check:ci:windows-blocking`) | `build` | Yes, the two required lanes |
|
||||
| CI node-compat 22.19 | `build:artifacts` (through run-gates) | None |
|
||||
| CI python runtime | `build-exe-for-python-sdk.ts --build-artifacts` | None |
|
||||
@@ -75,7 +75,7 @@ native → host-src ─┬─ host-check ─────────────
|
||||
| PR rehearsal in `release-vendor.yml` | `compile-referenced-projects.ts host-libraries` | None |
|
||||
| Non-PR branch of `release-vendor.yml`, `release-vendor-publish.yml` | `build:lib:host` | Host aggregate root program only |
|
||||
|
||||
`lint`, `lint:fix`, `doc-typecheck`, and the Typert contracts gate read only Typert outputs and package declarations: both aggregates are `noEmit`, oxlint builds its own programs, `doc-typecheck` references only package projects, and no consumer of `host-libraries` reads `apps/desktop/lib`. Their prerequisite step therefore skips the Host aggregate check and the Desktop bundle and falls from 159.8 s to 90.9 s (see the measurements below).
|
||||
`lint`, `lint:fix`, `doc-typecheck`, and the Typert contracts gate read only Typert outputs and package declarations: both aggregates are `noEmit`, oxlint builds its own programs, `doc-typecheck` references only package projects, and none of them reads a bundle. Their prerequisite step therefore skips the Host aggregate check and every bundle; skipping the Host aggregate check and the Desktop bundle alone took it from 159.8 s to 90.9 s (see the measurements below).
|
||||
|
||||
The consumers lane's HMR Web test starts `dev:web` and therefore uses `build:artifacts` inside that lane; the same lane's `build` gate still runs both aggregate checks. CI does not call `build:check` separately: the two required lanes already get the same checks through `build`. The [PR artifact build decision](2026-10-05-pr-artifact-typechecks.md) keeps its required complete builds, benchmark `--noCheck`, job and worker ceilings, serial node-compat Vitest, coverage weights, and pnpm packing checks; its PR artifact build is `build:artifacts`.
|
||||
|
||||
@@ -101,7 +101,7 @@ Final measurements: master (the merge base) and this branch run interleaved, eac
|
||||
| Development iteration: master `build`, branch `build:artifacts` | 317.1 s | 153.6 s (−51.6%) | 423.1 → 231.2 s (−45.4%) | 6.11 → 6.18 GiB |
|
||||
| `pnpm run build:check` after `build:artifacts` | — | 67.7 s | 144.6 s | 5.33 GiB |
|
||||
| `pnpm run build:check` no-op rerun | — | 19.4 s | 33.1 s | Not measured |
|
||||
| Prerequisite of `lint` and `doc-typecheck`: master `build:lib:host`, branch `host-libraries` | 159.8 s | 90.9 s (−43.2%) | 234.7 → 136.0 s | Not measured |
|
||||
| Prerequisite of `lint` and `doc-typecheck`: master `build:lib:host`, branch `host-libraries` (since replaced by `host-contracts`, see [local gate speed-ups](2026-10-12-local-gate-speedups.md)) | 159.8 s | 90.9 s (−43.2%) | 234.7 → 136.0 s | Not measured |
|
||||
|
||||
The serial branch sample overlapped other work on the host (742 s of foreign CPU), so its wall likely overstates the serial cost. In the serial build segments (master → branch, one sample each), Host tsdown falls from 22.5 to 11.7 s, Client package compilation from 55.6 to 48.7 s, the Client aggregate check from 68.2 to 35.9 s, and Client tsdown from 13.9 to 10.5 s; the segments sum to 308.5 s and 254.9 s. Those reductions come from [the lossless speed-ups note](2026-10-11-lossless-build-speedups.md); the further reduction from 254.9 s of serial segments to the 169.1 s concurrent build comes from this note's scheduling, which takes the Host aggregate check (about 66 s) off the critical path. In the concurrent build, the critical path is native → host-src → host-bundle → desktop-bundle → client-src → client-check, and host-check ends about 30 s before the last step (one earlier sample). `build:check` runs the Host and Client aggregate checks concurrently, so its wall is the Host check's (about 65 s).
|
||||
|
||||
@@ -114,7 +114,7 @@ The serial branch sample overlapped other work on the host (742 s of foreign CPU
|
||||
| Package source type error | host-src / client-src | Not reported (reads existing declarations) | host-src / client-src | Reported | Reported |
|
||||
| Type error only in an aggregate root program's tests, scripts, benchmarks, or website | Not reported | host-check / client-check | host-check / client-check | Reported | consumers, windows-build |
|
||||
| Package tsconfig configuration error | host-src / client-src | Not reported (`tsc -p` does not validate referenced projects' tsconfig options or syntax) | host-src / client-src | Reported | Reported |
|
||||
| Typert analysis error | host-bundle | Not reported | host-bundle | Reported (through the Host bundle) | Reported |
|
||||
| Typert analysis error | host-bundle | Not reported | host-bundle | Reported (through host-typert) | Reported |
|
||||
| Missing prerequisite output | — | Compiler diagnostic (TS6305, TS2307) | — | — | — |
|
||||
|
||||
Negative controls: after a type error (TS2322) is added to `scripts/pnpm-invocation.spec.ts`, which only the Host aggregate root program contains, `build:artifacts` exits 0; `build:check` exits 1 with the Host aggregate check failing and the Client aggregate check passing; `build` exits 1 with 8 of 9 steps passing and 1 failing, and writes no client build record. In a scratch fixture whose referenced project's tsconfig has an invalid `target`, a JSON syntax error, or an unknown compiler option, `tsc -p` exits 0, while `tsc -b` reports TS6046, TS5092 with TS1012, and TS5023 respectively and exits 1; when the referenced project lacks `composite`, both report TS6306.
|
||||
@@ -123,7 +123,7 @@ CI evidence: on PR #6005 both required lanes that run the concurrent `pnpm run b
|
||||
|
||||
### Intentional trade-offs (not lossless)
|
||||
|
||||
- **Some commands skip the aggregate checks:** `build:artifacts`, the launch builds of `dev:web` and `dev:desktop`, and the prerequisite steps of `lint`, `lint:fix`, `doc-typecheck`, and the Typert contracts gate do not type-check the two aggregate root programs, and these prerequisite steps do not produce `apps/desktop/lib`. `build`, `build:check`, `typecheck` (pre-push hook), and the two required CI lanes own completeness; `dev:web` and `dev:desktop` do not refuse to launch because of test type errors.
|
||||
- **Some commands skip the aggregate checks:** `build:artifacts`, the launch builds of `dev:web` and `dev:desktop`, and the prerequisite steps of `lint`, `lint:fix`, `doc-typecheck`, and the Typert contracts gate do not type-check the two aggregate root programs, and these prerequisite steps produce declarations and Typert outputs but no bundle. `build`, `build:check`, `typecheck` (pre-push hook), and the two required CI lanes own completeness; `dev:web` and `dev:desktop` do not refuse to launch because of test type errors.
|
||||
- **`build:check` does not check freshness:** When sources change after `build:artifacts`, `build:check` checks against stale declarations, including Typert Remote declarations; rerun `build:artifacts` first. The complete `build` is unaffected.
|
||||
- **Concurrent `build` raises the memory peak:** This branch's complete `build` peaks at 7.53 GiB of process-tree RSS against 6.11 GiB for the master serial build (+1.42 GiB, medians of 2) and 6.27 GiB for the branch's serial build (n=1); CPU meanwhile falls from 423.1 s to 374.4 s because [the lossless speed-ups note](2026-10-11-lossless-build-speedups.md) removes more work than concurrent contention adds. In the prototype (without the Typert changes), concurrent scheduling alone raises the RSS peak by about 2.1 GiB (5.9 → 8.0 GiB) and CPU by about 3.7%. `DSH_GATE_CONCURRENCY` bounds it; under memory pressure use `DSH_GATE_CONCURRENCY=1 pnpm run build`, or run `build:artifacts` and `build:check` separately. In the windows-build lane, `build` runs concurrently with `docs:build`.
|
||||
- **Passing steps' output is hidden by default:** Only failed steps print their complete output.
|
||||
@@ -150,7 +150,7 @@ CI evidence: on PR #6005 both required lanes that run the concurrent `pnpm run b
|
||||
|
||||
Development iterations can skip the two aggregate root programs with `build:artifacts` (51.6% faster cold than master's `build`) and complete the checks with `build:check` or `build` before declaring work complete. `build` stays complete: the Host aggregate check is off the critical path, the Client aggregate check runs alongside the Client bundle and web, and a cold build is 46.7% faster than master (including the lossless speed-ups note's changes; medians of 2). The costs are a higher memory peak, a little extra CPU from concurrent contention, less passing output by default, and several development and prerequisite commands that do not check test types (see the trade-offs above).
|
||||
|
||||
Removing or changing `build` in the two required lanes, consumers and windows-build, requires first transferring both aggregate checks to another blocking owner. If Typert later gains its own generation step, the step table adds it and client-src depends on it; command semantics and scheduling stay the same.
|
||||
Removing or changing `build` in the two required lanes, consumers and windows-build, requires first transferring both aggregate checks to another blocking owner. The typecheck scope and the lint prerequisites generate Typert contracts without bundling ([local gate speed-ups](2026-10-12-local-gate-speedups.md)); the artifact scopes keep generating them inside Host tsdown.
|
||||
|
||||
client-src's dependency on host-bundle guarantees the "Host and Remote artifacts complete before Client compilation" ordering that [Typert Remote method calls](../architecture/2026-08-02-typert-remote-method-calls.md) describes.
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ native → host-src ─┬─ host-check ─────────────
|
||||
└─ client-bundle → web ┘
|
||||
```
|
||||
|
||||
- client-src 必须在 host-bundle 之后:Client 包导入 `@deepseek-ai/dsh-*/remote`,其类型 `lib/typert.remote-client.d.ts` 只由 Host tsdown 中的 Typert 写出。host-check 不读取 Typert 输出,干净的串行构建一直在 Host tsdown 之前完成 Host 聚合检查。
|
||||
- client-src 必须在 host-bundle 之后:Client 包导入 `@deepseek-ai/dsh-*/remote`,其类型 `lib/typert.remote-client.d.ts` 由 Typert 写出:这些 scope 在 Host tsdown 中生成,typecheck scope 经 `scripts/generate-typert.ts` 生成。host-check 不读取 Typert 输出,干净的串行构建一直在 Host tsdown 之前完成 Host 聚合检查。
|
||||
- 产物链保留 native → host-src 与 desktop-bundle → client-src 这两条非数据依赖;只有两个 check 步骤并行挂接到链上。
|
||||
- [`compile-referenced-projects.ts`](../../../../scripts/compile-referenced-projects.ts) 拥有包库步骤列表 `libraryBuildSteps`、references 参数构造 `referencedProjectsCompilerArgs`(相对路径传参,避开 Windows 命令行长度上限)与聚合检查参数 `aggregateCheckArgs`。vendor 发布演练(`host-libraries`)与 CI benchmark(`--noCheck`)串行执行同一步骤列表。
|
||||
- check 步骤使用 project mode(`tsc -p`):它读取 references 已有的声明而不编译任何 reference,incremental 状态写入聚合配置已有的 `tsconfig.{host,client}.tsbuildinfo`。`build` 与 `build:check` 使用同一条命令,因此诊断相同。
|
||||
@@ -63,9 +63,9 @@ native → host-src ─┬─ host-check ─────────────
|
||||
|---|---|---|
|
||||
| `build`、`build:official`、`Makefile` `build`、`scripts/publish-npm-baseline.ts`、`apps/desktop/scripts/package-target.ts`、`scripts/dev-bundle-registry.ts`、`release-publish.yml`、`sandbox.yml`、`e2e.yml` 与 `release.yml` 的非 PR 分支 | `build` / `build:official` | 有 |
|
||||
| `test:web`、`test:web:refresh`、`test:web:perf`、`test:web:stress`、`apps/desktop` `test:updates:local`、`test:bench` / `build:bench` | `build`;`build:bench` 运行 `build:native-system`、`build:lib` 与 benchmark tsdown | 有 |
|
||||
| `typecheck`(pre-push hook 运行它) | `build:lib:host`(Host `tsc -b tsconfig.host.json`、Host bundle、Desktop bundle)与 Client `tsc -b tsconfig.client.json` | 有 |
|
||||
| `typecheck`(pre-push hook 运行它) | `build.ts --scope typecheck`:host-src 与 host-typert(不打包、只读源码的 Typert 生成 `generate-typert.ts`)并行 → client-src,各 face 包编译后运行 `tsc -b tsconfig.{host,client}.json`;不含任何 bundle | 有 |
|
||||
| `dev:web`([`scripts/dev-web.ts`](../../../../scripts/dev-web.ts))、`dev:desktop`(`apps/desktop/scripts/dev.ts`) | `build:artifacts` | 启动前无;`dev:web` 启动后的 `tsc -b tsconfig.client.json --watch` 持续检查 Client 聚合根程序 |
|
||||
| `lint`、`lint:fix`、`doc-typecheck` 与 CI 的 Typert contracts gate 的前置步骤 | Host 包编译与 Host bundle(`compile-referenced-projects.ts host-libraries`),不含 Desktop bundle | 无 |
|
||||
| `lint`、`lint:fix`、`doc-typecheck` 与 CI 的 Typert contracts gate 的前置步骤 | Host 包编译与不打包的 Typert 生成并行(`compile-referenced-projects.ts host-contracts`),不含任何 bundle | 无 |
|
||||
| CI node 24 / snapshots and artifacts(`check:ci:consumers`)、windows node 24 / build & observational(`check:ci:windows-blocking`) | `build` | 有,两个必需 lane |
|
||||
| CI node-compat 22.19 | `build:artifacts`(经 run-gates) | 无 |
|
||||
| CI python runtime | `build-exe-for-python-sdk.ts --build-artifacts` | 无 |
|
||||
@@ -75,7 +75,7 @@ native → host-src ─┬─ host-check ─────────────
|
||||
| `release-vendor.yml` 的 PR 演练 | `compile-referenced-projects.ts host-libraries` | 无 |
|
||||
| `release-vendor.yml` 的非 PR 分支、`release-vendor-publish.yml` | `build:lib:host` | 仅 Host 聚合根程序 |
|
||||
|
||||
`lint`、`lint:fix`、`doc-typecheck` 与 Typert contracts gate 只读取 Typert 输出与包声明:两个聚合配置都是 `noEmit`,oxlint 自行构建程序,`doc-typecheck` 只引用包 project,`host-libraries` 的消费方都不读取 `apps/desktop/lib`。它们的前置步骤因此跳过 Host 聚合检查与 Desktop bundle,耗时从 159.8 s 降到 90.9 s(见下文测量)。
|
||||
`lint`、`lint:fix`、`doc-typecheck` 与 Typert contracts gate 只读取 Typert 输出与包声明:两个聚合配置都是 `noEmit`,oxlint 自行构建程序,`doc-typecheck` 只引用包 project,它们都不读取 bundle。它们的前置步骤因此跳过 Host 聚合检查与所有 bundle;仅跳过 Host 聚合检查与 Desktop bundle 就使耗时从 159.8 s 降到 90.9 s(见下文测量)。
|
||||
|
||||
consumers lane 的 HMR Web 测试启动 `dev:web`,因此在该 lane 内使用 `build:artifacts`;同一 lane 的 `build` gate 仍运行两个聚合检查。CI 不单独调用 `build:check`:两个必需 lane 已通过 `build` 获得同一组检查。[PR 产物构建决策](2026-10-05-pr-artifact-typechecks.zh.md)的必需完整构建、benchmark `--noCheck`、job 与 worker 上限、node-compat 串行 Vitest、覆盖率权重与 pnpm 打包检查仍然有效;其中的 PR 产物构建由 `build:artifacts` 执行。
|
||||
|
||||
@@ -101,7 +101,7 @@ wall 中位数从 249.4 s 降到 172.1 s(−77.3 s,−31%)。各步骤单
|
||||
| 开发迭代:master `build`,本分支 `build:artifacts` | 317.1 s | 153.6 s(−51.6%) | 423.1 → 231.2 s(−45.4%) | 6.11 → 6.18 GiB |
|
||||
| `pnpm run build:check`(`build:artifacts` 之后) | — | 67.7 s | 144.6 s | 5.33 GiB |
|
||||
| `pnpm run build:check` 无改动重跑 | — | 19.4 s | 33.1 s | 未测量 |
|
||||
| `lint` 与 `doc-typecheck` 的前置步骤:master `build:lib:host`,本分支 `host-libraries` | 159.8 s | 90.9 s(−43.2%) | 234.7 → 136.0 s | 未测量 |
|
||||
| `lint` 与 `doc-typecheck` 的前置步骤:master `build:lib:host`,本分支 `host-libraries`(后由 `host-contracts` 取代,见[本地门禁提速](2026-10-12-local-gate-speedups.zh.md)) | 159.8 s | 90.9 s(−43.2%) | 234.7 → 136.0 s | 未测量 |
|
||||
|
||||
本分支串行样本运行时主机上有其他工作(外来 CPU 742 s),因此它的 wall 可能高估串行成本。串行构建的各段中(master → 本分支,各一个样本),Host tsdown 从 22.5 s 降到 11.7 s,Client 包编译从 55.6 s 降到 48.7 s,Client 聚合检查从 68.2 s 降到 35.9 s,Client tsdown 从 13.9 s 降到 10.5 s;各段合计分别为 308.5 s 与 254.9 s。这些缩短来自[无损提速 Note](2026-10-11-lossless-build-speedups.zh.md);从 254.9 s 的串行各段合计到 169.1 s 的并发构建,其余缩短来自本 Note 的调度,它把 Host 聚合检查(约 66 s)移出关键路径。并发构建的关键路径是 native → host-src → host-bundle → desktop-bundle → client-src → client-check,host-check 在最后一步结束前约 30 s 完成(取自更早的一个样本)。`build:check` 并发运行 Host 与 Client 聚合检查,因此其 wall 等于 Host 聚合检查的 wall(约 65 s)。
|
||||
|
||||
@@ -114,7 +114,7 @@ wall 中位数从 249.4 s 降到 172.1 s(−77.3 s,−31%)。各步骤单
|
||||
| 包源码类型错误 | host-src / client-src | 不报告(读取已有声明) | host-src / client-src | 报告 | 报告 |
|
||||
| 只属于聚合根程序的测试、脚本、benchmark、website 类型错误 | 不报告 | host-check / client-check | host-check / client-check | 报告 | consumers、windows-build |
|
||||
| 包 tsconfig 配置错误 | host-src / client-src | 不报告(`tsc -p` 不校验被引用 project 的 tsconfig 选项与语法) | host-src / client-src | 报告 | 报告 |
|
||||
| Typert 分析错误 | host-bundle | 不报告 | host-bundle | 报告(经 Host bundle) | 报告 |
|
||||
| Typert 分析错误 | host-bundle | 不报告 | host-bundle | 报告(经 host-typert) | 报告 |
|
||||
| 前置产物缺失 | — | 编译器诊断(TS6305、TS2307) | — | — | — |
|
||||
|
||||
负对照:在只属于 Host 聚合根程序的 `scripts/pnpm-invocation.spec.ts` 中加入类型错误(TS2322)后,`build:artifacts` 以 0 退出;`build:check` 以 1 退出,其中 Host 聚合检查失败、Client 聚合检查通过;`build` 以 1 退出,9 个步骤中 8 个通过、1 个失败,且不写 client build record。在临时 fixture 中,被引用 project 的 tsconfig 含无效 `target`、JSON 语法错误或未知编译选项时,`tsc -p` 以 0 退出,`tsc -b` 分别报告 TS6046、TS5092 与 TS1012、TS5023 并以 1 退出;被引用 project 缺少 `composite` 时,两者都报告 TS6306。
|
||||
@@ -123,7 +123,7 @@ CI 证据:PR #6005 上,两个运行并发 `pnpm run build` 的必需 lane
|
||||
|
||||
### 有意的取舍(非无损)
|
||||
|
||||
- **部分命令跳过聚合检查:** `build:artifacts`、`dev:web` 与 `dev:desktop` 的启动构建,以及 `lint`、`lint:fix`、`doc-typecheck` 与 Typert contracts gate 的前置步骤,都不类型检查两个聚合根程序,这些前置步骤也不产出 `apps/desktop/lib`。完整性由 `build`、`build:check`、`typecheck`(pre-push hook)与两个必需 CI lane 负责;`dev:web` 与 `dev:desktop` 不会因测试类型错误而拒绝启动。
|
||||
- **部分命令跳过聚合检查:** `build:artifacts`、`dev:web` 与 `dev:desktop` 的启动构建,以及 `lint`、`lint:fix`、`doc-typecheck` 与 Typert contracts gate 的前置步骤,都不类型检查两个聚合根程序,这些前置步骤只产出声明与 Typert 输出,不打包。完整性由 `build`、`build:check`、`typecheck`(pre-push hook)与两个必需 CI lane 负责;`dev:web` 与 `dev:desktop` 不会因测试类型错误而拒绝启动。
|
||||
- **`build:check` 不检查新鲜度:** 在 `build:artifacts` 之后修改源码时,`build:check` 基于旧声明(包括 Typert Remote 声明)检查;需要先重跑 `build:artifacts`。完整 `build` 不受影响。
|
||||
- **并发 `build` 提高内存峰值:** 本分支完整 `build` 的进程树 RSS 峰值为 7.53 GiB,master 串行构建为 6.11 GiB(+1.42 GiB,2 个样本的中位数),本分支串行构建为 6.27 GiB(n=1);同时 CPU 从 423.1 s 降到 374.4 s,因为[无损提速 Note](2026-10-11-lossless-build-speedups.zh.md) 省去的工作多于并发争用增加的工作。原型(不含 Typert 改动)中,单独的并发调度使 RSS 峰值增加约 2.1 GiB(5.9 → 8.0 GiB)、CPU 增加约 3.7%。上限由 `DSH_GATE_CONCURRENCY` 控制;内存紧张时使用 `DSH_GATE_CONCURRENCY=1 pnpm run build`,或分别运行 `build:artifacts` 与 `build:check`。windows-build lane 中 `build` 与 `docs:build` 同时运行。
|
||||
- **成功步骤的输出默认不显示:** 只有失败步骤打印完整输出。
|
||||
@@ -150,7 +150,7 @@ CI 证据:PR #6005 上,两个运行并发 `pnpm run build` 的必需 lane
|
||||
|
||||
开发迭代可以用 `build:artifacts` 跳过两个聚合根程序(冷启动比 master 的 `build` 快 51.6%),在声明完成前用 `build:check` 或 `build` 补齐检查。`build` 保持完整:Host 聚合检查不在关键路径上,Client 聚合检查与 Client bundle、web 并行,冷启动比 master 快 46.7%(含无损提速 Note 的改动,2 个样本的中位数)。代价是更高的内存峰值、并发争用带来的少量额外 CPU、默认更少的成功输出,以及多个开发与前置命令不检查测试类型(见上文取舍)。
|
||||
|
||||
删除或改变 consumers 与 windows-build 两个必需 lane 的 `build`,必须先把两个聚合检查转交另一处阻塞型 owner。若 Typert 以后获得独立的生成步骤,步骤表新增该步骤,client-src 改为依赖它;命令语义与调度不变。
|
||||
删除或改变 consumers 与 windows-build 两个必需 lane 的 `build`,必须先把两个聚合检查转交另一处阻塞型 owner。typecheck scope 与 lint 类前置步骤不打包即生成 Typert 约定([本地门禁提速](2026-10-12-local-gate-speedups.zh.md));产物 scope 仍在 Host tsdown 中生成。
|
||||
|
||||
[Typert Remote 方法调用](../architecture/2026-08-02-typert-remote-method-calls.zh.md)描述的“Client 编译前先完成 Host 与 Remote 产物”由 client-src 对 host-bundle 的依赖保证。
|
||||
|
||||
|
||||
@@ -39,8 +39,8 @@
|
||||
en: 80c2ddc5fdff0b5f
|
||||
zh: f5ce309a2e88ff4f
|
||||
/agent-note-build-speed-ups-that-keep-outputs-unchanged/alternatives-considered:
|
||||
en: 186e42f2f5481c8d
|
||||
zh: 4a1c79a391a268b0
|
||||
en: 4372c82ef0c944dd
|
||||
zh: 5fb70d499baadea7
|
||||
/agent-note-build-speed-ups-that-keep-outputs-unchanged/consequences:
|
||||
en: 93a96d3ed398f348
|
||||
zh: 93b7c7405be981a6
|
||||
@@ -118,7 +118,7 @@ All numbers come from one shared Linux host (256 vCPU, 4 TB memory, load average
|
||||
- **Narrow `paths` to each face's reference closure (item 1):** The 328-entry version that keeps wildcard keys checks in 55.73 s against 59.08 s (one sample), within noise; the version without wildcard keys produces 18 diagnostics.
|
||||
- **Split the Client test aggregate program (item 1):** Every sub-program must inject the 242 files carrying module augmentations to pass, and the visible location count stays at 33–49; splitting into 2, 4, or 8 groups leaves the Check sum nearly flat while user CPU rises by 9%, 30%, and 57%, lowering only wall, and the 4- and 8-group splits each produce 1–2 diagnostics.
|
||||
- **Cache resolution results and make the discovery queue O(1) (Typert):** After items 2–4 only 28 surface walks remain, about 0.18 s, below noise.
|
||||
- **Move Typert into a separate process or build step (Typert):** The generator would have to be compiled first, and `@deepseek-ai/dsh-client-file-upload/types` would need a `paths` entry (otherwise Typert reads `lib/types/types.d.ts` while `tsc` writes it); after item 6 the worker already overlaps bundling, leaving at most about 1 s.
|
||||
- **Move Typert into a separate build step in artifact builds (Typert):** After item 6 the worker already overlaps bundling, leaving at most about 1 s. Type checks, which need no bundle, run a source-only generation step ([local gate speed-ups](2026-10-12-local-gate-speedups.md)).
|
||||
- **Filter `transform` by code content (item 7):** rolldown interprets `^` and `\s` with Rust regex semantics, which differ from JavaScript on lone CR, U+2028, and BOM, so a decorated module could be missed.
|
||||
- **Build a process-wide manifest index on `globalThis` (item 8):** The prototype saves about as much time as item 8, but it is process-global state without an owner, violating the shared-state ownership rule in the [package rules](../../../../packages/AGENTS.md).
|
||||
- **Disable tsdown's gzip report (item 8):** `--no-report` lowers Client tsdown by 0.95 s, within the 1.56 s baseline spread.
|
||||
|
||||
@@ -118,7 +118,7 @@ Status: implemented
|
||||
- **把 `paths` 收窄为各 face 的 reference closure(第 1 项):** 保留通配键的 328 条版本 Check 为 55.73 s 对 59.08 s(1 个样本),在噪声内;去掉通配键的版本产生 18 个诊断。
|
||||
- **拆分 Client 测试聚合程序(第 1 项):** 每个子程序都必须注入 242 个含模块增强的文件才能通过检查,可见位置数仍为 33–49;拆成 2、4、8 组时 Check 总和基本不变,user CPU 分别增加 9%、30%、57%,只降低 wall,且 4 组与 8 组各出现 1–2 个诊断。
|
||||
- **缓存解析结果并把发现队列改为 O(1)(Typert):** 第 2–4 项之后只剩 28 次表面遍历,约 0.18 s,低于噪声。
|
||||
- **把 Typert 移到独立进程或独立构建步骤(Typert):** 需要先编译 generator 自身,并为 `@deepseek-ai/dsh-client-file-upload/types` 补充 `paths` 条目(否则它读取 `tsc` 正在写入的 `lib/types/types.d.ts`);第 6 项之后 worker 已与打包重叠,剩余收益不超过约 1 s。
|
||||
- **在产物构建中把 Typert 移到独立构建步骤(Typert):** 第 6 项之后 worker 已与打包重叠,剩余收益不超过约 1 s。不需要 bundle 的类型检查运行只读源码的生成步骤([本地门禁提速](2026-10-12-local-gate-speedups.zh.md))。
|
||||
- **按代码内容过滤 `transform`(第 7 项):** rolldown 以 Rust 正则语义解释 `^` 与 `\s`,在孤立 CR、U+2028 与 BOM 上与 JavaScript 不同,可能漏掉含装饰器的模块。
|
||||
- **在 `globalThis` 上建立进程级 manifest 索引(第 8 项):** 原型收益与第 8 项相当,但它是没有 owner 的进程全局状态,违反[包规则](../../../../packages/AGENTS.md)中的共享状态归属要求。
|
||||
- **关闭 tsdown 的 gzip 报告(第 8 项):** `--no-report` 使 Client tsdown 降低 0.95 s,在 1.56 s 的基线跨度内。
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
# Bilingual-pair consistency record for 2026-10-12-local-gate-speedups.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-10-12-local-gate-speedups.md
|
||||
/agent-note-local-gate-hook-and-test-speed-ups:
|
||||
en: d8edb2c26730e9af
|
||||
zh: fb69bf2e7b602d4c
|
||||
/agent-note-local-gate-hook-and-test-speed-ups/problem:
|
||||
en: 1e2163ec378c44ff
|
||||
zh: d93cb5970896fccb
|
||||
/agent-note-local-gate-hook-and-test-speed-ups/decision:
|
||||
en: 9984b4ad646bfaf2
|
||||
zh: 753287ae67e29605
|
||||
/agent-note-local-gate-hook-and-test-speed-ups/decision/measurement-conditions:
|
||||
en: 7430353afba96352
|
||||
zh: 6d2a09619a67ecba
|
||||
/agent-note-local-gate-hook-and-test-speed-ups/decision/1-type-checks-generate-typert-declarations-without-bundling:
|
||||
en: 4dc48e24a3323b7d
|
||||
zh: 7c88325160a41d12
|
||||
/agent-note-local-gate-hook-and-test-speed-ups/decision/2-the-pre-commit-hook-does-not-regenerate-third-party-notices:
|
||||
en: e2e344f184621172
|
||||
zh: 97d8785aaf9105bf
|
||||
/agent-note-local-gate-hook-and-test-speed-ups/decision/3-local-default-worker-budget:
|
||||
en: e9649c40d67e26e0
|
||||
zh: c99f22a41c4fc4af
|
||||
/agent-note-local-gate-hook-and-test-speed-ups/decision/4-repository-reference-candidates-resolve-against-one-object-listing:
|
||||
en: 2c945250337c88cf
|
||||
zh: d4bfa34cc858782b
|
||||
/agent-note-local-gate-hook-and-test-speed-ups/decision/5-documentation-gates-parse-each-document-once:
|
||||
en: c22d38399a2bb87f
|
||||
zh: 9ae97e5a6e3fbf48
|
||||
/agent-note-local-gate-hook-and-test-speed-ups/decision/6-repository-file-walks-list-each-directory-once:
|
||||
en: 2f0d35b0a688c938
|
||||
zh: 7184fd260c066a01
|
||||
/agent-note-local-gate-hook-and-test-speed-ups/decision/7-cli-help-reads-run-concurrently-doc-graph-probes-are-memoized:
|
||||
en: 965503ba8a31c039
|
||||
zh: fe02a394a677d018
|
||||
/agent-note-local-gate-hook-and-test-speed-ups/decision/8-type-model-spec-ts-runs-against-an-in-memory-workspace:
|
||||
en: d519ec362903aa2f
|
||||
zh: f49ee6547cb954f6
|
||||
/agent-note-local-gate-hook-and-test-speed-ups/decision/repository-wide-comparison:
|
||||
en: 7c9388dc859e0f93
|
||||
zh: 5df1fc58eb7a46e8
|
||||
/agent-note-local-gate-hook-and-test-speed-ups/alternatives-considered:
|
||||
en: 763d94734b8967cf
|
||||
zh: abe980d486e1d7da
|
||||
/agent-note-local-gate-hook-and-test-speed-ups/consequences:
|
||||
en: ca00b04567d09408
|
||||
zh: 97011043c60f4bc9
|
||||
@@ -0,0 +1,158 @@
|
||||
# Agent Note: Local gate, hook, and test speed-ups
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-10-12-local-gate-speedups.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
On the baseline, master at the merge of #6013, local runs of the Git hooks, `pnpm run test`, `test:docs`, and `doc-sync` spend most of their wall time on work that their results do not depend on:
|
||||
|
||||
- **Typert declarations from the bundler.** `typecheck`, the command the pre-push hook runs, executes `build:lib:host` (Host `tsc -b tsconfig.host.json`, the Host tsdown pass, and the Desktop bundle) before `tsc -b tsconfig.client.json`. The prerequisite of `lint`, `lint:fix`, `doc-typecheck`, and the CI `typert-contracts` gate runs Host package compilation and then the Host tsdown pass (`compile-referenced-projects.ts host-libraries`). Type checks read only package declarations and Typert declarations, yet `typecheck` with nothing to recheck takes 34.1/35.0 s and the prerequisite takes 52.2/29.6 s.
|
||||
- **Third-party notices on every commit.** The pre-commit hook regenerates `THIRD_PARTY_NOTICES.md` whenever a staged file is a generator input. To find browser-side third-party imports, the generator test-bundles 75 Client packages and runs one Vite build, so every package source file is an input; on a commit that stages one file under a package `src/` subdirectory, the hooks take 16.5/17.8 s, of which the notices job takes 12.4/13.4 s.
|
||||
- **Host CPUs as the local worker count.** `os.availableParallelism()` reports the host's CPUs (256 on the measurement host) rather than the container's CPU quota (64). With that default, `pnpm run test` starts 255 Vitest forks, peaks at 55.3 GiB RSS, and fails 12 additional files (14 timeouts) intermittently, while `doc-sync`, `test:docs`, `hygiene`, and `check:all` run at most 4 gates concurrently.
|
||||
- **One Git prefix lookup per candidate.** `verify-repository-references` resolves each of about 26,000 abbreviated hexadecimal candidates with a Git prefix lookup through `git cat-file --batch-check`; the lookups take 135.7 s of the gate's 166.8 s.
|
||||
- **Repeated Markdown parsing.** markdown links parses each anchor target twice more and probes target existence without a cache; translation pairing globs four times and parses each document again after link normalization; the package README model-experience and limitations checks each parse every README three times; type equivalence parses all 1,835 documents; Session format references parses each pair four times.
|
||||
- **Repeated directory reads.** `uniqueRepoFiles`, the walker behind markdown wrap, doc refs, and package paths, reads each directory once per pattern and `**` level and resolves every matched file with `realpath`.
|
||||
- **Serial help launches and repeated compiler probes.** `gen-cli-help` launches its 12 top-level source-mode `dsh … --help` processes one after another, each waiting mostly on profile boot I/O (49.9/53.9 s); `gen-doc-graphs` builds several compiler hosts and programs that repeat the same `ts.sys` file-system probes (48.7/44.7 s).
|
||||
- **A test file bound by file-system probes.** Each of the 61 cases of the Typert generator's `type-model.spec.ts` copies its fixture to disk and runs a full analysis whose four TypeScript programs each load the DOM library, `@types/node`, and zod v4, about 22,000 stat calls per analysis. The file takes 316.3/329.1 s and is the long tail of `pnpm run test`.
|
||||
|
||||
## Decision
|
||||
|
||||
The eight decisions below shorten those runs. Each item states the evidence that its outputs and diagnostics stay the same, or the intended difference it accepts.
|
||||
|
||||
| # | Decision | Affected commands | Measured wall | Outputs and diagnostics | Intended behavior difference |
|
||||
|---|---|---|---|---|---|
|
||||
| 1 | Type checks generate Typert declarations without bundling | `typecheck`, `lint`, `lint:fix`, `doc-typecheck`, CI `typert-contracts` | `typecheck` 34.1/35.0 → 21.9/20.0 s; prerequisite 52.2/29.6 → 12.5/11.3 s | 140 Typert files byte-identical; the same programs are checked | No runnable bundle and no client build record |
|
||||
| 2 | The pre-commit hook does not regenerate third-party notices | `pre-commit` | 16.5/17.8 → 4.3/4.5 s | Freshness asserted in the test lane | Stale notices fail in the test lane, not at commit |
|
||||
| 3 | Local default worker budget | run-gates aggregates, `build`, `typecheck`, `pnpm run test`, Oxlint, publint | `test` at 255 workers: 243.7 s, 55.3 GiB; `test:docs` 74.7 → 50.9 s | Same checks | Local defaults ignore CPUs above 12 or 48 |
|
||||
| 4 | Repository-reference candidates resolve against one object listing | `verify-repository-references` | 166.8 → 15.7 s | 0 classification differences over 27,050 candidates | None |
|
||||
| 5 | Documentation gates parse each document once | markdown links, translation pairing, README model experience and limitations, type equivalence, Session format references | markdown links 53.4/51.6 → 25.9/25.1 s; type equivalence 23.0/22.5 → 6.0/5.5 s | Byte-identical gate output | None |
|
||||
| 6 | Repository file walks list each directory once | markdown wrap, doc refs, package paths | doc refs 8.8/7.0 → 3.2/3.4 s | Identical file lists | doc refs does not read nested `lib` directories |
|
||||
| 7 | CLI help reads run concurrently; doc-graph probes are memoized | `verify-cli-help`, `verify-doc-graphs` | 49.9/53.9 → 6.9/7.2 s; 48.7/44.7 → 32.7/34.2 s | Byte-identical pages | CLI help uses about 3.6 GB at peak |
|
||||
| 8 | `type-model.spec.ts` runs against an in-memory workspace | `pnpm run test` | 316.3/329.1 → 14.65/15.04 s | Same 61 cases and assertions; one snapshot line differs | Stubs replace zod, `@types/node`, and the DOM library outside the Emitter case |
|
||||
|
||||
### Measurement conditions
|
||||
|
||||
All numbers are wall times from one shared Linux container with a 64-CPU quota on a host that reports 256 CPUs, at a one-minute load average of 20–150, so samples carry noise. The working tree lives on a network filesystem, where each file-system probe costs more than on a local disk. `a/b` lists two samples, and `x → y` compares the baseline with this implementation.
|
||||
|
||||
### 1. Type checks generate Typert declarations without bundling
|
||||
|
||||
- **Purpose:** Give `typecheck` and the prerequisite of `lint`, `lint:fix`, `doc-typecheck`, and the CI `typert-contracts` gate the declarations they read, package declarations from `tsc` and Typert declarations, without the Host tsdown pass or the Desktop bundle.
|
||||
- **Change:** `typecheck` is `tsx scripts/build.ts --scope typecheck`, which runs the steps below through the run-gates scheduler ([`scripts/build.ts`](../../../../scripts/build.ts)). The scope builds no native addon, tsdown bundle, Desktop bundle, or Web output, writes no client build record, and leaves runnable `lib/` output as the last `build:artifacts` left it; run `build:artifacts` before launching or testing built output. The prerequisite of `lint`, `lint:fix`, `doc-typecheck`, and `typert-contracts` is `compile-referenced-projects.ts host-contracts`, which runs host-src beside host-typert ([`compile-referenced-projects.ts`](../../../../scripts/compile-referenced-projects.ts)). `build`, `build:artifacts`, benchmark builds, and the PR rehearsal in `release-vendor.yml` run Typert inside the Host tsdown pass.
|
||||
|
||||
| Step | Command | `needs` |
|
||||
|---|---|---|
|
||||
| host-src | `node --max-old-space-size=4096 <tsc> -b <references of tsconfig.host.json>` | — |
|
||||
| host-typert | `node --import tsx/esm scripts/generate-typert.ts` | — |
|
||||
| client-src | `<tsc> -b <references of tsconfig.client.json>` | host-src, host-typert |
|
||||
| host-check | `node --max-old-space-size=4096 <tsc> -b tsconfig.host.json` | host-src |
|
||||
| client-check | `<tsc> -b tsconfig.client.json` | client-src |
|
||||
|
||||
- **Shared generation:** [`scripts/generate-typert.ts`](../../../../scripts/generate-typert.ts) calls `WorkspaceTypertGenerator.generateContributors()` for `WORKSPACE_TYPERT_FACES` ([`scripts/typert-faces.ts`](../../../../scripts/typert-faces.ts)), the faces the Host tsdown plugin also generates, and writes the result with `writeWorkspaceArtifacts()` from [`artifact-files.ts`](../../../../packages/typert/generator/src/artifact-files.ts), the writer the plugin uses. Like the plugin, it skips TypeScript diagnostics, which Host package compilation reports; a Typert analysis error fails host-typert as it fails the Host bundle in `build`. host-typert runs under Node with tsx's ESM hook rather than through `pnpm exec`, whose startup would lengthen the path to Client compilation.
|
||||
- **Aggregate checks in build mode:** host-check and client-check start after their own face's package compilation, so build mode finds every reference up to date, checks only the aggregate root program, and skips a root program whose tsbuildinfo is current.
|
||||
- **Source-only analysis:** host-typert can run beside host-src because its Host program reads no workspace build output. `tsconfig.base.json` maps `@deepseek-ai/dsh-client-file-upload/types` to source; without that alias the specifier resolves through package `exports` to `lib/types/types.d.ts`. With it, the Host program loads 1,289 files, none of them under a workspace package's `lib/`. `generate-typert.ts` enables `rejectBuildOutputs`: [`build-output-guard.ts`](../../../../packages/typert/generator/src/build-output-guard.ts) fails analysis with a `TypertAnalysisError` when a face program loads a file from a workspace package's `lib/` directory, or cannot resolve an import of a workspace package, as on a tree whose packages are not yet compiled, naming each such import specifier and the `paths` entry that maps it to source. Either way a missing alias fails generation whether or not host-src has run. The tsdown plugin leaves the option off because in `build` Typert always runs after Host package compilation. The [Typert generator README](../../../../packages/typert/generator/README.md) documents the writers and the option.
|
||||
- **Why it is lossless:** No workspace tsconfig sets `allowJs`, every `exports` `types` condition points into `lib/types/` or at `lib/typert.*`, and every tsdown config sets `dts: false`, so no type check reads tsdown output. The 140 Typert files (28 packages × 5 outputs) are byte-identical across the baseline tsdown pass, the current tsdown pass, `generate-typert.ts` after every Typert output is deleted, and `generate-typert.ts` with all 344 `lib/types` directories hidden; with one Remote method temporarily added to `packages/goal/goal`, the tsdown pass and `generate-typert.ts` also write identical files. `typecheck` checks every package project of both faces and both aggregate root programs, the programs that `build` checks.
|
||||
- **Performance:** `typecheck` with nothing to recheck takes 34.1/35.0 → 21.9/20.0 s. When both aggregate root programs must be rechecked, it takes 83.5 → 76.0/72.1 s, and its critical path is the Host aggregate check at about 66–70 s. The prerequisite of `lint` and `doc-typecheck` takes 52.2/29.6 → 12.5/11.3 s.
|
||||
- **Trade-off:** `typecheck`, `lint`, `lint:fix`, `doc-typecheck`, and `typert-contracts` write Typert declarations but no bundle, so runnable `lib/` JavaScript can lag behind those declarations until the next `build:artifacts`.
|
||||
- **Relation to the build:** [The lossless build speed-ups note](2026-10-11-lossless-build-speedups.md) rejects moving Typert out of the Host tsdown pass for builds, where its Worker Thread already overlaps bundling and a separate step saves at most about 1 s. Type-check commands run no bundler, so generating without one removes the whole Host tsdown pass and the Desktop bundle from their critical path. [The build split note](2026-10-11-build-artifacts-check-split.md) lists every caller and its command.
|
||||
- **Known gap:** Incremental `tsc -b` does not record `lib/typert.remote-client.d.ts`, which Client sources reach through package `exports`, as an input of the consuming project; when a Remote signature changes and no Client source does, an incremental check does not recheck the consumers. The gap is independent of which pass writes the declarations; Issue #6022 tracks it.
|
||||
|
||||
### 2. The pre-commit hook does not regenerate third-party notices
|
||||
|
||||
- **Change:** The `pre-commit` hook in [`lefthook.yml`](../../../../lefthook.yml) has no third-party notices job. [`gen-third-party-notices.spec.ts`](../../../../scripts/gen-third-party-notices.spec.ts) asserts the committed bytes of `THIRD_PARTY_NOTICES.md` in the test lane, including the required `node 24 / coverage` lane, and names `pnpm run gen-third-party-notices` when they are stale. [The generated third-party notices note](2026-07-30-generated-third-party-notices.md) owns this freshness decision.
|
||||
- **Performance:** A commit that stages one file under a package `src/` subdirectory spends 4.3/4.5 s in the hooks instead of 16.5/17.8 s, of which the notices job took 12.4/13.4 s.
|
||||
- **Trade-off:** A commit that leaves the notices stale fails in the test lane after push rather than being corrected at commit time.
|
||||
|
||||
### 3. Local default worker budget
|
||||
|
||||
- **Purpose:** Size default parallelism for a shared workstation or container, where Node reports host CPUs rather than the CPU quota.
|
||||
- **Change:** [`scripts/parallelism.ts`](../../../../scripts/parallelism.ts) owns the default. With `CI=true` it is the CPU count Node reports. Otherwise it is capped at 12 (`LOCAL_PARALLELISM_CAP`) for the run-gates scheduler, `build`, `typecheck`, Oxlint, and publint, and at 48 (`LOCAL_TEST_PARALLELISM_CAP`) for Vitest forks and the local coverage budget. `doc-sync`, `test:docs`, `hygiene`, and `check:all`, whose gates each build a full `ts.Program`, run at most 8 gates concurrently, in CI as well. Explicit `DSH_GATE_CONCURRENCY`, `DSH_OXLINT_THREADS`, `DSH_COVERAGE_MAX_WORKERS`, and Vitest `--maxWorkers` take precedence; in CI, Vitest and Oxlint keep their own defaults unless the run-gates CI environment sets these variables. The [development guide](../../../../docs/development.md) states the defaults for contributors.
|
||||
|
||||
`pnpm run test` at four fork counts, with the disk-backed `type-model.spec.ts` that item 8 replaces, which sets the wall of the 32-worker run:
|
||||
|
||||
| Vitest workers | Wall | Peak RSS | Additional intermittent failures | Every file except the slowest finished at |
|
||||
|---|---|---|---|---|
|
||||
| 255 (the reported CPU count) | 243.7 s | 55.3 GiB | 12 files, 14 timeouts | about 135–170 s |
|
||||
| 32 | 310.4 s | 15.7 GiB | 4 files, 4 timeouts | 193 s |
|
||||
| 24 | 337.2 s | 13.2 GiB | 5 files, 5 timeouts | 233 s |
|
||||
| 12 | 410.5 s | 8.4 GiB | 2 files, 3 timeouts | 406 s |
|
||||
|
||||
- **Oxlint:** Oxlint's own default is 64 threads, read from the cgroup quota; at 12 threads its wall stays about 87–90 s with about 15% less CPU, and at 8 threads it takes about 4 s longer.
|
||||
- **Documentation aggregates:** `test:docs` takes 50.9 s at 8 concurrent gates against 74.7 s at 4. `doc-sync`, measured without item 4, takes 341.8, 295.0, and 253.2 s at 4, 8, and 12 concurrent gates, with peak RSS of 10.0, 13.5, and 16.3 GiB.
|
||||
- **Trade-off:** A machine whose CPU quota exceeds the caps gets no more default parallelism than 12 or 48 and needs the override variables; a container whose quota is below a cap still oversubscribes, because Node reports host CPUs. At 8 concurrent gates `doc-sync` peaks at 13.5 GiB RSS against 10.0 GiB at 4; 12 concurrent gates finish 41.8 s sooner at 16.3 GiB. The CI documentation workflow also runs `doc-sync` at 8 concurrent gates.
|
||||
|
||||
### 4. Repository-reference candidates resolve against one object listing
|
||||
|
||||
- **Change:** [`verify-repository-references.ts`](../../../../scripts/verify-repository-references.ts) lists every object name once with `git cat-file --batch-all-objects --batch-check=%(objectname)`, about 1.2 million objects in 0.6 s, sorts the list, and binary-searches each lowercase candidate prefix in memory; one `--batch-check=%(objectname) %(objecttype)` call then reads the types of the matched objects. A candidate is a commit reference only when its prefix matches exactly one available object and that object is a commit, the rule Git's own prefix lookup applies; the listing covers unreachable and alternate objects, as Git's lookup does.
|
||||
- **Performance:** 166.8 → 15.7 s.
|
||||
- **Why it is lossless:** Git's per-candidate prefix lookup and the in-memory search classify all 27,050 real and synthetic candidates identically, including ambiguous prefixes, blob and tree prefixes, and random strings.
|
||||
- **Trade-off:** The listing is about 49 MiB of Git output for 1.2 million objects, read under a 1 GiB output limit.
|
||||
|
||||
### 5. Documentation gates parse each document once
|
||||
|
||||
- **Change:** Each gate below parses a Markdown document once and passes the tree to every consumer in that run.
|
||||
|
||||
| Gate | Single-parse mechanism | Wall |
|
||||
|---|---|---|
|
||||
| markdown links ([`verify-md-links.ts`](../../../../scripts/verify-md-links.ts)) | One per-run cache parses each file once for its destinations and anchors and probes each resolved target once | 53.4/51.6 → 25.9/25.1 s |
|
||||
| translation pairing ([`verify-translation-pairing.ts`](../../../../scripts/verify-translation-pairing.ts)) | One glob covers every scope pattern; the record reuses the authored tree under the guard below | 51.0/47.1 → 30.3/29.3 s |
|
||||
| package README model experience, package README limitations | Each check parses a README once and passes the tree to `markdownProseLines()` and `markdownHeadingLines()` | about 12 → 5.9 s each |
|
||||
| type equivalence ([`verify-type-equiv.ts`](../../../../scripts/verify-type-equiv.ts)) | A text prefilter skips documents that cannot hold a source-equivalence fence; each manifest TypeScript source is parsed once | 23.0/22.5 → 6.0/5.5 s |
|
||||
| Session format references | The persistence renderer passes the trees it parses to the pairing record | 10.2 → 5.3 s |
|
||||
|
||||
- **Pairing reuse guard:** `normalizedTopLevelBlocks()` in [`translation-pairing-record.ts`](../../../../scripts/translation-pairing-record.ts) reuses the authored tree for normalized text only when every link-normalization edit replaces a complete, title-free destination that does not start a line, the authored text equals the node's `url`, and both the authored and the replacement text contain only `[A-Za-z0-9._/:#%-]`. Those characters cannot end a destination or start or end another construct, so the normalized text parses to the same nodes with shifted offsets. Any other edit falls back to a full parse of the normalized text.
|
||||
- **Type-equivalence prefilter:** [`type-equiv-prefilter.ts`](../../../../scripts/type-equiv-prefilter.ts) keeps a document for parsing when it contains `type-equiv` or `public-api`, or when a line containing `` ``` `` or `~~~` also contains `&` or `\`. Parsing changes an info string only by decoding character references and backslash escapes, so `ts type-equiv` and `ts type\-equiv` keep their documents; [`type-equiv-prefilter.spec.ts`](../../../../scripts/type-equiv-prefilter.spec.ts) covers both forms.
|
||||
- **Why it is lossless:** Every gate's output on the repository is byte-identical, and seeded faults are reported identically. For pairing, the top-level blocks of all 1,886 corpus documents and the records of all 943 pairs match those of a full reparse, as do randomized destinations.
|
||||
|
||||
### 6. Repository file walks list each directory once
|
||||
|
||||
- **Change:** `uniqueRepoFiles()` in [`scripts/repo-files.ts`](../../../../scripts/repo-files.ts) shares one directory-listing cache across all patterns of a call, so each directory is read at most once, and calls `realpath` only for matches reached through a symbolic link; a regular file reached through real directories canonicalizes to the repository's realpath joined with its relative path. Its optional `skipDirectory` predicate keeps the walker out of a directory whose every path the caller excludes; [`verify-doc-refs.ts`](../../../../scripts/verify-doc-refs.ts) skips every `lib` directory below the first path segment, whose files it excludes in any case.
|
||||
- **Performance:** markdown wrap 25.8/25.0 → 21.3/21.2 s; doc refs 8.8/7.0 → 3.2/3.4 s; package paths 9.9/8.1 → 7.2/5.5 s.
|
||||
- **Why it is lossless:** All three gates receive identical file lists, and a broken or cyclic symbolic link still fails through `realpath`.
|
||||
- **Behavior difference:** doc refs does not list a skipped `lib` directory, so an unreadable one does not fail the gate with EACCES.
|
||||
|
||||
### 7. CLI help reads run concurrently; doc-graph probes are memoized
|
||||
|
||||
- **CLI help:** `prefetchHelp()` in [`scripts/gen-cli-help.ts`](../../../../scripts/gen-cli-help.ts) starts the 12 top-level `dsh … --help` reads (the launcher, `plugin`, and each profile's shorthand and `--profile` forms) within the default worker budget, each with its own temporary `DSH_HOME` and `DSH_AGENTS_HOME`, and the in-order traversal consumes them; nested reads share the same limit. A failed read reaches the traversal when it requests that invocation, and `close()` aborts queued and running reads and waits for every started child. The gate takes 49.9/53.9 → 6.9/7.2 s.
|
||||
- **Doc graphs:** `withMemoizedFileSystemProbes()` in [`scripts/gen-doc-graphs.ts`](../../../../scripts/gen-doc-graphs.ts) memoizes `ts.sys` `fileExists`, `directoryExists`, `realpath`, `readDirectory`, and `getDirectories` while `renderDocs` runs, so every compiler host and config parse in one run shares one view of the file system. The workspace must not change during the run, and the original methods are restored before pages are written. The gate takes 48.7/44.7 → 32.7/34.2 s.
|
||||
- **Why it is lossless:** Both generators produce byte-identical pages.
|
||||
- **Trade-off:** The concurrent help processes use about 3.6 GB of memory combined at peak.
|
||||
|
||||
### 8. `type-model.spec.ts` runs against an in-memory workspace
|
||||
|
||||
- **Change:** [`type-model.spec.ts`](../../../../packages/typert/generator/tests/type-model.spec.ts) mocks `node:fs` with `memoryFileSystem()` and the `ts.sys` host from [`type-model-workspace.ts`](../../../../packages/typert/generator/tests/type-model-workspace.ts), so fixture copies, case edits, write-mode annotations, tsconfig expansion, and module resolution under the in-memory root never touch the disk. Each workspace mounts minimal `zod` and `@types/node` declaration stubs; only the Emitter case keeps real zod. The fixture's `tsconfig.base.json` sets `lib: ["ES2024"]`, which excludes the DOM library, and cases that read the unmodified fixture share one deep-frozen analysis. The generator source has no test-specific path.
|
||||
- **Performance:** The file alone takes 316.3/329.1 → 14.65/15.04 s.
|
||||
- **Why the behavior coverage stays:** The 61 case names and their assertions are the same. The snapshot differs in one line, the external zod symbol path, which names the stub (`<external>:node_modules/zod/index.d.ts#ZodType`) rather than a pnpm store version.
|
||||
- **Trade-off:** Outside the Emitter case, the spec does not exercise the analyzer against the real file system, the DOM library, or the real zod and `@types/node` declarations. The memory file system implements only the `node:fs` calls the analyzer makes (`existsSync`, `readFileSync`, `realpathSync`, and `writeFileSync`); another call on an in-memory path reaches the real file system, where the path does not exist.
|
||||
|
||||
### Repository-wide comparison
|
||||
|
||||
Both trees were measured in the same session, alternating baseline and implementation runs of each command after `pnpm run build:artifacts` (`pnpm run test` fails the same environment-dependent files on both trees, 42 on the baseline and a subset of 28 here):
|
||||
|
||||
| Command | Baseline | This implementation | Change | Items |
|
||||
|---|---|---|---|---|
|
||||
| `pre-commit` hooks, one staged file under a package `src/` subdirectory | 16.5/17.8 s | 4.3/4.5 s | −75% | 2 |
|
||||
| `pnpm run typecheck` (pre-push), nothing to recheck | 29.7/23.3 s | 14.2/16.1 s | −43% | 1, 3 |
|
||||
| `pnpm run lint` | 110.0 s | 106.7 s | −3% | 1 |
|
||||
| `pnpm run doc-typecheck` | 45.2 s | 36.1 s | −20% | 1 |
|
||||
| `pnpm run test:docs` | 102.4/104.0 s | 26.8/29.3 s | −73% | 3–6 |
|
||||
| `pnpm run doc-sync` | 186.8 s | 70.3 s | −62% | 3–7 |
|
||||
| `pnpm run test` | 222.7 s (255 workers) | 148.1 s (48 workers) | −34% | 3, 8 |
|
||||
|
||||
`lint` time is Oxlint itself; its prerequisite falls as item 1 states. CPU time falls with wall: `typecheck` user time 39.5 → 14.2 s, `test:docs` 212.6 → 126.3 s, `doc-sync` 628.2 → 503.2 s, and `test` 3,417 → 3,014 s.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
- **Cap every local default at 12, including Vitest forks (item 3):** `pnpm run test` takes 410.5 s at 12 workers against 243.7 s at 255, 68% longer.
|
||||
- **Use half of the cgroup CPU quota as the local budget (item 3):** Reading the quota is a larger change and helps only inside containers.
|
||||
- **Parse documents in parallel `worker_threads` (item 5):** It adds more complexity than parsing each document once, which removes the repeated work itself.
|
||||
- **Regenerate third-party notices in the pre-commit hook (item 2):** Browser inputs make every package source file a generator input, so the hook runs the 16-second generator on nearly every commit while few commits change its output; [the generated third-party notices note](2026-07-30-generated-third-party-notices.md) owns the decision.
|
||||
|
||||
## Consequences
|
||||
|
||||
The pre-push `typecheck` with nothing to recheck takes about 14–22 s, the `lint` and `doc-typecheck` prerequisite about 12 s, and the hooks of a one-file commit about 4 s. `pnpm run test` starts at most 48 forks locally, and `test:docs` and `doc-sync` run up to 8 gates at once. Typert outputs, generated pages, file lists, and reference classifications are byte-identical to the baseline.
|
||||
|
||||
Costs: type-check commands do not refresh runnable bundles; a stale notices file fails in the test lane after push; local defaults ignore CPUs above the caps and still oversubscribe a container whose quota is below them; 8 concurrent documentation gates raise the `doc-sync` RSS peak; CLI help uses about 3.6 GB at peak; doc graphs and markdown links assume the tree does not change during a run; `type-model.spec.ts` exercises stubs rather than real zod, `@types/node`, the DOM library, and disk I/O outside the Emitter case; and incremental `typecheck` inherits the Remote-declaration gap that Issue #6022 tracks.
|
||||
|
||||
Verification: `generate-typert.spec.ts` pins byte-identical files against the workspace-mode plugin, rejection of a Host program that loads a compiled workspace declaration with the missing alias named, and each failure stage; `compile-referenced-projects.spec.ts` pins the `host-contracts` steps and their failure reporting; `build.spec.ts` pins the typecheck scope's steps; `parallelism.spec.ts`, `run-gates.spec.ts`, and `run-oxlint.spec.ts` pin the CI and local budgets and the overrides; `repo-files.spec.ts`, `markdown.spec.ts`, `translation-pairing.spec.ts`, `type-equiv-prefilter.spec.ts`, `verify-md-links.spec.ts`, `gen-cli-help.spec.ts`, and `gen-doc-graphs.spec.ts` pin single directory listing, parse reuse, the pairing guard, the prefilter, the prefetch order and failure path, and probe memoization with restoration.
|
||||
@@ -0,0 +1,158 @@
|
||||
# Agent Note: 本地门禁、钩子与测试提速
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-10-12-local-gate-speedups.md) | 中文
|
||||
|
||||
## 问题
|
||||
|
||||
在基线(合并 #6013 时的 master)上,本地运行 Git 钩子、`pnpm run test`、`test:docs` 与 `doc-sync`(文档同步门禁)时,大部分 wall 时间花在结果并不依赖的工作上:
|
||||
|
||||
- **经打包器获得 Typert 声明。** pre-push 钩子运行的 `typecheck` 先运行 `build:lib:host`(Host `tsc -b tsconfig.host.json`、Host tsdown 阶段与 Desktop bundle),再运行 `tsc -b tsconfig.client.json`。`lint`、`lint:fix`、`doc-typecheck` 与 CI `typert-contracts` 门禁的前置步骤先运行 Host 包编译,再运行 Host tsdown 阶段(`compile-referenced-projects.ts host-libraries`)。类型检查只读取包声明与 Typert 声明,但无需重查时 `typecheck` 仍需 34.1/35.0 s,前置步骤需 52.2/29.6 s。
|
||||
- **每次提交都生成第三方声明。** 只要暂存文件是生成器的输入,pre-commit 钩子就重新生成 `THIRD_PARTY_NOTICES.md`。为找出浏览器侧的第三方 import,生成器对 75 个 Client 包试打包并运行一次 Vite 构建,因此每个包源码文件都是它的输入;暂存一个位于包 `src/` 子目录下的文件的提交,钩子合计 16.5/17.8 s,其中第三方声明任务占 12.4/13.4 s。
|
||||
- **以宿主 CPU 数作为本地 worker 数。** `os.availableParallelism()` 报告的是宿主 CPU 数(测量主机上为 256),而不是容器的 CPU 配额(64)。按此默认值,`pnpm run test` 启动 255 个 Vitest fork,RSS 峰值 55.3 GiB,并偶发地多失败 12 个文件(14 次超时);同时 `doc-sync`、`test:docs`、`hygiene` 与 `check:all` 最多只并发 4 个门禁。
|
||||
- **每个候选一次 Git 前缀查找。** `verify-repository-references` 通过 `git cat-file --batch-check` 对约 26,000 个缩写十六进制候选逐个做 Git 前缀查找;这些查找占该门禁 166.8 s 中的 135.7 s。
|
||||
- **重复解析 Markdown。** markdown links 对每个锚点目标再多解析两次,且探测目标是否存在时不缓存;translation pairing 做四次 glob,并在链接归一化后再次解析每个文档;包 README 的 model experience 与 limitations 检查各自把每个 README 解析三次;type equivalence 解析全部 1,835 个文档;Session format references 把每个配对解析四次。
|
||||
- **重复读取目录。** markdown wrap、doc refs 与 package paths 背后的遍历器 `uniqueRepoFiles` 对每个 pattern 与每层 `**` 各读取一次每个目录,并对每个匹配文件调用 `realpath`。
|
||||
- **串行启动 help 与重复的编译器探测。** `gen-cli-help` 依次启动 12 个顶层源码模式的 `dsh … --help` 进程,每个进程大部分时间在等待 profile 启动的 I/O(49.9/53.9 s);`gen-doc-graphs` 构建多个编译器 host 与 program,重复执行同样的 `ts.sys` 文件系统探测(48.7/44.7 s)。
|
||||
- **受文件系统探测拖累的测试文件。** Typert generator 的 `type-model.spec.ts` 的 61 个用例各自把 fixture(测试前置数据)复制到磁盘并运行一次完整分析,分析中的四个 TypeScript program 各自加载 DOM lib、`@types/node` 与 zod v4,每次分析约 22,000 次 stat 调用。该文件耗时 316.3/329.1 s,是 `pnpm run test` 的长尾。
|
||||
|
||||
## 决策
|
||||
|
||||
以下八项决策缩短上述运行。每一项都给出其产物与诊断保持不变的依据,或它接受的有意差异。
|
||||
|
||||
| # | 决策 | 受影响的命令 | 实测 wall | 产物与诊断 | 有意的行为差异 |
|
||||
|---|---|---|---|---|---|
|
||||
| 1 | 类型检查不打包地生成 Typert 声明 | `typecheck`、`lint`、`lint:fix`、`doc-typecheck`、CI `typert-contracts` | `typecheck` 34.1/35.0 → 21.9/20.0 s;前置步骤 52.2/29.6 → 12.5/11.3 s | 140 个 Typert 文件逐字节一致;检查的程序相同 | 不产出可运行 bundle,不写 client build record |
|
||||
| 2 | pre-commit 钩子不重新生成第三方声明 | `pre-commit` | 16.5/17.8 → 4.3/4.5 s | 新鲜度由测试 lane 断言 | 第三方声明过期时在测试 lane 失败,而不是在提交时 |
|
||||
| 3 | 本地默认 worker 预算 | run-gates 聚合、`build`、`typecheck`、`pnpm run test`、Oxlint、publint | 255 个 worker 时 `test` 为 243.7 s、55.3 GiB;`test:docs` 74.7 → 50.9 s | 检查不变 | 本地默认值不使用超过 12 或 48 的 CPU |
|
||||
| 4 | 仓库引用候选对照一次对象列表解析 | `verify-repository-references` | 166.8 → 15.7 s | 27,050 个候选的判定 0 差异 | 无 |
|
||||
| 5 | 文档门禁每个文档只解析一次 | markdown links、translation pairing、README model experience 与 limitations、type equivalence、Session format references | markdown links 53.4/51.6 → 25.9/25.1 s;type equivalence 23.0/22.5 → 6.0/5.5 s | 门禁输出逐字节一致 | 无 |
|
||||
| 6 | 仓库文件遍历每个目录只列一次 | markdown wrap、doc refs、package paths | doc refs 8.8/7.0 → 3.2/3.4 s | 文件列表一致 | doc refs 不读取嵌套的 `lib` 目录 |
|
||||
| 7 | CLI(命令行界面)help 读取并发运行;doc graphs 的探测做 memo | `verify-cli-help`、`verify-doc-graphs` | 49.9/53.9 → 6.9/7.2 s;48.7/44.7 → 32.7/34.2 s | 页面逐字节一致 | CLI help 峰值约用 3.6 GB 内存 |
|
||||
| 8 | `type-model.spec.ts` 在内存工作区上运行 | `pnpm run test` | 316.3/329.1 → 14.65/15.04 s | 61 个用例与断言不变;快照有一行不同 | 除 Emitter 用例外,桩替代 zod、`@types/node` 与 DOM lib |
|
||||
|
||||
### 测量条件
|
||||
|
||||
所有数字都是 wall 时间,取自同一个共享 Linux 容器:CPU 配额 64 核,宿主报告 256 个 CPU,一分钟 load average 为 20–150,因此样本带有噪声。工作树位于网络文件系统上,每次文件系统探测的代价都高于本地磁盘。`a/b` 表示两个样本,`x → y` 比较基线与本实现。
|
||||
|
||||
### 1. 类型检查不打包地生成 Typert 声明
|
||||
|
||||
- **目的:** 让 `typecheck` 以及 `lint`、`lint:fix`、`doc-typecheck` 与 CI `typert-contracts` 门禁的前置步骤得到它们读取的声明,即 `tsc` 产出的包声明与 Typert 声明,而不运行 Host tsdown 阶段或 Desktop bundle。
|
||||
- **改动:** `typecheck` 是 `tsx scripts/build.ts --scope typecheck`,它通过 run-gates 调度器运行下表中的步骤([`scripts/build.ts`](../../../../scripts/build.ts))。该 scope 不构建 native addon、tsdown bundle、Desktop bundle 或 Web 产物,不写 client build record,可运行的 `lib/` 产物保持上一次 `build:artifacts` 的状态;启动或测试构建产物之前先运行 `build:artifacts`。`lint`、`lint:fix`、`doc-typecheck` 与 `typert-contracts` 的前置步骤是 `compile-referenced-projects.ts host-contracts`,它让 host-src 与 host-typert 并行([`compile-referenced-projects.ts`](../../../../scripts/compile-referenced-projects.ts))。`build`、`build:artifacts`、benchmark 构建与 `release-vendor.yml` 的 PR(Pull Request)演练在 Host tsdown 阶段内运行 Typert。
|
||||
|
||||
| 步骤 | 命令 | `needs` |
|
||||
|---|---|---|
|
||||
| host-src | `node --max-old-space-size=4096 <tsc> -b <references of tsconfig.host.json>` | — |
|
||||
| host-typert | `node --import tsx/esm scripts/generate-typert.ts` | — |
|
||||
| client-src | `<tsc> -b <references of tsconfig.client.json>` | host-src、host-typert |
|
||||
| host-check | `node --max-old-space-size=4096 <tsc> -b tsconfig.host.json` | host-src |
|
||||
| client-check | `<tsc> -b tsconfig.client.json` | client-src |
|
||||
|
||||
- **共用生成:** [`scripts/generate-typert.ts`](../../../../scripts/generate-typert.ts) 对 `WORKSPACE_TYPERT_FACES`([`scripts/typert-faces.ts`](../../../../scripts/typert-faces.ts),即 Host tsdown 插件同样生成的 face)调用 `WorkspaceTypertGenerator.generateContributors()`,并用 [`artifact-files.ts`](../../../../packages/typert/generator/src/artifact-files.ts) 中插件同样使用的 `writeWorkspaceArtifacts()` 写出结果。与插件一样,它跳过 TypeScript 诊断,这些诊断由 Host 包编译报告;Typert 分析错误使 host-typert 失败,正如它在 `build` 中使 Host bundle 失败。host-typert 由 Node 加 tsx 的 ESM 钩子运行,而不经 `pnpm exec`,因为后者的启动开销会拉长通往 Client 编译的路径。
|
||||
- **以 build mode 运行聚合检查:** host-check 与 client-check 在本侧 face 的包编译之后才开始,因此 build mode 发现所有 references 都是最新的,只检查聚合根程序,并在根程序的 tsbuildinfo 为最新时跳过它。
|
||||
- **只读源码的分析:** host-typert 能与 host-src 并行,是因为它的 Host program 不读取任何工作区构建产物。`tsconfig.base.json` 把 `@deepseek-ai/dsh-client-file-upload/types` 映射到源码;没有这条别名时,该说明符经包 `exports` 解析到 `lib/types/types.d.ts`。有了它,Host program 加载 1,289 个文件,其中没有一个位于工作区包的 `lib/` 下。`generate-typert.ts` 开启 `rejectBuildOutputs`:face program 加载工作区包 `lib/` 目录下的文件,或无法解析对工作区包的 import(例如包尚未编译的工作区)时,[`build-output-guard.ts`](../../../../packages/typert/generator/src/build-output-guard.ts) 以 `TypertAnalysisError` 使分析失败,并指出每个这样的 import 说明符,以及把它映射到源码的 `paths` 条目。因此无论 host-src 是否已运行,缺失的别名都会使生成失败。tsdown 插件不开启该选项,因为在 `build` 中 Typert 总在 Host 包编译之后运行。[Typert generator README](../../../../packages/typert/generator/README.zh.md) 记录了这些写入函数与该选项。
|
||||
- **无损依据:** 没有任何工作区 tsconfig 设置 `allowJs`,每个 `exports` 的 `types` 条件都指向 `lib/types/` 内或 `lib/typert.*`,每个 tsdown 配置都设置 `dts: false`,因此没有类型检查读取 tsdown 产物。140 个 Typert 文件(28 个包 × 5 个输出)在以下场景中逐字节一致:基线 tsdown 阶段、当前 tsdown 阶段、删除全部 Typert 输出后运行 `generate-typert.ts`、隐藏全部 344 个 `lib/types` 目录后运行 `generate-typert.ts`;临时给 `packages/goal/goal` 加一个 Remote 方法时,tsdown 阶段与 `generate-typert.ts` 写出的文件也相同。`typecheck` 检查两个 face 的全部包 project 与两个聚合根程序,即 `build` 检查的程序。
|
||||
- **性能:** 无需重查时 `typecheck` 为 34.1/35.0 → 21.9/20.0 s。两个聚合根程序都需要重查时为 83.5 → 76.0/72.1 s,其关键路径是约 66–70 s 的 Host 聚合检查。`lint` 与 `doc-typecheck` 的前置步骤为 52.2/29.6 → 12.5/11.3 s。
|
||||
- **取舍:** `typecheck`、`lint`、`lint:fix`、`doc-typecheck` 与 `typert-contracts` 写出 Typert 声明但不写 bundle,因此在下一次 `build:artifacts` 之前,可运行的 `lib/` JavaScript 可能落后于这些声明。
|
||||
- **与构建的关系:** [无损构建提速 Note](2026-10-11-lossless-build-speedups.zh.md) 否决了在构建中把 Typert 移出 Host tsdown 阶段:构建中它的 Worker Thread 已与打包重叠,独立步骤最多只能省约 1 s。类型检查命令不运行打包器,因此不打包地生成会把整个 Host tsdown 阶段与 Desktop bundle 移出它们的关键路径。[构建拆分 Note](2026-10-11-build-artifacts-check-split.zh.md) 列出每个调用方及其命令。
|
||||
- **已知缺口:** 增量 `tsc -b` 不把 Client 源码经包 `exports` 访问到的 `lib/typert.remote-client.d.ts` 记为消费方 project 的输入;Remote 签名改变而 Client 源码未变时,增量检查不会重查消费方。这一缺口与由哪一种生成写出声明无关,由 Issue #6022 跟踪。
|
||||
|
||||
### 2. pre-commit 钩子不重新生成第三方声明
|
||||
|
||||
- **改动:** [`lefthook.yml`](../../../../lefthook.yml) 中的 `pre-commit` 钩子没有第三方声明任务。[`gen-third-party-notices.spec.ts`](../../../../scripts/gen-third-party-notices.spec.ts) 在测试 lane(包括必过的 `node 24 / coverage` lane)中断言 `THIRD_PARTY_NOTICES.md` 已提交的字节,过期时指出 `pnpm run gen-third-party-notices`。[生成的第三方声明 Note](2026-07-30-generated-third-party-notices.zh.md) 拥有这一新鲜度决策。
|
||||
- **性能:** 暂存一个位于包 `src/` 子目录下的文件的提交,钩子耗时由 16.5/17.8 s 降为 4.3/4.5 s,其中第三方声明任务占 12.4/13.4 s。
|
||||
- **取舍:** 使第三方声明过期的提交会在推送后于测试 lane 失败,而不是在提交时被修正。
|
||||
|
||||
### 3. 本地默认 worker 预算
|
||||
|
||||
- **目的:** 按共享工作站或容器确定默认并行度;在这类环境中 Node 报告的是宿主 CPU 数而不是 CPU 配额。
|
||||
- **改动:** [`scripts/parallelism.ts`](../../../../scripts/parallelism.ts) 拥有默认值。`CI=true` 时它是 Node 报告的 CPU 数。否则,run-gates 调度器、`build`、`typecheck`、Oxlint 与 publint 的上限为 12(`LOCAL_PARALLELISM_CAP`),Vitest fork 与本地覆盖率预算的上限为 48(`LOCAL_TEST_PARALLELISM_CAP`)。`doc-sync`、`test:docs`、`hygiene` 与 `check:all` 的每个门禁都构建完整的 `ts.Program`,它们最多并发 8 个门禁,CI 中同样如此。显式的 `DSH_GATE_CONCURRENCY`、`DSH_OXLINT_THREADS`、`DSH_COVERAGE_MAX_WORKERS` 与 Vitest `--maxWorkers` 优先;CI 中,除非 run-gates 的 CI 环境设置了这些变量,Vitest 与 Oxlint 使用各自的默认值。[开发指南](../../../../docs/development.zh.md)向贡献者说明这些默认值。
|
||||
|
||||
四种 fork 数下的 `pnpm run test`,运行的是第 8 项所替换的落盘版 `type-model.spec.ts`,32 个 worker 那次的 wall 由它决定:
|
||||
|
||||
| Vitest worker 数 | wall | RSS 峰值 | 额外的偶发失败 | 除最慢文件外其余文件完成于 |
|
||||
|---|---|---|---|---|
|
||||
| 255(报告的 CPU 数) | 243.7 s | 55.3 GiB | 12 个文件、14 次超时 | 约 135–170 s |
|
||||
| 32 | 310.4 s | 15.7 GiB | 4 个文件、4 次超时 | 193 s |
|
||||
| 24 | 337.2 s | 13.2 GiB | 5 个文件、5 次超时 | 233 s |
|
||||
| 12 | 410.5 s | 8.4 GiB | 2 个文件、3 次超时 | 406 s |
|
||||
|
||||
- **Oxlint:** Oxlint 自身的默认值是 64 线程(读取 cgroup 配额);12 线程时其 wall 保持约 87–90 s,CPU 少约 15%;8 线程时慢约 4 s。
|
||||
- **文档聚合:** 并发 8 个门禁时 `test:docs` 为 50.9 s,并发 4 个时为 74.7 s。不含第 4 项时测得的 `doc-sync` 在并发 4、8、12 个门禁时分别为 341.8、295.0、253.2 s,RSS 峰值分别为 10.0、13.5、16.3 GiB。
|
||||
- **取舍:** CPU 配额超过上限的机器,默认并行度也不超过 12 或 48,需要使用覆盖变量;配额低于上限的容器仍会超额订阅,因为 Node 报告的是宿主 CPU 数。并发 8 个门禁时 `doc-sync` 的 RSS 峰值为 13.5 GiB,并发 4 个时为 10.0 GiB;并发 12 个门禁快 41.8 s,但峰值为 16.3 GiB。CI 的文档 workflow 运行 `doc-sync` 时同样最多并发 8 个门禁。
|
||||
|
||||
### 4. 仓库引用候选对照一次对象列表解析
|
||||
|
||||
- **改动:** [`verify-repository-references.ts`](../../../../scripts/verify-repository-references.ts) 用 `git cat-file --batch-all-objects --batch-check=%(objectname)` 一次列出全部对象名(约 120 万个对象,0.6 s),排序后在内存中对每个小写候选前缀做二分查找;随后一次 `--batch-check=%(objectname) %(objecttype)` 调用读取命中对象的类型。只有当候选前缀恰好匹配一个可用对象且该对象是 commit 时,它才算 commit 引用,这与 Git 自身前缀查找的规则相同;与 Git 的查找一样,该列表也包含不可达对象与 alternate 对象。
|
||||
- **性能:** 166.8 → 15.7 s。
|
||||
- **无损依据:** 在 27,050 个真实与合成候选上(包括歧义前缀、blob 与 tree 前缀以及随机字符串),Git 的逐候选前缀查找与内存查找的判定完全一致。
|
||||
- **取舍:** 120 万个对象的列表约为 49 MiB 的 Git 输出,读取时的输出上限为 1 GiB。
|
||||
|
||||
### 5. 文档门禁每个文档只解析一次
|
||||
|
||||
- **改动:** 下表中的每个门禁对一个 Markdown 文档只解析一次,并把语法树传给本次运行中的所有使用方。
|
||||
|
||||
| 门禁 | 单次解析机制 | wall |
|
||||
|---|---|---|
|
||||
| markdown links([`verify-md-links.ts`](../../../../scripts/verify-md-links.ts)) | 一个按运行划分的缓存对每个文件只解析一次,同时取得其 destination 与锚点,并对每个解析后的目标只探测一次 | 53.4/51.6 → 25.9/25.1 s |
|
||||
| translation pairing([`verify-translation-pairing.ts`](../../../../scripts/verify-translation-pairing.ts)) | 一次 glob 覆盖所有范围 pattern;record 在下述守卫条件下复用原文语法树 | 51.0/47.1 → 30.3/29.3 s |
|
||||
| package README model experience、package README limitations | 每项检查对一个 README 只解析一次,并把语法树传给 `markdownProseLines()` 与 `markdownHeadingLines()` | 各约 12 → 5.9 s |
|
||||
| type equivalence([`verify-type-equiv.ts`](../../../../scripts/verify-type-equiv.ts)) | 文本预筛跳过不可能含源码等价围栏的文档;manifest(元数据清单)中的每个 TypeScript 源文件只解析一次 | 23.0/22.5 → 6.0/5.5 s |
|
||||
| Session format references | persistence 渲染器把它解析出的语法树传给配对 record | 10.2 → 5.3 s |
|
||||
|
||||
- **配对复用守卫:** [`translation-pairing-record.ts`](../../../../scripts/translation-pairing-record.ts) 中的 `normalizedTopLevelBlocks()` 仅在以下条件同时成立时,才为归一化后的文本复用原文语法树:每处链接归一化编辑都替换一个完整、无 title 且不在行首开始的 destination,原文等于该节点的 `url`,且原文与替换文本都只含 `[A-Za-z0-9._/:#%-]`。这些字符既不能结束 destination,也不能开始或结束其他语法结构,因此归一化后的文本解析出相同的节点,只是偏移量随之移动。其他任何编辑都回退为对归一化文本的完整解析。
|
||||
- **type equivalence 预筛:** [`type-equiv-prefilter.ts`](../../../../scripts/type-equiv-prefilter.ts) 在文档含 `type-equiv` 或 `public-api`,或者某个含 `` ``` `` 或 `~~~` 的行同时含 `&` 或 `\` 时,保留该文档进行解析。解析只会通过解码字符引用与反斜杠转义改变信息字符串,因此 `ts type-equiv` 与 `ts type\-equiv` 所在的文档都会被保留;[`type-equiv-prefilter.spec.ts`](../../../../scripts/type-equiv-prefilter.spec.ts) 覆盖这两种写法。
|
||||
- **无损依据:** 每个门禁在仓库上的输出逐字节一致,人为注入的错误也被同样报告。对配对而言,语料中全部 1,886 个文档的顶层块与全部 943 个配对的 record 都与完整重新解析的结果一致,随机 destination 的结果也一致。
|
||||
|
||||
### 6. 仓库文件遍历每个目录只列一次
|
||||
|
||||
- **改动:** [`scripts/repo-files.ts`](../../../../scripts/repo-files.ts) 中的 `uniqueRepoFiles()` 在一次调用的所有 pattern 之间共享一个目录列表缓存,使每个目录最多读取一次,并且只对经符号链接到达的匹配调用 `realpath`;只经真实目录到达的普通文件,规范路径为仓库 realpath 拼接其相对路径。它的可选谓词 `skipDirectory` 让遍历器不进入调用方排除其下全部路径的目录;[`verify-doc-refs.ts`](../../../../scripts/verify-doc-refs.ts) 跳过第一段路径之后的每个 `lib` 目录,其下文件本来就全部被它排除。
|
||||
- **性能:** markdown wrap 25.8/25.0 → 21.3/21.2 s;doc refs 8.8/7.0 → 3.2/3.4 s;package paths 9.9/8.1 → 7.2/5.5 s。
|
||||
- **无损依据:** 三个门禁得到的文件列表逐项相同,损坏或循环的符号链接仍会经 `realpath` 失败。
|
||||
- **行为差异:** doc refs 不列出被跳过的 `lib` 目录,因此不可读的此类目录不会以 EACCES 使门禁失败。
|
||||
|
||||
### 7. CLI help 读取并发运行;doc graphs 的探测做 memo
|
||||
|
||||
- **CLI help:** [`scripts/gen-cli-help.ts`](../../../../scripts/gen-cli-help.ts) 中的 `prefetchHelp()` 在默认 worker 预算内启动 12 个顶层 `dsh … --help` 读取(启动器、`plugin`,以及每个 profile 的简写与 `--profile` 形式),每个读取使用独立的临时 `DSH_HOME` 与 `DSH_AGENTS_HOME`,并由按原顺序进行的遍历消费;嵌套读取共享同一上限。失败的读取在遍历请求该调用时才交给遍历;`close()` 中止排队与运行中的读取,并等待每个已启动的子进程结束。该门禁为 49.9/53.9 → 6.9/7.2 s。
|
||||
- **doc graphs:** [`scripts/gen-doc-graphs.ts`](../../../../scripts/gen-doc-graphs.ts) 中的 `withMemoizedFileSystemProbes()` 在 `renderDocs` 运行期间对 `ts.sys` 的 `fileExists`、`directoryExists`、`realpath`、`readDirectory` 与 `getDirectories` 做 memo,使一次运行中的所有编译器 host 与配置解析共享同一个文件系统视图。运行期间工作区不得改变,写出页面之前恢复原方法。该门禁为 48.7/44.7 → 32.7/34.2 s。
|
||||
- **无损依据:** 两个生成器生成的页面逐字节一致。
|
||||
- **取舍:** 并发的 help 进程合计峰值约占 3.6 GB 内存。
|
||||
|
||||
### 8. `type-model.spec.ts` 在内存工作区上运行
|
||||
|
||||
- **改动:** [`type-model.spec.ts`](../../../../packages/typert/generator/tests/type-model.spec.ts) 用 [`type-model-workspace.ts`](../../../../packages/typert/generator/tests/type-model-workspace.ts) 中的 `memoryFileSystem()` mock `node:fs` 与 `ts.sys` host,使内存根目录下的 fixture 复制、用例编辑、写模式注解、tsconfig 展开与模块解析都不触及磁盘。每个工作区挂载最小的 `zod` 与 `@types/node` 声明桩;只有 Emitter 用例保留真实 zod。fixture 的 `tsconfig.base.json` 设置 `lib: ["ES2024"]`,不含 DOM lib;读取未修改 fixture 的用例共享一份深度冻结的分析结果。generator 源码没有任何测试专用路径。
|
||||
- **性能:** 单独运行该文件为 316.3/329.1 → 14.65/15.04 s。
|
||||
- **行为覆盖保持不变的依据:** 61 个用例名及其断言相同。快照只有一行不同,即外部 zod 符号路径,它指向桩(`<external>:node_modules/zod/index.d.ts#ZodType`),而不是某个 pnpm store 版本。
|
||||
- **取舍:** 除 Emitter 用例外,该 spec 不针对真实文件系统、DOM lib 以及真实 zod 与 `@types/node` 声明检验分析器。内存文件系统只实现分析器使用的 `node:fs` 调用(`existsSync`、`readFileSync`、`realpathSync` 与 `writeFileSync`);对内存路径的其他调用会落到真实文件系统,而该路径并不存在。
|
||||
|
||||
### 全仓对比
|
||||
|
||||
两棵树在同一时段测量,每个命令在 `pnpm run build:artifacts` 之后交替运行基线与本实现(`pnpm run test` 在两棵树上失败的都是依赖环境的文件,基线 42 个,本实现是其中的 28 个):
|
||||
|
||||
| 命令 | 基线 | 本实现 | 变化 | 对应项 |
|
||||
|---|---|---|---|---|
|
||||
| `pre-commit` 钩子,暂存一个位于包 `src/` 子目录下的文件 | 16.5/17.8 s | 4.3/4.5 s | −75% | 2 |
|
||||
| `pnpm run typecheck`(pre-push),无需重查 | 29.7/23.3 s | 14.2/16.1 s | −43% | 1、3 |
|
||||
| `pnpm run lint` | 110.0 s | 106.7 s | −3% | 1 |
|
||||
| `pnpm run doc-typecheck` | 45.2 s | 36.1 s | −20% | 1 |
|
||||
| `pnpm run test:docs` | 102.4/104.0 s | 26.8/29.3 s | −73% | 3–6 |
|
||||
| `pnpm run doc-sync` | 186.8 s | 70.3 s | −62% | 3–7 |
|
||||
| `pnpm run test` | 222.7 s(255 个 worker) | 148.1 s(48 个 worker) | −34% | 3、8 |
|
||||
|
||||
`lint` 的耗时主要是 Oxlint 本身,其前置步骤的下降见第 1 项。CPU 时间随 wall 一同下降:`typecheck` 的 user 时间 39.5 → 14.2 s,`test:docs` 212.6 → 126.3 s,`doc-sync` 628.2 → 503.2 s,`test` 3,417 → 3,014 s。
|
||||
|
||||
## 考虑过的替代方案
|
||||
|
||||
- **所有本地默认值一律以 12 为上限,包括 Vitest fork(第 3 项):** 12 个 worker 时 `pnpm run test` 为 410.5 s,255 个时为 243.7 s,慢 68%。
|
||||
- **以 cgroup CPU 配额的一半作为本地预算(第 3 项):** 读取配额的改动更大,且只在容器内有意义。
|
||||
- **用 `worker_threads` 并行解析文档(第 5 项):** 它带来的复杂度高于每个文档只解析一次,而后者直接消除了重复工作。
|
||||
- **在 pre-commit 钩子中重新生成第三方声明(第 2 项):** 浏览器输入使每个包源码文件都成为生成器输入,钩子会让几乎每次提交都运行约 16 秒的生成器,而改变输出的提交很少;[生成的第三方声明 Note](2026-07-30-generated-third-party-notices.zh.md) 拥有该决策。
|
||||
|
||||
## 后果
|
||||
|
||||
无需重查时 pre-push `typecheck` 约 14–22 s,`lint` 与 `doc-typecheck` 的前置步骤约 12 s,改动 1 个文件的提交的钩子约 4 s。`pnpm run test` 在本地最多启动 48 个 fork,`test:docs` 与 `doc-sync` 最多同时运行 8 个门禁。Typert 输出、生成的页面、文件列表与引用判定都与基线逐字节一致。
|
||||
|
||||
代价:类型检查命令不刷新可运行的 bundle;第三方声明过期时在推送后于测试 lane 失败;本地默认值不使用超过上限的 CPU,而配额低于上限的容器仍会超额订阅;并发 8 个文档门禁抬高 `doc-sync` 的 RSS 峰值;CLI help 峰值约用 3.6 GB 内存;doc graphs 与 markdown links 假定运行期间工作树不变;除 Emitter 用例外,`type-model.spec.ts` 检验的是桩,而不是真实 zod、`@types/node`、DOM lib 与磁盘 I/O;增量 `typecheck` 继承 Issue #6022 跟踪的 Remote 声明缺口。
|
||||
|
||||
验证:`generate-typert.spec.ts` 固定与 workspace 模式插件逐字节一致的文件、对加载已编译工作区声明的 Host program 的拒绝(并指出缺失的别名),以及每个失败阶段;`compile-referenced-projects.spec.ts` 固定 `host-contracts` 的步骤及其失败报告;`build.spec.ts` 固定 typecheck scope 的步骤;`parallelism.spec.ts`、`run-gates.spec.ts` 与 `run-oxlint.spec.ts` 固定 CI 与本地预算以及覆盖变量;`repo-files.spec.ts`、`markdown.spec.ts`、`translation-pairing.spec.ts`、`type-equiv-prefilter.spec.ts`、`verify-md-links.spec.ts`、`gen-cli-help.spec.ts` 与 `gen-doc-graphs.spec.ts` 固定目录只列一次、语法树复用、配对守卫、预筛、预取顺序与失败路径,以及探测 memo 及其恢复。
|
||||
@@ -1,27 +1,25 @@
|
||||
name: Windows installer (unsigned)
|
||||
name: Windows installer
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
build_version:
|
||||
description: 'Build version: auto generates a version; otherwise enter a full version'
|
||||
type: string
|
||||
default: auto
|
||||
required: true
|
||||
deployment:
|
||||
description: Update policy deployment
|
||||
preset:
|
||||
description: 'Machine preset (configured on the packaging runner)'
|
||||
type: choice
|
||||
options: [test, production]
|
||||
default: test
|
||||
required: true
|
||||
policy_origin:
|
||||
description: 'Required update policy HTTPS origin (no path)'
|
||||
type: string
|
||||
signing:
|
||||
description: 'unsigned: test installer; signed: use the configured EV hardware token'
|
||||
type: choice
|
||||
options: [unsigned, signed]
|
||||
default: unsigned
|
||||
required: true
|
||||
login_origins:
|
||||
description: 'Required for test: comma-separated allowed login HTTPS origins'
|
||||
build_version:
|
||||
description: 'Version: auto recommended; or checkout product version / e.g. 0.2.1-alpha.1.20261009.1 (prefix must match checkout)'
|
||||
type: string
|
||||
required: false
|
||||
default: auto
|
||||
required: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -39,7 +37,20 @@ jobs:
|
||||
shell: pwsh
|
||||
env:
|
||||
DSH_TELEMETRY_DISABLED: '1'
|
||||
DSH_PACKAGING_PRESET: ${{ inputs.preset }}
|
||||
PACKAGE_SIGNING: ${{ inputs.signing }}
|
||||
steps:
|
||||
- name: Reset packaging checkout
|
||||
working-directory: ${{ runner.temp }}
|
||||
run: |
|
||||
$workspace = [IO.Path]::GetFullPath($env:GITHUB_WORKSPACE)
|
||||
$parent = [IO.Path]::GetFullPath($env:RUNNER_WORKSPACE)
|
||||
if ([IO.Path]::GetDirectoryName($workspace) -ne $parent) { throw 'Checkout must be a direct child of RUNNER_WORKSPACE' }
|
||||
for ($item = [IO.DirectoryInfo]::new($workspace); $null -ne $item; $item = $item.Parent) {
|
||||
if ($item.Exists -and ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) { throw 'Checkout ancestors cannot be links' }
|
||||
}
|
||||
node -e "const fs = require('node:fs'); fs.rmSync(process.argv[1], { recursive: true, force: true, maxRetries: 3 }); fs.mkdirSync(process.argv[1])" $workspace
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Checkout cleanup failed' }
|
||||
- uses: actions/[email protected]
|
||||
id: checkout
|
||||
with:
|
||||
@@ -55,25 +66,26 @@ jobs:
|
||||
run: |
|
||||
pnpm install --frozen-lockfile
|
||||
exit $LASTEXITCODE
|
||||
- name: Validate inputs and prepare public package settings
|
||||
- name: Validate preset and resolve build version
|
||||
id: settings
|
||||
env:
|
||||
PACKAGE_BUILD_VERSION: ${{ inputs.build_version }}
|
||||
PACKAGE_DEPLOYMENT: ${{ inputs.deployment }}
|
||||
PACKAGE_POLICY_ORIGIN: ${{ inputs.policy_origin }}
|
||||
PACKAGE_LOGIN_ORIGINS: ${{ inputs.login_origins }}
|
||||
run: node apps/desktop/scripts/prepare-windows-ci.mjs
|
||||
- name: Check packaging configuration and toolchain
|
||||
env:
|
||||
PACKAGE_VERSION: ${{ steps.settings.outputs.version }}
|
||||
run: |
|
||||
pnpm run package:desktop:win:x64:unsigned --check --build-version "$env:PACKAGE_VERSION"
|
||||
$packageArgs = @('run', 'package:desktop:win:x64', '--check', '--build-version', $env:PACKAGE_VERSION)
|
||||
if ($env:PACKAGE_SIGNING -eq 'unsigned') { $packageArgs += '--unsigned' }
|
||||
pnpm @packageArgs
|
||||
exit $LASTEXITCODE
|
||||
- name: Build installer and verify packaged runtime
|
||||
env:
|
||||
PACKAGE_VERSION: ${{ steps.settings.outputs.version }}
|
||||
run: |
|
||||
pnpm run package:desktop:win:x64:unsigned --build-version "$env:PACKAGE_VERSION"
|
||||
$packageArgs = @('run', 'package:desktop:win:x64', '--build-version', $env:PACKAGE_VERSION)
|
||||
if ($env:PACKAGE_SIGNING -eq 'unsigned') { $packageArgs += '--unsigned' }
|
||||
pnpm @packageArgs
|
||||
exit $LASTEXITCODE
|
||||
- name: Retain packaging diagnostics
|
||||
if: always() && steps.checkout.outcome == 'success'
|
||||
@@ -84,7 +96,8 @@ jobs:
|
||||
path: apps/desktop/.desktop-build/packaging-runs/
|
||||
if-no-files-found: warn
|
||||
retention-days: 14
|
||||
- name: Retain verified installer
|
||||
- name: Retain verified unsigned installer
|
||||
if: success() && inputs.signing == 'unsigned'
|
||||
uses: actions/[email protected]
|
||||
with:
|
||||
name: windows-x64-unsigned-${{ steps.settings.outputs.version }}-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
@@ -92,9 +105,12 @@ jobs:
|
||||
path: apps/desktop/.desktop-build/targets/win-x64/unsigned-artifacts/*.exe
|
||||
if-no-files-found: error
|
||||
retention-days: 14
|
||||
- name: Remove generated package settings
|
||||
if: always() && steps.checkout.outcome == 'success'
|
||||
run: |
|
||||
if (Test-Path -LiteralPath apps/desktop/.env.windows) {
|
||||
Remove-Item -LiteralPath apps/desktop/.env.windows
|
||||
}
|
||||
- name: Retain verified signed installer
|
||||
if: success() && inputs.signing == 'signed'
|
||||
uses: actions/[email protected]
|
||||
with:
|
||||
name: windows-x64-signed-${{ steps.settings.outputs.version }}-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
include-hidden-files: true
|
||||
path: apps/desktop/.desktop-build/targets/win-x64/artifacts/*.exe
|
||||
if-no-files-found: error
|
||||
retention-days: 14
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
DeepSeek Harness is licensed under [MIT](LICENSE). It depends on the third-party software listed below. Each project remains under its own license; nothing in this file changes those terms.
|
||||
|
||||
This file lists **direct** dependencies declared by the workspace, the explicitly disclosed official Claude Code platform payload closure, and the Bundled Python distributions. It is generated by `scripts/gen-third-party-notices.ts`: a pre-commit hook regenerates it whenever a staged file changes one of its inputs, and `scripts/gen-third-party-notices.spec.ts` asserts in the test lane that the committed bytes match. Deleting a manifest runs no hook, so that case is caught by the assertion instead. Run `pnpm run verify-third-party-notices` for the standalone check.
|
||||
This file lists **direct** dependencies declared by the workspace, the explicitly disclosed official Claude Code platform payload closure, and the Bundled Python distributions. It is generated by `scripts/gen-third-party-notices.ts`, and `scripts/gen-third-party-notices.spec.ts` asserts in the test lane that the committed bytes match. Run `pnpm run gen-third-party-notices` after changing one of its inputs, or `pnpm run verify-third-party-notices` for the standalone check.
|
||||
|
||||
The complete npm transitive closure, including the Landlock launcher workspace, is recorded with exact pinned versions in [`pnpm-lock.yaml`](pnpm-lock.yaml) — inspect it with `pnpm licenses list`. The Python SDK closure is recorded separately in [`python/sdk/uv.lock`](python/sdk/uv.lock).
|
||||
|
||||
|
||||
@@ -42,8 +42,8 @@
|
||||
en: 4cd8a8da6977928d
|
||||
zh: 9f624855a2edac37
|
||||
/deepseek-harness-desktop/package/release-versions:
|
||||
en: d938302f92fc3a1a
|
||||
zh: 29df50bc8791baa7
|
||||
en: fdc1fadc506d1087
|
||||
zh: 46d5cb8a60ddf7cf
|
||||
/deepseek-harness-desktop/package/local-macos-dmg-without-release-signing:
|
||||
en: 57869a5e3885f843
|
||||
zh: 7cfc01b2dcbebd78
|
||||
@@ -57,14 +57,14 @@
|
||||
en: f48baa680e841b0d
|
||||
zh: 25ded1aeaac6dad1
|
||||
/deepseek-harness-desktop/package/unsigned-windows-test-installer:
|
||||
en: fb6de542360dbae7
|
||||
zh: 0e17d7765fb10c48
|
||||
en: 2e30de3155c32344
|
||||
zh: be88a9d7f8682e75
|
||||
/deepseek-harness-desktop/package/windows-installer-interface:
|
||||
en: 1fc1db8f54475c8f
|
||||
zh: dd834ed206070396
|
||||
/deepseek-harness-desktop/package/windows-ev-signing:
|
||||
en: 64836513eb7eda6e
|
||||
zh: 6ebb9184a7aa51de
|
||||
en: 5c12ccf2f4482606
|
||||
zh: efea2cb823bda62f
|
||||
/deepseek-harness-desktop/package/desktop-runtime-preparation:
|
||||
en: 9a71990bee9867a7
|
||||
zh: 76c5c1fdff6e6908
|
||||
|
||||
+11
-5
@@ -217,9 +217,9 @@ A production release publishes the product version and takes no `--build-version
|
||||
|
||||
Version derivation does not change the fixed update channel or `nightly.yml` / `nightly-mac.yml` filenames. SemVer orders `0.1.6-alpha.1 < 0.1.6-alpha.1.20260916.1 < 0.1.6-alpha.2`, and a stable base's test version precedes that stable release. Clients only accept a greater version: replacing a feed cannot move an installed higher version to a lower corrected version. Such clients need manual installation; keep automatic downgrade disabled. The [archived version decision](../../.agents/notes/archived/process/2026-09-16-desktop-release-version-derivation.md) explains why the channel does not supply the prerelease identifier.
|
||||
|
||||
Except for local unsigned macOS builds, packaging, upload, and manual macOS signature verification read `apps/desktop/.env.windows` or `.env.macos`, selected by target platform. Copy the [Windows template](.env.windows.example) or [macOS template](.env.macos.example) and fill in the local settings; Git ignores both local files, and packaged artifacts exclude them. Release fields come only from the target file, without fallback to system or shell variables; `PATH`, proxies, and build-tool settings remain inherited. The published version is an argument rather than a release field, and upload reads it from the completion record the packaging run wrote. Files use UTF-8 with optional BOM; relative certificate, SignTool, Apple API key, and keychain paths resolve from `apps/desktop`, values are not shell-expanded, and passwords containing `#` or spaces need quotes. CI also creates the target file before invoking packaging.
|
||||
Except for Windows packaging with a selected machine preset and local unsigned macOS builds, packaging, upload, and manual macOS signature verification read `apps/desktop/.env.windows` or `.env.macos`, selected by target platform. Copy the [Windows template](.env.windows.example) or [macOS template](.env.macos.example) and fill in the local settings; Git ignores both local files, and packaged artifacts exclude them. Release fields come only from the selected configuration files, without fallback to system or shell variables; `PATH`, proxies, and build-tool settings remain inherited. The published version is an argument rather than a release field, and upload reads it from the completion record the packaging run wrote. Files use UTF-8 with optional BOM; relative certificate, SignTool, Apple API key, and keychain paths resolve from `apps/desktop`, values are not shell-expanded, and passwords containing `#` or spaces need quotes. Windows CI reads machine presets as described below.
|
||||
|
||||
Every package command checks the application ID and its mode-specific update and signing configuration before building or downloading, then probes the external tools the run will use: the archive reader, and on a Windows target the installer compiler. macOS checks the identity, Team ID, one complete notarization strategy, readable local `CSC_LINK` p12 file, explicit `CSC_KEY_PASSWORD`, and referenced API key and keychain files; Windows checks the public code-signing certificate, SignTool file, container name, and PIN format. Windows preparation-only builds and explicit unsigned builds on either platform do not require signing credentials. Configuration checks do not authenticate the PIN, log in to the token, unlock a keychain, or contact Apple; actual signing and notarization perform those checks. `--build-version auto` does contact the destination bucket, including under `--check`. Run the same checks separately:
|
||||
Every package command checks the application ID and its mode-specific update and signing configuration before building or downloading, then probes the external tools the run will use: the archive reader, and on a Windows target the installer compiler. macOS checks the identity, Team ID, one complete notarization strategy, readable local `CSC_LINK` p12 file, explicit `CSC_KEY_PASSWORD`, and referenced API key and keychain files; Windows checks the public code-signing certificate, SignTool file, container name, and PIN format. Windows preparation-only builds and explicit unsigned builds on either platform do not require signing credentials. Configuration checks do not authenticate the PIN, log in to the token, unlock a keychain, or contact Apple; actual signing and notarization perform those checks. Without a Windows machine preset, `--build-version auto` contacts the destination bucket, including under `--check`. Run the same checks separately:
|
||||
|
||||
```sh
|
||||
pnpm --dir apps/desktop run check:package
|
||||
@@ -364,9 +364,15 @@ The command reads `.env.windows` and requires `DSH_DESKTOP_APP_ID` and the [mand
|
||||
|
||||
Run `pnpm install --frozen-lockfile`, then `pnpm run package:desktop:win:x64:unsigned --check` to validate configuration and tooling before the full command above. Packaging performs its own complete build and isolated runtime smoke without an online model. Stage logs remain under `.desktop-build/packaging-runs/`; a successful build alone does not qualify the installer. Dependency installation and runtime preparation need access to npm, GitHub release assets and nodejs.org; use the existing registry and proxy configuration when the network requires it. Caches and tool locations belong to the build machine, not tracked personal paths.
|
||||
|
||||
The [manual Windows workflow](../../.github/workflows/windows-package.yml) selects a self-hosted Windows x64 runner with the dedicated `dsh-win-package-trial` label and calls the same unsigned command. Provision PowerShell 7 and the tools listed above before starting the runner. It requires the policy deployment and HTTPS origin; test deployments also require comma-separated login origins. These public inputs generate a temporary `.env.windows` without signing or upload credentials. `build_version` defaults to `auto`, using the CI identifier described in [Release versions](#release-versions). An explicit version uses the existing product-version validator. The resolved version appears in the run summary before packaging; manifests remain unchanged.
|
||||
The [manual Windows workflow](../../.github/workflows/windows-package.yml) selects the dedicated Windows x64 runner label `dsh-win-package-trial` and the machine preset `test` or `production`. Choose `unsigned` (default) or `signed`; signed mode uses the existing EV token preflight, signature cache and failure interlock. It does not publish or upload a release. `build_version` defaults to `auto`, using the CI identifier in [Release versions](#release-versions); an explicit value may be the checkout's product version or an extended build version such as `0.2.1-alpha.1.20261009.1` for product `0.2.1-alpha.1`. The version prefix must match the selected checkout; validation errors show its current example. Manifests remain unchanged.
|
||||
|
||||
After this workflow reaches the default branch, select it in Actions, choose the source branch, fill the inputs and click Run workflow. It has no push or PR trigger and leaves existing automatic CI unchanged. Packaging logs and successful EXE artifacts are retained for 14 days; installation, signing and publication are separate operations. Run it once from the default branch and inspect the retained logs and installer before relying on Actions packaging. Checkout cleans the runner-owned source directory, including ignored files; never point it at a development checkout. Runs share one concurrency group without cancelling an active build; only one run can remain pending, and a newer dispatch replaces that pending run. Diagnostics are uploaded only after a successful clean checkout, and generated settings are removed even when preparation fails after writing them.
|
||||
Select the workflow in Actions, choose the source branch, preset, signing mode and version, then click Run workflow. Before merging input changes, test the pushed branch with `gh workflow run windows-package.yml --ref <branch> -f preset=test -f signing=unsigned -f build_version=auto`; verify the web form after merging. There is no push or PR trigger. Logs and successful EXEs are retained for 14 days. Inspect the retained logs and installer before relying on packaging; installation is separate. Before checkout, Node removes the runner-owned source directory without following dependency junctions; the workflow validates its location and rejects linked ancestors. Never point it at a development checkout. Runs share one concurrency group without cancelling an active build; only one run remains pending, and a newer dispatch replaces it. Diagnostics upload requires a successful clean checkout. Machine settings stay outside the checkout and are never uploaded as artifacts.
|
||||
|
||||
The shared packaging runner assumes trusted internal-team code and operators. Under this assumption, credential and device isolation are deferred and the residual risk is accepted (tracked in #5973); signed/master-only access is not enforced. Unsigned mode skips signing-file loading but cannot prevent branch code running as the same Windows account from reading those files or accessing the token. SafeNet Single Logon may reuse authentication. Direct device calls can bypass the signing scripts and exhaust PIN retries; the persistent failure interlock only protects calls through those scripts. Cross-account token isolation and remaining retry counts are unverified. Reassess runner/account/device isolation before expanding access, executing untrusted contributions, changing runner sharing, or after suspicious activity.
|
||||
|
||||
Set `DSH_PACKAGING_CONFIG_DIR` to the absolute machine configuration directory and `DSH_PACKAGING_PRESET` to `test` or `production` for local Windows commands. The loader reads `presets/<preset>.env`; signed commands additionally read `secrets/windows-signing.env`. Relative certificate and SignTool paths resolve beside the file declaring them. Public presets reject credentials, and the signing file cannot override public settings. Missing configuration fails without falling back to `.env.windows`; commands without a preset retain the existing dotenv behavior. Unsigned and preparation-only presets never read the signing file. Cache maintenance also reads only public preset settings. Test signed packages also require the existing download origin and release ID, but no upload credentials. Local preset commands with `--build-version auto` number from local artifacts only; Actions uses its run number and attempt.
|
||||
|
||||
Run `pwsh -NoProfile -File apps/desktop/scripts/setup-windows-packaging.ps1 -Root <absolute-machine-root>` to prepare private `packaging/{presets,secrets,certificates}` and `cache/windows-signatures` directories and copy templates without overwriting existing files. Add `-CheckOnly` to inspect without writes. Fill the [preset templates](config/windows-packaging/test.env.example) and [signing template](config/windows-packaging/windows-signing.env.example) on the machine. Run `start-windows-packaging-runner.ps1 -RunnerRoot <registered-runner-directory> -ConfigRoot <machine-root>/packaging -CheckOnly` from the same scripts directory to inspect PowerShell 7.6.6 under the runner's `tools` directory, Node, Python, Git, tar and Visual C++ tools; packaging `--check` performs the remaining toolchain validation. Omit `-CheckOnly` to start the existing runner with an explicit config root and scrubbed inherited environment. Registration and tool installation are separate; these scripts never create tokens, alter system security settings or clear signing failure records. Use the signing cache maintenance command below to migrate existing entries before changing the preset's cache path.
|
||||
|
||||
<a id="windows-uninstall-rules"></a>
|
||||
|
||||
@@ -422,7 +428,7 @@ Insert and unlock the token before packaging. The electron-builder hook passes e
|
||||
|
||||
Timestamp completion retries only a normally exited timestamp command returning failure or warning, at most three times with one- and two-second delays. Each attempt starts from the same verified primary signature. Launch errors, uncertain termination and verification failures stop immediately. SignTool operates on short private paths; publication copies verified bytes to the target volume before atomic replacement. Final Windows trust, certificate, timestamp and normalized full-file equality are required. Exhaustion stops packaging and preserves evidence without another hardware call. See the [signature completion decision](../../.agents/notes/implemented/process/2026-09-17-windows-signature-completion.md).
|
||||
|
||||
The PIN cannot contain `]`, a quote, or a line break because those characters delimit the SafeNet `/kc` value or its CMD argument. The CMD disables delayed expansion so a PIN containing `!` reaches SafeNet unchanged. Packaging withholds every `DSH_DESKTOP_WINDOWS_*` field from build and runtime-preparation subprocesses, gives signing preflight, the dedicated runtime signing stages and electron-builder only the four configured inputs, gives the signing CMD only the validated signing fields in an otherwise scrubbed environment, clears those fields before SignTool starts, and redacts SignTool diagnostics. SafeNet still requires the PIN in the SignTool process command line. The local `.env.windows` stores the PIN in plaintext and needs restricted file access; CI uses a temporary file and deletes it after the job. Do not commit or share its contents or print credentials in logs. Configuration checks consume no token PIN attempts; signing still stops the batch on its first failure.
|
||||
The PIN cannot contain `]`, a quote, or a line break because those characters delimit the SafeNet `/kc` value or its CMD argument. The CMD disables delayed expansion so a PIN containing `!` reaches SafeNet unchanged. Packaging withholds every `DSH_DESKTOP_WINDOWS_*` field from build and runtime-preparation subprocesses, gives signing preflight, the dedicated runtime signing stages and electron-builder only the four configured inputs, gives the signing CMD only the validated signing fields in an otherwise scrubbed environment, clears those fields before SignTool starts, and redacts SignTool diagnostics. SafeNet still requires the PIN in the SignTool process command line. The local `.env.windows` or machine-owned `secrets/windows-signing.env` stores the PIN in plaintext and needs restricted file access. CI reads the machine-owned file outside the checkout and retains it across jobs. Do not commit or share its contents or print credentials in logs. Configuration checks consume no token PIN attempts; signing still stops the batch on its first failure.
|
||||
|
||||
Create a runnable application directory instead of an installer by using the matching `:dir` command, such as:
|
||||
|
||||
|
||||
@@ -219,9 +219,9 @@ production 发布使用产品版本本身,不传 `--build-version`。其上传
|
||||
|
||||
版本派生不改变固定更新通道,也不改变 `nightly.yml` / `nightly-mac.yml` 文件名。SemVer 排序为 `0.1.6-alpha.1 < 0.1.6-alpha.1.20260916.1 < 0.1.6-alpha.2`,稳定基础版本的测试版低于该稳定版。客户端只接受更高版本:替换 feed 无法让已安装的较高版本更新到较低的纠正版。这类客户端需要手动安装;保持自动降级关闭。[已归档的版本决策](../../.agents/notes/archived/process/2026-09-16-desktop-release-version-derivation.md)解释为什么不能用通道名替换预发布标识。
|
||||
|
||||
除本地 macOS 未签名构建外,打包、上传以及手动 macOS 签名检查使用 `apps/desktop/.env.windows` 或 `.env.macos`,由目标平台选择。复制对应的 [Windows 模板](.env.windows.example) 或 [macOS 模板](.env.macos.example),填写本机配置;Git 忽略这两个本地文件,安装产物也不包含它们。发布字段只从目标文件读取,不回退到系统或 shell 中的同名变量;`PATH`、代理和构建工具环境仍保留。发布版本是命令参数而非发布字段,上传从打包写下的完成记录中读取它。文件使用 UTF-8,支持 BOM;相对证书、SignTool、Apple API Key 和钥匙串路径以 `apps/desktop` 为基准,变量值不做 shell 展开,包含 `#` 或空格的密码需要引号。CI 同样在运行前生成目标文件。
|
||||
除选择机器 preset 的 Windows 打包和本地 macOS 未签名构建外,打包、上传以及手动 macOS 签名检查使用 `apps/desktop/.env.windows` 或 `.env.macos`,由目标平台选择。复制对应的 [Windows 模板](.env.windows.example) 或 [macOS 模板](.env.macos.example),填写本机配置;Git 忽略这两个本地文件,安装产物也不包含它们。发布字段只从选定的配置文件读取,不回退到系统或 shell 中的同名变量;`PATH`、代理和构建工具环境仍保留。发布版本是命令参数而非发布字段,上传从打包写下的完成记录中读取它。文件使用 UTF-8,支持 BOM;相对证书、SignTool、Apple API Key 和钥匙串路径以 `apps/desktop` 为基准,变量值不做 shell 展开,包含 `#` 或空格的密码需要引号。Windows CI 读取下文说明的机器 preset。
|
||||
|
||||
每条打包命令在构建与下载前检查应用 ID 以及该模式需要的更新与签名配置,随后探测本次运行要用的外部工具:归档读取工具,以及 Windows 目标的安装器编译器。macOS 检查身份、Team ID、一套完整公证凭据、`CSC_LINK` 指定的可读本地 p12 文件、显式配置的 `CSC_KEY_PASSWORD`,以及引用的 API Key 和钥匙串文件;Windows 检查公开代码签名证书、SignTool 文件、容器名称和 PIN 格式。仅准备 Windows 资源以及两个平台上的显式未签名打包均不要求签名凭据。配置检查不验证 PIN 是否正确、Token 是否登录、钥匙串是否解锁或 Apple 是否接受凭据;实际签名与公证负责这些检查。`--build-version auto` 会访问目标 bucket,`--check` 下同样如此。单独运行相同检查:
|
||||
每条打包命令在构建与下载前检查应用 ID 以及该模式需要的更新与签名配置,随后探测本次运行要用的外部工具:归档读取工具,以及 Windows 目标的安装器编译器。macOS 检查身份、Team ID、一套完整公证凭据、`CSC_LINK` 指定的可读本地 p12 文件、显式配置的 `CSC_KEY_PASSWORD`,以及引用的 API Key 和钥匙串文件;Windows 检查公开代码签名证书、SignTool 文件、容器名称和 PIN 格式。仅准备 Windows 资源以及两个平台上的显式未签名打包均不要求签名凭据。配置检查不验证 PIN 是否正确、Token 是否登录、钥匙串是否解锁或 Apple 是否接受凭据;实际签名与公证负责这些检查。未选择 Windows 机器 preset 时,`--build-version auto` 会访问目标 bucket,`--check` 下同样如此。单独运行相同检查:
|
||||
|
||||
```sh
|
||||
pnpm --dir apps/desktop run check:package
|
||||
@@ -366,9 +366,15 @@ pnpm run package:desktop:win:x64:unsigned
|
||||
|
||||
先运行 `pnpm install --frozen-lockfile`,再运行 `pnpm run package:desktop:win:x64:unsigned --check` 校验配置和工具,最后执行上面的完整命令。打包自行执行完整构建和隔离的运行时 smoke,不调用在线模型。阶段日志保留在 `.desktop-build/packaging-runs/`;仅构建成功不代表安装包验证通过。依赖安装和运行时准备需要访问 npm、GitHub release 资源和 nodejs.org;网络需要时使用现有 registry 和代理配置。缓存与工具位置属于构建机器配置,不在跟踪文件中固定个人路径。
|
||||
|
||||
[Windows 手动工作流](../../.github/workflows/windows-package.yml) 选择带有专用标签 `dsh-win-package-trial` 的自托管 Windows x64 runner,并调用同一个未签名命令。启动 runner 前需准备 PowerShell 7 和上述工具。必须填写策略部署环境和 HTTPS origin;测试部署还需填写逗号分隔的登录 origin。这些公开输入生成临时 `.env.windows`,不包含签名或上传凭据。`build_version` 默认为 `auto`,使用[发布版本](#release-versions)中说明的 CI 标识。显式版本复用现有产品版本校验器。解析后的版本在打包前显示于运行摘要,manifest 保持不变。
|
||||
[Windows 手动工作流](../../.github/workflows/windows-package.yml) 选择专用 Windows x64 runner 标签 `dsh-win-package-trial`,并使用机器 preset `test` 或 `production`。选择 `unsigned`(默认)或 `signed`;签名模式复用现有 EV token 预检、签名缓存与失败 interlock,不发布或上传 release。`build_version` 默认为 `auto`,使用[发布版本](#release-versions)中的 CI 标识;显式值可以是源码产品版本,或扩展构建版本,例如产品 `0.2.1-alpha.1` 对应 `0.2.1-alpha.1.20261009.1`。版本前缀必须匹配所选源码;校验错误显示其当前示例。manifest 保持不变。
|
||||
|
||||
工作流进入默认分支后,在 Actions 中选择它,选择源码分支、填写输入并点击 Run workflow。它不监听 push 或 PR,不改变现有自动 CI。打包日志和成功生成的 EXE 产物保留 14 天;安装、签名和发布是独立操作。依赖 Actions 打包前,先从默认分支运行一次,并检查保留的日志和安装包。Checkout 会清理 runner 专用源码目录,包括被忽略的文件;不得指向日常开发目录。运行共享一个并发组,不取消正在进行的构建;最多保留一个待运行任务,新的手动触发会替换该待运行任务。仅在成功完成干净检出后上传诊断日志;即使配置准备在写入后失败,也会清理生成的配置。
|
||||
在 Actions 选择工作流、源码分支、preset、签名模式和版本,再点击 Run workflow。输入变更合并前,用 `gh workflow run windows-package.yml --ref <branch> -f preset=test -f signing=unsigned -f build_version=auto` 测试已推送分支;合并后验证网页表单。它不监听 push 或 PR。日志和成功生成的 EXE 保留 14 天。依赖打包流程前检查日志和安装包;安装是独立操作。检出前,Node 删除 runner 专用源码目录,不跟随依赖 junction;工作流校验目标位置并拒绝链接祖先目录。不得指向日常开发目录。运行共享一个并发组,不取消正在进行的构建;最多保留一个待运行任务,新触发会替换它。仅在成功完成干净检出后上传诊断。机器配置位于 checkout 之外,不作为产物上传。
|
||||
|
||||
共享打包 runner 以内部团队代码和操作人员可信为前提。在此前提下,凭据和设备隔离暂缓实施,剩余风险按已知风险接受(由 #5973 跟踪);尚未强制限制仅 signed/master 可访问。未签名模式跳过签名文件加载,但无法阻止同一 Windows 账户下的分支代码读取这些文件或访问 Token。SafeNet Single Logon 可能复用认证状态。直接调用设备可以绕过签名脚本并耗尽 PIN 重试次数;持久失败 interlock 只保护经过这些脚本的调用。跨账户 Token 隔离和剩余重试次数尚未验证。扩大访问范围、执行不可信贡献、改变 runner 共享方式前,或出现可疑活动后,重新评估 runner、账户和设备隔离。
|
||||
|
||||
本地 Windows 命令通过 `DSH_PACKAGING_CONFIG_DIR` 指定机器配置绝对目录,通过 `DSH_PACKAGING_PRESET` 选择 `test` 或 `production`。加载器读取 `presets/<preset>.env`;签名命令另读 `secrets/windows-signing.env`。相对证书和 SignTool 路径以声明它们的文件所在目录为基准。公开 preset 拒绝凭据,签名文件不能覆盖公开配置。配置缺失立即失败,不回退到 `.env.windows`;不选择 preset 的命令保留原 dotenv 行为。未签名和仅准备 preset 不读取签名文件。缓存维护也只读取公开 preset 配置。签名测试包还需现有下载 origin 和 release ID,但无需上传凭据。本地 preset 命令使用 `--build-version auto` 时仅按本地产物编号;Actions 使用运行编号和重试次数。
|
||||
|
||||
运行 `pwsh -NoProfile -File apps/desktop/scripts/setup-windows-packaging.ps1 -Root <absolute-machine-root>` 创建私有 `packaging/{presets,secrets,certificates}` 和 `cache/windows-signatures` 目录并复制模板,不覆盖现有文件。添加 `-CheckOnly` 只检查不写入。在机器上填写 [preset 模板](config/windows-packaging/test.env.example)和[签名模板](config/windows-packaging/windows-signing.env.example)。从同一 scripts 目录运行 `start-windows-packaging-runner.ps1 -RunnerRoot <registered-runner-directory> -ConfigRoot <machine-root>/packaging -CheckOnly`,检查 runner 的 `tools` 目录下 PowerShell 7.6.6、Node、Python、Git、tar 和 Visual C++ 工具;打包 `--check` 完成其余工具链检查。省略 `-CheckOnly`,以显式配置目录和清理后的继承环境启动现有 runner。注册和工具安装单独进行;这些脚本不创建 token、不改系统安全设置、不清除签名失败记录。修改 preset 缓存路径前,使用下文签名缓存维护命令迁移已有条目。
|
||||
|
||||
<a id="windows-uninstall-rules"></a>
|
||||
|
||||
@@ -424,7 +430,7 @@ pnpm run package:desktop:win:x64
|
||||
|
||||
时间戳处理仅对正常退出但返回失败或警告的时间戳命令重试,最多尝试三次,间隔为一秒和两秒。每次均从同一份已验证的主签名开始。启动错误、终止状态不确定或验签失败会立即停止。SignTool 使用短的私有路径;发布时先把已验证字节复制到目标卷,再原子替换。最终必须通过 Windows 信任、证书、时间戳和规范化全文件相等检查。尝试耗尽后停止打包并保留证据,不再次调用硬件。参见[签名完成决策](../../.agents/notes/implemented/process/2026-09-17-windows-signature-completion.zh.md)。
|
||||
|
||||
PIN 不能包含 `]`、引号或换行,因为这些字符用于分隔 SafeNet `/kc` 值或对应的 CMD 参数。CMD 会禁用延迟展开,因此包含 `!` 的 PIN 可以原样到达 SafeNet。打包流程不会把任何 `DSH_DESKTOP_WINDOWS_*` 字段传给构建与 运行时准备子进程;它只向签名预检、独立的第一方运行时签名阶段与 electron-builder 提供四个配置输入,在其他字段已经清理的环境中只向签名 CMD 提供经过校验的签名字段,在 SignTool 启动前清除这些字段,并遮盖 SignTool 诊断。SafeNet 仍要求 PIN 出现在 SignTool 进程命令行中。本地 `.env.windows` 明文保存 PIN,应限制文件访问权限;CI 使用临时文件并在任务结束后删除。不要提交或分享文件内容,也不要把凭据写入日志。配置检查不会消耗 Token 的 PIN 尝试次数;签名仍在首次失败后停止整批任务。
|
||||
PIN 不能包含 `]`、引号或换行,因为这些字符用于分隔 SafeNet `/kc` 值或对应的 CMD 参数。CMD 会禁用延迟展开,因此包含 `!` 的 PIN 可以原样到达 SafeNet。打包流程不会把任何 `DSH_DESKTOP_WINDOWS_*` 字段传给构建与 运行时准备子进程;它只向签名预检、独立的第一方运行时签名阶段与 electron-builder 提供四个配置输入,在其他字段已经清理的环境中只向签名 CMD 提供经过校验的签名字段,在 SignTool 启动前清除这些字段,并遮盖 SignTool 诊断。SafeNet 仍要求 PIN 出现在 SignTool 进程命令行中。本地 `.env.windows` 或机器管理的 `secrets/windows-signing.env` 明文保存 PIN,应限制文件访问权限。CI 读取 checkout 外的机器签名文件,并在任务结束后保留。不要提交或分享文件内容,也不要把凭据写入日志。配置检查不会消耗 Token 的 PIN 尝试次数;签名仍在首次失败后停止整批任务。
|
||||
|
||||
使用对应的 `:dir` 命令可以生成可直接运行的应用目录,而不是安装包,例如:
|
||||
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
# Copy to production.env in the same machine configuration directory and fill in the values.
|
||||
DSH_DESKTOP_APP_ID=com.deepseek.harness
|
||||
DSH_DESKTOP_AUTO_UPDATE_ENV=production
|
||||
DSH_DESKTOP_MANDATORY_UPDATE_PROD_ORIGIN=
|
||||
DSH_DESKTOP_MANDATORY_UPDATE_CONFIG='{}'
|
||||
# DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_DIR=
|
||||
DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_CONCURRENCY=4
|
||||
@@ -0,0 +1,13 @@
|
||||
# Copy to test.env in the same machine configuration directory and fill in the values.
|
||||
# Public test configuration. No PIN or upload credentials belong here.
|
||||
DSH_DESKTOP_APP_ID=com.deepseek.harness
|
||||
DSH_DESKTOP_AUTO_UPDATE_ENV=test
|
||||
DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN=
|
||||
# Replace login.example.com with the real login origin before packaging.
|
||||
DSH_DESKTOP_MANDATORY_UPDATE_CONFIG='{"allowedAuthOrigins":["https://login.example.com"]}'
|
||||
# Required for signed test packages; retain the release ID for an upgrade test batch.
|
||||
DOWNLOAD_TEST_ORIGIN=
|
||||
DOWNLOAD_TEST_RELEASE_ID=
|
||||
# Optional absolute private cache directory. Omit to retain the account default cache.
|
||||
# DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_DIR=
|
||||
DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_CONCURRENCY=4
|
||||
@@ -0,0 +1,7 @@
|
||||
# Copy to windows-signing.env in the same machine configuration directory and fill in the values.
|
||||
# Restrict this file to the runner account, SYSTEM and administrators.
|
||||
# File paths resolve relative to this file; use the same account as local signing.
|
||||
DSH_DESKTOP_WINDOWS_CER_FILE=../certificates/windows.cer
|
||||
DSH_DESKTOP_WINDOWS_SIGNTOOL=
|
||||
DSH_DESKTOP_WINDOWS_KEY_CONTAINER=
|
||||
DSH_DESKTOP_WINDOWS_TOKEN_PIN=
|
||||
@@ -8,16 +8,18 @@
|
||||
export function localMacOSPackageEnvironment(environment?: NodeJS.ProcessEnv): NodeJS.ProcessEnv
|
||||
|
||||
/**
|
||||
* Read the target's required UTF-8 dotenv file; release settings never fall back to ambient values.
|
||||
* Read a Windows machine preset when selected, otherwise the target's required dotenv; no ambient release fallback.
|
||||
* @param platform Target platform.
|
||||
* @param environment Parent environment, retained only for unrelated build tools.
|
||||
* @param appRoot Desktop application directory; relative credential paths resolve here.
|
||||
* @param options Unsigned and preparation-only presets never read signing credentials.
|
||||
* @returns Isolated environment with file-owned release settings.
|
||||
*/
|
||||
export function loadDesktopPackageEnvironment(
|
||||
platform: 'win32' | 'darwin',
|
||||
environment?: NodeJS.ProcessEnv,
|
||||
appRoot?: string,
|
||||
options?: { unsigned?: boolean, prepareOnly?: boolean },
|
||||
): NodeJS.ProcessEnv
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/** Select local test defaults or platform release settings without changing the caller's environment. */
|
||||
|
||||
import { accessSync, constants, readFileSync, statSync } from 'node:fs'
|
||||
import { dirname, join, resolve } from 'node:path'
|
||||
import { dirname, isAbsolute, join, resolve } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { parseEnv } from 'node:util'
|
||||
import { resolveDesktopAppId, resolveMacOSNotarizationEnvironment, resolveMacOSSigningEnvironment, resolveNpmRegistry } from './desktop-release-environment.mjs'
|
||||
@@ -33,14 +33,46 @@ export function localMacOSPackageEnvironment(environment = process.env) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the target's required UTF-8 dotenv file; release settings never fall back to ambient values.
|
||||
* Read a Windows machine preset when selected, otherwise the target's required dotenv; no ambient release fallback.
|
||||
* @param {'win32' | 'darwin'} platform Target platform.
|
||||
* @param {NodeJS.ProcessEnv} environment Parent environment, retained only for unrelated build tools.
|
||||
* @param {string} appRoot Desktop application directory; relative credential paths resolve here.
|
||||
* @param {{ unsigned?: boolean, prepareOnly?: boolean }} options Unsigned and preparation-only presets never read signing credentials.
|
||||
* @returns {NodeJS.ProcessEnv} Isolated environment with file-owned release settings.
|
||||
*/
|
||||
export function loadDesktopPackageEnvironment(platform, environment = process.env, appRoot = APP_ROOT) {
|
||||
const path = join(appRoot, platform === 'win32' ? '.env.windows' : '.env.macos')
|
||||
export function loadDesktopPackageEnvironment(platform, environment = process.env, appRoot = APP_ROOT, options = {}) {
|
||||
const preset = environment.DSH_PACKAGING_PRESET
|
||||
let path = join(appRoot, platform === 'win32' ? '.env.windows' : '.env.macos')
|
||||
if (preset !== undefined) {
|
||||
if (platform !== 'win32') throw new Error('desktop package: presets support Windows only')
|
||||
if (preset !== 'test' && preset !== 'production') throw new Error('desktop package: preset must be test or production')
|
||||
const root = environment.DSH_PACKAGING_CONFIG_DIR
|
||||
if (!root || !isAbsolute(root)) throw new Error('desktop package: DSH_PACKAGING_CONFIG_DIR must be an absolute directory')
|
||||
path = join(root, 'presets', `${preset}.env`)
|
||||
}
|
||||
const platformSetting = platform === 'win32' ? WINDOWS_SETTING : MACOS_SETTING
|
||||
const settings = readSettings(path, name => preset === undefined
|
||||
? SHARED_SETTING.test(name) || platformSetting.test(name)
|
||||
: /^(?:DSH_DESKTOP_(?:APP_ID|AUTO_UPDATE_ENV|NPM_REGISTRY|MANDATORY_UPDATE_(?:CONFIG|(?:TEST|PROD)_ORIGIN)|WINDOWS_SIGNATURE_CACHE_(?:DIR|CONCURRENCY))|DOWNLOAD_TEST_(?:ORIGIN|RELEASE_ID))$/u.test(name))
|
||||
if (preset !== undefined) {
|
||||
if (settings.DSH_DESKTOP_AUTO_UPDATE_ENV !== preset) throw new Error('desktop package: preset deployment must match its name')
|
||||
if (!options.unsigned && !options.prepareOnly) Object.assign(settings, readSettings(join(dirname(dirname(path)), 'secrets', 'windows-signing.env'),
|
||||
name => /^DSH_DESKTOP_WINDOWS_(?:CER_FILE|SIGNTOOL|KEY_CONTAINER|TOKEN_PIN)$/u.test(name)))
|
||||
}
|
||||
return {
|
||||
...Object.fromEntries(Object.entries(environment).filter(([name]) => !AMBIENT_RELEASE_SETTING.test(name))),
|
||||
...settings,
|
||||
...(preset === undefined ? {} : { DSH_PACKAGING_PRESET: preset }),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read an explicitly selected dotenv without exposing credential-bearing parser errors.
|
||||
* @param {string} path Selected file; relative file settings resolve beside it.
|
||||
* @param {(name: string) => boolean} accepts Whether this file may declare a setting.
|
||||
* @returns {NodeJS.ProcessEnv} Validated file settings.
|
||||
*/
|
||||
function readSettings(path, accepts) {
|
||||
let contents
|
||||
try {
|
||||
contents = readFileSync(path, 'utf8')
|
||||
@@ -56,9 +88,8 @@ export function loadDesktopPackageEnvironment(platform, environment = process.en
|
||||
// Parser diagnostics can contain credential-bearing input.
|
||||
throw new Error(`desktop package: invalid dotenv syntax in ${path}`)
|
||||
}
|
||||
const platformSetting = platform === 'win32' ? WINDOWS_SETTING : MACOS_SETTING
|
||||
for (const name of Object.keys(settings)) {
|
||||
if (!SHARED_SETTING.test(name) && !platformSetting.test(name)) {
|
||||
if (!accepts(name)) {
|
||||
throw new Error(`desktop package: unsupported setting ${name} in ${path}; use the platform template`)
|
||||
}
|
||||
if (settings[name].includes('\0')) throw new Error(`desktop package: ${name} cannot contain a NUL character`)
|
||||
@@ -66,10 +97,7 @@ export function loadDesktopPackageEnvironment(platform, environment = process.en
|
||||
for (const name of FILE_SETTINGS) {
|
||||
if (settings[name]?.trim()) settings[name] = resolve(dirname(path), settings[name].trim())
|
||||
}
|
||||
return {
|
||||
...Object.fromEntries(Object.entries(environment).filter(([name]) => !AMBIENT_RELEASE_SETTING.test(name))),
|
||||
...settings,
|
||||
}
|
||||
return settings
|
||||
}
|
||||
|
||||
function requireReadableFile(environment, name) {
|
||||
|
||||
@@ -11,7 +11,7 @@ const { values } = parseArgs({ options: {
|
||||
if ([values.from !== undefined, values.usage === true, values.clear === true].filter(Boolean).length !== 1) {
|
||||
throw new Error('Specify exactly one of --from <old-cache>, --usage or --clear')
|
||||
}
|
||||
const environment = values.directory === undefined ? loadDesktopPackageEnvironment('win32')
|
||||
const environment = values.directory === undefined ? loadDesktopPackageEnvironment('win32', process.env, undefined, { unsigned: true })
|
||||
: { DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_DIR: values.directory }
|
||||
const root = resolveWindowsSignatureCacheDirectory(environment)
|
||||
const record = event => process.stdout.write(`${JSON.stringify(event)}\n`)
|
||||
|
||||
@@ -322,7 +322,9 @@ async function resolveRequestedBuildVersion(
|
||||
if (requested !== AUTOMATIC_BUILD_VERSION) return validateDesktopBuildVersion(requested, productVersion)
|
||||
const paths = desktopTargetBuildPaths(invocation.target.name)
|
||||
return suggestDesktopBuildVersion({
|
||||
productVersion, target: invocation.target.name, environment,
|
||||
productVersion, target: invocation.target.name,
|
||||
// Machine presets own packaging, not upload credentials; local auto numbering uses existing artifacts.
|
||||
environment: environment.DSH_PACKAGING_PRESET === undefined ? environment : {},
|
||||
// Unsigned builds land beside the signed output, so numbering has to read the directory this run writes.
|
||||
artifactsRoot: invocation.unsigned ? paths.unsignedArtifacts : paths.artifacts,
|
||||
})
|
||||
@@ -333,9 +335,11 @@ async function main(): Promise<void> {
|
||||
const { target } = invocation
|
||||
const environment = target.platform === 'darwin' && invocation.unsigned
|
||||
? localMacOSPackageEnvironment()
|
||||
: loadDesktopPackageEnvironment(target.platform)
|
||||
: loadDesktopPackageEnvironment(target.platform, process.env, APP_ROOT, {
|
||||
unsigned: invocation.unsigned, prepareOnly: invocation.prepareOnly,
|
||||
})
|
||||
const productVersion = packageVersion(join(APP_ROOT, 'package.json'), 'desktop package')
|
||||
// Release settings come from the target dotenv file alone, so the version this run publishes is an
|
||||
// Release settings come from the selected configuration files, so the version this run publishes is an
|
||||
// argument; the environment variable below only carries it to the child processes that build.
|
||||
const buildVersion = await resolveRequestedBuildVersion(invocation, productVersion, environment)
|
||||
environment[DESKTOP_BUILD_VERSION_ENV] = buildVersion
|
||||
|
||||
@@ -1,14 +1,10 @@
|
||||
/** Public settings prepared for a manual Windows package run. */
|
||||
export interface WindowsCiSettings {
|
||||
version: string
|
||||
settings: string
|
||||
}
|
||||
/** Resolve the version used by the manual Windows packaging workflow. */
|
||||
|
||||
/**
|
||||
* Validate manual inputs without local credentials or release storage.
|
||||
* @param environment Manual inputs and GitHub run identity.
|
||||
* Resolve an explicit version or a UTC date/run/attempt identifier without release storage access.
|
||||
* @param environment Manual version and GitHub run identity.
|
||||
* @param productVersion Version declared by the selected checkout.
|
||||
* @param now Time used for the UTC date segment.
|
||||
* @returns Validated version and public dotenv content.
|
||||
* @returns Validated build version.
|
||||
*/
|
||||
export function windowsCiSettings(environment: NodeJS.ProcessEnv, productVersion: string, now?: Date): WindowsCiSettings
|
||||
export function windowsCiVersion(environment: NodeJS.ProcessEnv, productVersion: string, now?: Date): string
|
||||
@@ -1,54 +1,52 @@
|
||||
/** Prepare public Windows packaging settings and a version for a manual GitHub run. */
|
||||
import { appendFileSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
/** Resolve a manual Windows build version and validate the selected machine preset. */
|
||||
import { appendFileSync, readFileSync } from 'node:fs'
|
||||
import { resolve } from 'node:path'
|
||||
import { desktopBuildVersionPrefix, validateDesktopBuildVersion } from './desktop-build-version.mjs'
|
||||
import { resolveDesktopPolicyEnvironment } from './desktop-policy-environment.mjs'
|
||||
import { loadDesktopPackageEnvironment, validateDesktopPackageEnvironment } from './desktop-package-environment.mjs'
|
||||
|
||||
/**
|
||||
* Validate manual inputs without reading local credentials or querying release storage.
|
||||
* @param {NodeJS.ProcessEnv} environment Manual inputs and GitHub run identity.
|
||||
* Resolve an explicit version or a UTC date/run/attempt identifier without release storage access.
|
||||
* @param {NodeJS.ProcessEnv} environment Manual version and GitHub run identity.
|
||||
* @param {string} productVersion Version declared by the selected checkout.
|
||||
* @param {Date} now Time used for the UTC date segment.
|
||||
* @returns {{ version: string, settings: string }} Validated version and public dotenv content.
|
||||
* @returns {string} Validated build version.
|
||||
*/
|
||||
export function windowsCiSettings(environment, productVersion, now = new Date()) {
|
||||
const deployment = environment.PACKAGE_DEPLOYMENT
|
||||
if (deployment !== 'test' && deployment !== 'production') throw new Error('Select test or production deployment')
|
||||
const loginOrigins = (environment.PACKAGE_LOGIN_ORIGINS ?? '').split(',').map(value => value.trim()).filter(Boolean)
|
||||
if (deployment === 'production' && loginOrigins.length > 0) throw new Error('Production must not supply login origins')
|
||||
const originKey = deployment === 'test' ? 'DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN' : 'DSH_DESKTOP_MANDATORY_UPDATE_PROD_ORIGIN'
|
||||
const config = deployment === 'test' ? { allowedAuthOrigins: loginOrigins } : {}
|
||||
const policy = resolveDesktopPolicyEnvironment({
|
||||
DSH_DESKTOP_AUTO_UPDATE_ENV: deployment,
|
||||
[originKey]: environment.PACKAGE_POLICY_ORIGIN,
|
||||
DSH_DESKTOP_MANDATORY_UPDATE_CONFIG: JSON.stringify(config),
|
||||
})
|
||||
export function windowsCiVersion(environment, productVersion, now = new Date()) {
|
||||
const requested = environment.PACKAGE_BUILD_VERSION?.trim()
|
||||
if (!requested) throw new Error('Build version is required; use auto or a full version')
|
||||
const date = now.toISOString().slice(0, 10).replaceAll('-', '')
|
||||
const example = `${desktopBuildVersionPrefix(productVersion)}${date}.1`
|
||||
if (!requested) throw new Error(`Build version is required: use auto, ${productVersion}, or e.g. ${example}`)
|
||||
let candidate = requested
|
||||
if (requested === 'auto') {
|
||||
for (const name of ['GITHUB_RUN_NUMBER', 'GITHUB_RUN_ATTEMPT']) {
|
||||
if (!/^[1-9]\d*$/u.test(environment[name] ?? '')) throw new Error(`${name} must be a positive integer`)
|
||||
}
|
||||
const date = now.toISOString().slice(0, 10).replaceAll('-', '')
|
||||
candidate = `${desktopBuildVersionPrefix(productVersion)}${date}.${environment.GITHUB_RUN_NUMBER}.${environment.GITHUB_RUN_ATTEMPT}`
|
||||
}
|
||||
const version = validateDesktopBuildVersion(candidate, productVersion)
|
||||
const settings = [
|
||||
'DSH_DESKTOP_APP_ID=com.deepseek.harness',
|
||||
`DSH_DESKTOP_AUTO_UPDATE_ENV=${deployment}`,
|
||||
`${originKey}=${policy.origin}`,
|
||||
`DSH_DESKTOP_MANDATORY_UPDATE_CONFIG=${JSON.stringify(config)}`,
|
||||
].join('\n') + '\n'
|
||||
return { version, settings }
|
||||
try {
|
||||
return validateDesktopBuildVersion(candidate, productVersion)
|
||||
} catch {
|
||||
throw new Error(`Invalid build version for this checkout: use auto, ${productVersion}, or e.g. ${example}`)
|
||||
}
|
||||
}
|
||||
|
||||
if (process.argv[1] !== undefined && resolve(process.argv[1]) === import.meta.filename) {
|
||||
const appRoot = resolve(import.meta.dirname, '..')
|
||||
const product = JSON.parse(readFileSync(resolve(appRoot, 'package.json'), 'utf8'))
|
||||
const result = windowsCiSettings(process.env, product.version)
|
||||
const version = windowsCiVersion(process.env, product.version)
|
||||
const mode = process.env.PACKAGE_SIGNING
|
||||
if (mode !== 'unsigned' && mode !== 'signed') throw new Error('Select unsigned or signed packaging')
|
||||
if (!process.env.DSH_PACKAGING_PRESET) throw new Error('Select a machine preset')
|
||||
const environment = loadDesktopPackageEnvironment('win32', process.env, appRoot, { unsigned: mode === 'unsigned' })
|
||||
// Machine-owned secrets are not automatically known to the Actions log masker.
|
||||
for (const [name, value] of Object.entries(environment)) {
|
||||
if (/TOKEN|PASSWORD|SECRET/iu.test(name) && value) {
|
||||
const escaped = value.replaceAll('%', '%25').replaceAll('\r', '%0D').replaceAll('\n', '%0A')
|
||||
process.stdout.write(`::add-mask::${escaped}\n`)
|
||||
}
|
||||
}
|
||||
validateDesktopPackageEnvironment(environment, { platform: 'win32', arch: 'x64' }, { unsigned: mode === 'unsigned' })
|
||||
if (!process.env.GITHUB_OUTPUT || !process.env.GITHUB_STEP_SUMMARY) throw new Error('Run this adapter from GitHub Actions')
|
||||
writeFileSync(resolve(appRoot, '.env.windows'), result.settings, { flag: 'wx' })
|
||||
appendFileSync(process.env.GITHUB_OUTPUT, `version=${result.version}\n`)
|
||||
appendFileSync(process.env.GITHUB_STEP_SUMMARY, `Windows x64 unsigned installer\n\nVersion: ${result.version}\n\nCommit: ${process.env.GITHUB_SHA}\n\nDeployment: ${process.env.PACKAGE_DEPLOYMENT}\n`)
|
||||
appendFileSync(process.env.GITHUB_OUTPUT, `version=${version}\n`)
|
||||
appendFileSync(process.env.GITHUB_STEP_SUMMARY, `Windows x64 ${mode} installer\n\nVersion: ${version}\n\nCommit: ${process.env.GITHUB_SHA}\n\nPreset: ${process.env.DSH_PACKAGING_PRESET}\n`)
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
# Prepare or inspect machine-owned Windows packaging directories without reading secret values.
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory=$true)][string]$Root,
|
||||
[switch]$CheckOnly
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if ($Root -notmatch '^[A-Za-z]:[\\/]') { throw 'Root must be an absolute local drive directory' }
|
||||
$rootPath = [IO.Path]::GetFullPath($Root)
|
||||
$drive = [IO.DriveInfo]::new([IO.Path]::GetPathRoot($rootPath))
|
||||
if ($drive.DriveType -ne [IO.DriveType]::Fixed) { throw 'Packaging root requires a fixed local drive' }
|
||||
for ($ancestor = [IO.DirectoryInfo]::new($rootPath); $null -ne $ancestor; $ancestor = $ancestor.Parent) {
|
||||
if ($ancestor.Exists -and ($ancestor.Attributes -band [IO.FileAttributes]::ReparsePoint)) { throw 'Packaging root cannot contain linked directories' }
|
||||
}
|
||||
$identity = [Security.Principal.WindowsIdentity]::GetCurrent().User
|
||||
$allowed = @($identity.Value, 'S-1-5-18', 'S-1-5-32-544')
|
||||
foreach ($relative in @('packaging', 'packaging/presets', 'packaging/secrets', 'packaging/certificates', 'cache', 'cache/windows-signatures')) {
|
||||
$path = Join-Path $rootPath $relative
|
||||
if (-not (Test-Path -LiteralPath $path)) {
|
||||
if ($CheckOnly) { throw "Missing directory: $path" }
|
||||
$null = New-Item -ItemType Directory -Path $path
|
||||
$acl = [Security.AccessControl.DirectorySecurity]::new()
|
||||
$acl.SetOwner($identity)
|
||||
$acl.SetAccessRuleProtection($true, $false)
|
||||
foreach ($sid in $allowed) {
|
||||
$rule = [Security.AccessControl.FileSystemAccessRule]::new([Security.Principal.SecurityIdentifier]::new($sid), 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow')
|
||||
$null = $acl.AddAccessRule($rule)
|
||||
}
|
||||
Set-Acl -LiteralPath $path -AclObject $acl
|
||||
}
|
||||
$item = Get-Item -LiteralPath $path
|
||||
if (-not $item.PSIsContainer -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) { throw "Not a real directory: $path" }
|
||||
$acl = Get-Acl -LiteralPath $path
|
||||
if ($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value -ne $identity.Value) { throw "Directory must belong to current account: $path" }
|
||||
foreach ($rule in $acl.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier])) {
|
||||
if ($rule.AccessControlType -eq 'Allow' -and $rule.IdentityReference.Value -notin $allowed) { throw "Directory permits another account: $path" }
|
||||
}
|
||||
}
|
||||
if (-not $CheckOnly) {
|
||||
$templates = Join-Path $PSScriptRoot '../config/windows-packaging'
|
||||
foreach ($name in @('test', 'production')) {
|
||||
$destination = Join-Path $rootPath "packaging/presets/$name.env.example"
|
||||
if (-not (Test-Path -LiteralPath $destination)) { Copy-Item -LiteralPath (Join-Path $templates "$name.env.example") -Destination $destination }
|
||||
}
|
||||
$destination = Join-Path $rootPath 'packaging/secrets/windows-signing.env.example'
|
||||
if (-not (Test-Path -LiteralPath $destination)) { Copy-Item -LiteralPath (Join-Path $templates 'windows-signing.env.example') -Destination $destination }
|
||||
}
|
||||
Write-Output "Packaging directories verified. Configuration root: $(Join-Path $rootPath 'packaging')"
|
||||
Write-Output 'Existing configuration, caches, runner registration and signing failure records were not overwritten.'
|
||||
@@ -0,0 +1,38 @@
|
||||
# Start the existing registered runner with explicit machine configuration and a scrubbed environment.
|
||||
[CmdletBinding()]
|
||||
param([Parameter(Mandatory=$true)][string]$RunnerRoot, [Parameter(Mandatory=$true)][string]$ConfigRoot, [switch]$CheckOnly)
|
||||
$ErrorActionPreference='Stop'
|
||||
$pwshRoot=Join-Path $RunnerRoot 'tools/pwsh-7.6.6'
|
||||
$runnerPath = $pwshRoot + ';' + [Environment]::GetEnvironmentVariable('Path','Machine') + ';' + [Environment]::GetEnvironmentVariable('Path','User')
|
||||
$keep=@('SystemRoot','windir','SystemDrive','ComSpec','TEMP','TMP','USERPROFILE','HOMEDRIVE','HOMEPATH','LOCALAPPDATA','APPDATA','ProgramData','ProgramFiles','ProgramFiles(x86)','CommonProgramFiles','CommonProgramFiles(x86)','CommonProgramW6432','ProgramW6432','PROCESSOR_ARCHITECTURE','NUMBER_OF_PROCESSORS','OS','PATHEXT','USERNAME','USERDOMAIN','COMPUTERNAME','PUBLIC','ALLUSERSPROFILE')
|
||||
foreach($entry in @(Get-ChildItem Env:)) {
|
||||
if($entry.Name -notin $keep) { [Environment]::SetEnvironmentVariable($entry.Name,$null,'Process') }
|
||||
}
|
||||
$env:PATH=$runnerPath
|
||||
if (-not [IO.Path]::IsPathRooted($ConfigRoot) -or -not (Test-Path -LiteralPath $ConfigRoot -PathType Container)) { throw 'ConfigRoot must identify an existing absolute directory' }
|
||||
if ($ConfigRoot -notmatch '^[A-Za-z]:[\\/]') { throw 'ConfigRoot requires an absolute local drive directory' }
|
||||
$drive = [IO.DriveInfo]::new([IO.Path]::GetPathRoot([IO.Path]::GetFullPath($ConfigRoot)))
|
||||
if ($drive.DriveType -ne [IO.DriveType]::Fixed) { throw 'ConfigRoot requires a fixed local drive' }
|
||||
$env:DSH_PACKAGING_CONFIG_DIR=[IO.Path]::GetFullPath($ConfigRoot)
|
||||
$env:DSH_TELEMETRY_DISABLED='1'
|
||||
$env:POWERSHELL_TELEMETRY_OPTOUT='1'
|
||||
foreach($tool in @('pwsh','node','git','tar','python')) {
|
||||
$resolved=Get-Command $tool -CommandType Application -ErrorAction Stop | Select-Object -First 1
|
||||
Write-Output ('Tool: '+$tool+' -> '+$resolved.Source)
|
||||
}
|
||||
$env:PYTHON=(Get-Command python -CommandType Application | Select-Object -First 1).Source
|
||||
& pwsh -NoProfile -Command '$PSVersionTable.PSVersion.ToString()'
|
||||
if($LASTEXITCODE -ne 0){throw 'PowerShell probe failed'}
|
||||
& node --version
|
||||
if($LASTEXITCODE -ne 0){throw 'Node probe failed'}
|
||||
& python --version
|
||||
if($LASTEXITCODE -ne 0){throw 'Python probe failed'}
|
||||
$vswhere=Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio/Installer/vswhere.exe'
|
||||
$visualStudio=& $vswhere -latest -products '*' -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath
|
||||
if($LASTEXITCODE -ne 0 -or -not $visualStudio){throw 'Visual C++ tools unavailable'}
|
||||
Write-Output 'Visual C++ tools located.'
|
||||
if($CheckOnly){Write-Output 'Runner environment check passed.'; exit 0}
|
||||
if(Get-Process -Name Runner.Listener -ErrorAction SilentlyContinue){throw 'A runner listener is already running; inspect before starting another.'}
|
||||
Set-Location $RunnerRoot
|
||||
& .\run.cmd
|
||||
exit $LASTEXITCODE
|
||||
@@ -1,56 +1,22 @@
|
||||
import { parseEnv } from 'node:util'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { windowsCiSettings } from '../scripts/prepare-windows-ci.mjs'
|
||||
import { validateDesktopPackageEnvironment } from '../scripts/desktop-package-environment.mjs'
|
||||
import { windowsCiVersion } from '../scripts/prepare-windows-ci.mjs'
|
||||
|
||||
const inputs = {
|
||||
PACKAGE_BUILD_VERSION: 'auto',
|
||||
PACKAGE_DEPLOYMENT: 'test',
|
||||
PACKAGE_POLICY_ORIGIN: 'https://policy.example.com',
|
||||
PACKAGE_LOGIN_ORIGINS: 'https://login.example.com, https://sso.example.com',
|
||||
GITHUB_RUN_NUMBER: '42',
|
||||
GITHUB_RUN_ATTEMPT: '2',
|
||||
}
|
||||
const productVersion = '0.2.1-alpha.1'
|
||||
const now = new Date('2026-10-08T23:59:59Z')
|
||||
const inputs = { PACKAGE_BUILD_VERSION: 'auto', GITHUB_RUN_NUMBER: '42', GITHUB_RUN_ATTEMPT: '2' }
|
||||
const now = new Date('2026-10-09T01:02:03Z')
|
||||
|
||||
describe('manual Windows package inputs', () => {
|
||||
it('numbers fresh runners and reruns without storage credentials', () => {
|
||||
const result = windowsCiSettings(inputs, productVersion, now)
|
||||
expect(result.version).toBe('0.2.1-alpha.1.20261008.42.2')
|
||||
const settings = parseEnv(result.settings)
|
||||
expect(() => { validateDesktopPackageEnvironment(settings, { platform: 'win32', arch: 'x64' }, { unsigned: true }) }).not.toThrow()
|
||||
expect(Object.keys(settings).sort()).toEqual([
|
||||
'DSH_DESKTOP_APP_ID', 'DSH_DESKTOP_AUTO_UPDATE_ENV',
|
||||
'DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN', 'DSH_DESKTOP_MANDATORY_UPDATE_CONFIG',
|
||||
].sort())
|
||||
describe('manual Windows CI version', () => {
|
||||
it('uses the selected product prefix and UTC run identity', () => {
|
||||
expect(windowsCiVersion(inputs, '0.2.1-alpha.1', now)).toBe('0.2.1-alpha.1.20261009.42.2')
|
||||
expect(windowsCiVersion(inputs, '0.2.1', now)).toBe('0.2.1-test.20261009.42.2')
|
||||
})
|
||||
|
||||
it('accepts an explicit version without a GitHub run identity', () => {
|
||||
const result = windowsCiSettings({ ...inputs, PACKAGE_BUILD_VERSION: '0.2.1-alpha.1.20261008.7',
|
||||
GITHUB_RUN_NUMBER: undefined, GITHUB_RUN_ATTEMPT: undefined }, productVersion, now)
|
||||
expect(result.version).toBe('0.2.1-alpha.1.20261008.7')
|
||||
it.each(['0.2.1-alpha.1', '0.2.1-alpha.1.20261009.7'])('accepts explicit version %s without run identity', (version) => {
|
||||
expect(windowsCiVersion({ PACKAGE_BUILD_VERSION: version }, '0.2.1-alpha.1', now)).toBe(version)
|
||||
})
|
||||
|
||||
it('uses the stable product test prefix and anonymous production policy', () => {
|
||||
const result = windowsCiSettings({ ...inputs, PACKAGE_DEPLOYMENT: 'production', PACKAGE_LOGIN_ORIGINS: '' }, '0.2.1', now)
|
||||
expect(result.version).toBe('0.2.1-test.20261008.42.2')
|
||||
expect(() => { validateDesktopPackageEnvironment(parseEnv(result.settings), { platform: 'win32', arch: 'x64' }, { unsigned: true }) }).not.toThrow()
|
||||
it.each(['', 'bad', '0.3.0'])('reports checkout-specific guidance for %s', (version) => {
|
||||
expect(() => windowsCiVersion({ PACKAGE_BUILD_VERSION: version }, '0.2.1-alpha.1', now))
|
||||
.toThrow(/auto, 0\.2\.1-alpha\.1, or e\.g\. 0\.2\.1-alpha\.1\.20261009\.1/u)
|
||||
})
|
||||
|
||||
it.each([
|
||||
{ PACKAGE_BUILD_VERSION: '' },
|
||||
{ PACKAGE_BUILD_VERSION: '0.3.0' },
|
||||
{ PACKAGE_DEPLOYMENT: 'staging' },
|
||||
{ PACKAGE_POLICY_ORIGIN: '' },
|
||||
{ PACKAGE_POLICY_ORIGIN: 'http://policy.example.com' },
|
||||
{ PACKAGE_POLICY_ORIGIN: 'https://policy.example.com/path' },
|
||||
{ PACKAGE_LOGIN_ORIGINS: '' },
|
||||
{ PACKAGE_LOGIN_ORIGINS: 'https://user:[email protected]' },
|
||||
{ PACKAGE_DEPLOYMENT: 'production' },
|
||||
{ GITHUB_RUN_NUMBER: '0' },
|
||||
{ GITHUB_RUN_ATTEMPT: '1\nINJECTED=value' },
|
||||
])('rejects invalid manual settings %j', (override) => {
|
||||
expect(() => windowsCiSettings({ ...inputs, ...override }, productVersion, now)).toThrow()
|
||||
it.each([{ GITHUB_RUN_NUMBER: '0' }, { GITHUB_RUN_ATTEMPT: '1\nINJECTED=value' }])('rejects invalid run identity %j', (override) => {
|
||||
expect(() => windowsCiVersion({ ...inputs, ...override }, '0.2.1', now)).toThrow(/positive integer/u)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,93 @@
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { expect, it } from 'vitest'
|
||||
import { loadDesktopPackageEnvironment } from '../scripts/desktop-package-environment.mjs'
|
||||
|
||||
async function withPreset(run: (root: string) => Promise<void>) {
|
||||
const root = await mkdtemp(join(tmpdir(), 'dsh-windows-preset-'))
|
||||
try {
|
||||
await mkdir(join(root, 'presets'))
|
||||
await mkdir(join(root, 'secrets'))
|
||||
await writeFile(join(root, 'presets/test.env'), 'DSH_DESKTOP_AUTO_UPDATE_ENV=test\nDSH_DESKTOP_APP_ID=com.example.desktop\n')
|
||||
await run(root)
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
it('loads unsigned public settings without requiring the signing secret file or personal dotenv', async () => {
|
||||
await withPreset(async (root) => {
|
||||
const environment = loadDesktopPackageEnvironment('win32', {
|
||||
DSH_PACKAGING_CONFIG_DIR: root, DSH_PACKAGING_PRESET: 'test', DSH_DESKTOP_WINDOWS_TOKEN_PIN: 'ambient-secret',
|
||||
}, join(root, 'missing-checkout'), { unsigned: true })
|
||||
expect(environment.DSH_DESKTOP_APP_ID).toBe('com.example.desktop')
|
||||
expect(environment.DSH_DESKTOP_WINDOWS_TOKEN_PIN).toBeUndefined()
|
||||
const prepared = loadDesktopPackageEnvironment('win32', {
|
||||
DSH_PACKAGING_CONFIG_DIR: root, DSH_PACKAGING_PRESET: 'test',
|
||||
}, root, { prepareOnly: true })
|
||||
expect(prepared.DSH_DESKTOP_WINDOWS_TOKEN_PIN).toBeUndefined()
|
||||
expect(prepared.DSH_PACKAGING_PRESET).toBe('test')
|
||||
expect(() => loadDesktopPackageEnvironment('win32', { DSH_PACKAGING_CONFIG_DIR: root, DSH_PACKAGING_PRESET: 'test' }))
|
||||
.toThrow(/cannot read/u)
|
||||
})
|
||||
})
|
||||
|
||||
it('resolves signing file paths relative to the secret file and rejects public overrides there', async () => {
|
||||
await withPreset(async (root) => {
|
||||
const env = { DSH_PACKAGING_CONFIG_DIR: root, DSH_PACKAGING_PRESET: 'test' }
|
||||
const file = join(root, 'secrets/windows-signing.env')
|
||||
await writeFile(file, 'DSH_DESKTOP_WINDOWS_CER_FILE=../certificates/ev.cer\nDSH_DESKTOP_WINDOWS_TOKEN_PIN="private-value"\n')
|
||||
const result = loadDesktopPackageEnvironment('win32', env)
|
||||
expect(result.DSH_DESKTOP_WINDOWS_CER_FILE).toBe(join(root, 'certificates/ev.cer'))
|
||||
expect(result.DSH_DESKTOP_WINDOWS_TOKEN_PIN).toBe('private-value')
|
||||
await writeFile(file, 'DSH_DESKTOP_AUTO_UPDATE_ENV=production\n')
|
||||
expect(() => loadDesktopPackageEnvironment('win32', env)).toThrow(/unsupported setting/u)
|
||||
})
|
||||
})
|
||||
|
||||
it('preserves the selected preset when Windows environment enumeration uses lowercase keys', async () => {
|
||||
await withPreset(async (root) => {
|
||||
const values: NodeJS.ProcessEnv = { dsh_packaging_config_dir: root, dsh_packaging_preset: 'test' }
|
||||
const environment = new Proxy(values, {
|
||||
get: (target, name) => typeof name === 'string' ? target[name.toLowerCase()] : undefined,
|
||||
})
|
||||
const selected = loadDesktopPackageEnvironment('win32', environment, root, { unsigned: true })
|
||||
expect(selected.DSH_PACKAGING_PRESET).toBe('test')
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects missing presets, traversal, deployment mismatches and secrets in public configuration', async () => {
|
||||
await withPreset(async (root) => {
|
||||
const env = { DSH_PACKAGING_CONFIG_DIR: root, DSH_PACKAGING_PRESET: 'test' }
|
||||
const load = (override = {}) => loadDesktopPackageEnvironment('win32', { ...env, ...override }, root, { unsigned: true })
|
||||
expect(() => load({ DSH_PACKAGING_CONFIG_DIR: 'relative' })).toThrow(/absolute/u)
|
||||
expect(() => load({ DSH_PACKAGING_CONFIG_DIR: undefined })).toThrow(/absolute/u)
|
||||
expect(() => loadDesktopPackageEnvironment('darwin', env)).toThrow(/Windows only/u)
|
||||
expect(() => load({ DSH_PACKAGING_PRESET: '../secrets' })).toThrow(/preset must/u)
|
||||
expect(() => load({ DSH_PACKAGING_PRESET: 'production' })).toThrow(/cannot read/u)
|
||||
await writeFile(join(root, 'presets/test.env'), 'DSH_DESKTOP_AUTO_UPDATE_ENV=production\n')
|
||||
expect(() => load()).toThrow(/must match/u)
|
||||
await writeFile(join(root, 'presets/test.env'), 'DSH_DESKTOP_WINDOWS_TOKEN_PIN=private-value\n')
|
||||
expect(() => load()).toThrow(/unsupported setting DSH_DESKTOP_WINDOWS_TOKEN_PIN/u)
|
||||
expect(() => load()).not.toThrow(/private-value/u)
|
||||
})
|
||||
})
|
||||
|
||||
it('cache maintenance reaches cache path validation without a signing file', async () => {
|
||||
await withPreset(async (root) => {
|
||||
await writeFile(join(root, 'presets/test.env'),
|
||||
'DSH_DESKTOP_AUTO_UPDATE_ENV=test\nDSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_DIR=relative-cache\n')
|
||||
const result = spawnSync(process.execPath,
|
||||
[join(import.meta.dirname, '../scripts/manage-windows-signature-cache.mjs'), '--usage'], {
|
||||
env: { ...process.env, DSH_PACKAGING_CONFIG_DIR: root, DSH_PACKAGING_PRESET: 'test' },
|
||||
encoding: 'utf8', timeout: 10_000, windowsHide: true,
|
||||
})
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.signal).toBeNull()
|
||||
expect(result.status).toBe(1)
|
||||
expect(result.stderr).toContain('absolute local')
|
||||
expect(result.stderr).not.toContain('cannot read')
|
||||
})
|
||||
})
|
||||
@@ -455,8 +455,9 @@ it.each([false, true])('starts Creator from Plugins with Coding Tools=%s without
|
||||
|
||||
await page.getByRole('navigation', { name: 'Global panels' }).getByRole('button', { name: 'Plugins', exact: true }).click()
|
||||
await page.getByRole('button', { name: 'Choose how to add a plugin', exact: true }).click()
|
||||
// The Creator entry reuses the draft's blank Session and names its preset in the creation request.
|
||||
await Promise.all([
|
||||
page.waitForResponse('**/api/agentPresets/select'),
|
||||
page.waitForResponse('**/api/session/create'),
|
||||
page.getByRole('menuitem', { name: /^Let the agent create a plugin/ }).click(),
|
||||
])
|
||||
const picker = page.getByTitle('Choose the agent preset for your new task', { exact: true }).filter({ hasText: 'Creator mode' })
|
||||
@@ -469,8 +470,9 @@ it.each([false, true])('starts Creator from Plugins with Coding Tools=%s without
|
||||
expect(scaffold.ctx.agentPresets.composedPreset(creator.ctx)).toBe('cordis')
|
||||
expect(scaffold.ctx.tools.schemas(creator).map(tool => tool.name))
|
||||
.toEqual(expect.arrayContaining(['cordis_inspect_list', 'cordis_inspect_query', 'plugin_manager']))
|
||||
expect(creator.session.snapshotEvents().some(event => event.type === 'agent-preset/selected'
|
||||
&& event.data.agentPreset === 'cordis')).toBe(true)
|
||||
// The chip may also select Creator once the list updates; the registry records the switch only once.
|
||||
expect(creator.session.snapshotEvents().filter(event => event.type === 'agent-preset/selected'
|
||||
&& event.data.agentPreset === 'cordis')).toHaveLength(1)
|
||||
expect(creator.session.snapshotEvents().some(event => event.type === 'user/message' || event.type === 'turn/start')).toBe(false)
|
||||
expect(scaffold.ctx.settings.describe().find(row => row.ns === 'ui-settings')?.value).toMatchObject({ enabled: developerTools })
|
||||
expect(scaffold.ctx.agentPresets.defaultId).toBe('standard')
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
/** Blank Session reuse under the requested or default Agent preset through the shipped Web composition. */
|
||||
|
||||
import { mkdir } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { chromium, type Browser, type Page } from 'playwright'
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
|
||||
import { SessionId } from '@deepseek-ai/dsh-session'
|
||||
import type { SessionEvent } from '@deepseek-ai/dsh-session'
|
||||
import { launchWebScaffold, watchConsole, type WebScaffold } from './scaffold.ts'
|
||||
import { newEnglishPage } from './support.ts'
|
||||
|
||||
/** A preset these blank Sessions recorded that the deployment no longer declares. */
|
||||
const UNDECLARED = 'liangshen'
|
||||
|
||||
describe('web e2e: blank Session reuse under the requested preset', () => {
|
||||
let scaffold: WebScaffold
|
||||
let browser: Browser
|
||||
const tripwires: ReturnType<typeof watchConsole>[] = []
|
||||
|
||||
beforeAll(async () => {
|
||||
scaffold = await launchWebScaffold({})
|
||||
browser = await chromium.launch()
|
||||
}, 120_000)
|
||||
|
||||
afterAll(async () => {
|
||||
await browser?.close()
|
||||
await scaffold?.close()
|
||||
})
|
||||
|
||||
/** Store a blank Session recorded under `agentPreset`, with a plan-mode switch, as the only member of a new Workspace. */
|
||||
async function storeBlank(sessionId: SessionId, folder: string, agentPreset: string): Promise<void> {
|
||||
const path = join(scaffold.workspaceCwd, folder)
|
||||
await mkdir(path)
|
||||
const workspace = await scaffold.ctx.workspaceRegistry.create(path)
|
||||
const handle = await scaffold.ctx.agents.create({
|
||||
sessionId,
|
||||
meta: { cwd: path, agentPreset },
|
||||
agentOptions: scaffold.ctx.agentDefaultModel.currentSelection(),
|
||||
})
|
||||
try {
|
||||
handle.agent.session.append('plan/mode', { active: true })
|
||||
await workspace.attachSession(sessionId)
|
||||
} finally {
|
||||
await handle.dispose()
|
||||
}
|
||||
}
|
||||
|
||||
async function openPage(saved?: SessionId): Promise<Page> {
|
||||
const page = await newEnglishPage(browser)
|
||||
tripwires.push(watchConsole(page))
|
||||
if (saved !== undefined) {
|
||||
await page.addInitScript((id) => {
|
||||
localStorage.setItem('dsh.sessions.current', JSON.stringify({ sessionId: id }))
|
||||
}, saved)
|
||||
}
|
||||
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
|
||||
await page.locator('[data-composer-input]').first().waitFor({ timeout: 30_000 })
|
||||
return page
|
||||
}
|
||||
|
||||
async function selected(page: Page): Promise<string | undefined> {
|
||||
return page.evaluate(() => {
|
||||
const value = localStorage.getItem('dsh.sessions.current')
|
||||
return value === null ? undefined : (JSON.parse(value) as { sessionId?: string }).sessionId
|
||||
})
|
||||
}
|
||||
|
||||
/** The live Agent's mounted preset, its projected preset, and its plan-mode state. */
|
||||
function liveComposition(sessionId: SessionId) {
|
||||
const agent = scaffold.ctx.agents.get(sessionId)
|
||||
if (agent === undefined) return undefined
|
||||
return {
|
||||
mounted: scaffold.ctx.agentPresets.composedPreset(agent.ctx),
|
||||
projected: scaffold.ctx.sessionProjections.stateOf(agent.session, 'agentPreset'),
|
||||
plan: scaffold.ctx.sessionProjections.stateOf(agent.session, 'plan'),
|
||||
}
|
||||
}
|
||||
|
||||
async function storedSelections(sessionId: SessionId): Promise<unknown[]> {
|
||||
const handle = await scaffold.ctx.sessionPersistence.open(sessionId, 'read')
|
||||
try {
|
||||
const { events } = await handle.read()
|
||||
return events
|
||||
.filter((event: SessionEvent) => event.type === 'agent-preset/selected')
|
||||
.map((event: SessionEvent) => event.data)
|
||||
} finally {
|
||||
await handle.close()
|
||||
}
|
||||
}
|
||||
|
||||
it('reuses a blank recorded under an undeclared preset under the default when startup connects its Workspace', async () => {
|
||||
const stale = SessionId('blank-undeclared')
|
||||
await storeBlank(stale, 'undeclared', UNDECLARED)
|
||||
|
||||
const page = await openPage()
|
||||
await expect.poll(() => selected(page)).toBe(stale)
|
||||
await expect.poll(() => liveComposition(stale)).toMatchObject({
|
||||
mounted: 'standard', projected: 'standard', plan: { active: true },
|
||||
})
|
||||
expect(await storedSelections(stale)).toEqual([{ agentPreset: 'standard' }])
|
||||
expect(scaffold.ctx.workspaceRegistry.list().find(item => item.sessionIds.includes(stale))?.sessionIds).toEqual([stale])
|
||||
expect(await page.getByRole('alert').count()).toBe(0)
|
||||
})
|
||||
|
||||
it('restores a saved blank under the preset it recorded', async () => {
|
||||
const picked = SessionId('blank-picked')
|
||||
await storeBlank(picked, 'picked', 'minimal')
|
||||
|
||||
const page = await openPage(picked)
|
||||
await expect.poll(() => selected(page)).toBe(picked)
|
||||
await expect.poll(() => liveComposition(picked)).toMatchObject({ mounted: 'minimal', projected: 'minimal' })
|
||||
expect(await storedSelections(picked)).toEqual([])
|
||||
})
|
||||
|
||||
it('restores a saved blank under the default once its recorded preset is undeclared', async () => {
|
||||
const saved = SessionId('saved-undeclared')
|
||||
await storeBlank(saved, 'saved-undeclared', UNDECLARED)
|
||||
|
||||
const page = await openPage(saved)
|
||||
await expect.poll(() => selected(page)).toBe(saved)
|
||||
await expect.poll(() => liveComposition(saved)).toMatchObject({
|
||||
mounted: 'standard', projected: 'standard', plan: { active: true },
|
||||
})
|
||||
expect(await storedSelections(saved)).toEqual([{ agentPreset: 'standard' }])
|
||||
expect(await page.getByRole('alert').count()).toBe(0)
|
||||
for (const tripwire of tripwires) {
|
||||
expect(tripwire.pageErrors).toEqual([])
|
||||
expect(tripwire.warnings).toEqual([])
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,218 @@
|
||||
/**
|
||||
* A Turn this Client did not submit (a subagent-settled notice) wakes while the
|
||||
* reader follows the tail of a long Turn under "On next message" folding. The
|
||||
* notice Turn belongs to the long Turn's exchange, so the long Turn stays
|
||||
* expanded through the host's pre-Step gap and after the notice arrives, and a
|
||||
* reader who was following sees the notice and its reply at the tail.
|
||||
*/
|
||||
import type { Browser, Page } from 'playwright'
|
||||
import { chromium } from 'playwright'
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
|
||||
import { ToolCallId, createAssistantMessage, createToolResultMessage, createUserMessage } from '@deepseek-ai/dsh-llm'
|
||||
import { SessionId } from '@deepseek-ai/dsh-session'
|
||||
import type { SubagentSettledMessageSource } from '@deepseek-ai/dsh-subagent'
|
||||
import { launchWebScaffold, watchConsole, type WebScaffold } from './scaffold.ts'
|
||||
import { connectFreshWorkspace, newEnglishPage } from './support.ts'
|
||||
|
||||
/** Settled Turns before the long one, so every work-details mode overflows the viewport. */
|
||||
const HISTORY_TURNS = 3
|
||||
const LONG_TURN = HISTORY_TURNS + 1
|
||||
const NOTICE_TURN = HISTORY_TURNS + 2
|
||||
/** Tool Steps in the finished Turn; their folded height must exceed the notice Turn's height. */
|
||||
const TOOL_STEPS = 12
|
||||
const OUTPUT_LINES = 40
|
||||
/** The recorded host gap between the waking claim and Step 1, spent assembling the system prompt. */
|
||||
const PRE_STEP_GAP_MS = 187
|
||||
const REPLY = 'NOTICE_WAKE_REPLY'
|
||||
|
||||
interface Tail {
|
||||
/** Height of the room reserved below the flow. */
|
||||
readonly spacer: number
|
||||
readonly noticeVisible: boolean
|
||||
readonly replyVisible: boolean
|
||||
/** Whether the long Turn's process disclosure reports itself expanded. */
|
||||
readonly longTurnOpen: boolean
|
||||
}
|
||||
|
||||
function readTail(page: Page): Promise<Tail> {
|
||||
return page.evaluate(([reply, longTurn]) => {
|
||||
const host = document.querySelector<HTMLElement>('[data-conversation-scroll]')
|
||||
if (host === null) throw new Error('conversation scrollport is absent')
|
||||
const viewTop = host.getBoundingClientRect().top
|
||||
const viewBottom = host.querySelector<HTMLElement>('[data-composer-seat]')?.getBoundingClientRect().top
|
||||
?? host.getBoundingClientRect().bottom
|
||||
const inView = (element: Element): boolean => {
|
||||
const rect = element.getBoundingClientRect()
|
||||
return rect.height > 0.5 && rect.bottom > viewTop && rect.top < viewBottom
|
||||
}
|
||||
const spacer = host.querySelector<HTMLElement>('[data-chat-turn-spacer]')
|
||||
return {
|
||||
spacer: spacer === null ? 0 : Number.parseFloat(spacer.style.height) || 0,
|
||||
noticeVisible: [...host.querySelectorAll('[data-turn-trigger]')].some(inView),
|
||||
replyVisible: [...host.querySelectorAll('[data-chat-flow-kind="assistant-step"]')]
|
||||
.some(row => (row.textContent ?? '').includes(reply) && inView(row)),
|
||||
longTurnOpen: host.querySelector(`[data-turn-process="${longTurn}"]`)?.getAttribute('aria-expanded') === 'true',
|
||||
}
|
||||
}, [REPLY, String(LONG_TURN)] as const)
|
||||
}
|
||||
|
||||
describe('web e2e: notice Turn after a long Detailed Turn', () => {
|
||||
let browser: Browser
|
||||
|
||||
beforeAll(async () => {
|
||||
browser = await chromium.launch({ headless: true })
|
||||
}, 60_000)
|
||||
|
||||
afterAll(async () => {
|
||||
await browser?.close()
|
||||
})
|
||||
|
||||
it.each(['detailed', 'standard'] as const)('keeps the new tail visible in %s work details', async (view) => {
|
||||
const scaffold: WebScaffold = await launchWebScaffold({})
|
||||
const page = await newEnglishPage(browser)
|
||||
const tripwire = watchConsole(page)
|
||||
try {
|
||||
await page.setViewportSize({ width: 1280, height: 800 })
|
||||
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
|
||||
await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
|
||||
await connectFreshWorkspace(page, scaffold.workspaceCwd)
|
||||
await scaffold.ctx.settings.update('ui-chat', { transcriptView: view, collapseTiming: 'next-input' })
|
||||
const agent = scaffold.ctx.agents.list().at(-1)
|
||||
if (agent === undefined) throw new Error('connected workspace created no Agent')
|
||||
const session = agent.session
|
||||
const setRunning = (running: boolean): void => { scaffold.ctx.emit('api-session/status', agent.id, running) }
|
||||
|
||||
for (let turn = 1; turn <= HISTORY_TURNS; turn += 1) {
|
||||
session.append('turn/start', { turn })
|
||||
session.append('step/start', { turn, step: 1 })
|
||||
session.append('user/message', createUserMessage({
|
||||
content: [{ type: 'text', text: `Earlier question ${String(turn)}.` }],
|
||||
source: { kind: 'user' },
|
||||
}), { surfaceOp: 'append' })
|
||||
session.append('assistant/message', {
|
||||
stream: [],
|
||||
turn,
|
||||
step: 1,
|
||||
message: createAssistantMessage({
|
||||
content: [{ type: 'text', text: `Earlier answer ${String(turn)}. ${'This settled reply wraps across several lines of prose. '.repeat(24)}` }],
|
||||
source: { provider: 'fixture', model: 'fixture' },
|
||||
}),
|
||||
}, { surfaceOp: 'append' })
|
||||
session.append('step/end', { turn, step: 1 })
|
||||
session.append('turn/end', { turn, reason: { kind: 'completed' } })
|
||||
}
|
||||
|
||||
// A long running Turn streams Step by Step while the reader follows the tail.
|
||||
setRunning(true)
|
||||
session.append('turn/start', { turn: LONG_TURN })
|
||||
session.append('step/start', { turn: LONG_TURN, step: 1 })
|
||||
session.append('user/message', createUserMessage({
|
||||
content: [{ type: 'text', text: 'Run the long diagnostic.' }],
|
||||
source: { kind: 'user' },
|
||||
}), { surfaceOp: 'append' })
|
||||
for (let step = 1; step <= TOOL_STEPS; step += 1) {
|
||||
const callId = ToolCallId(`notice-wake-${String(step)}`)
|
||||
const args = JSON.stringify({ command: `diagnose ${String(step)}`, description: `Diagnostic ${String(step)}` })
|
||||
session.append('assistant/message', {
|
||||
stream: [],
|
||||
turn: LONG_TURN,
|
||||
step,
|
||||
message: createAssistantMessage({
|
||||
content: [
|
||||
{ type: 'reasoning', text: `Checking diagnostic ${String(step)}.` },
|
||||
{ type: 'tool-call', id: callId, name: 'bash', arguments: args },
|
||||
],
|
||||
source: { provider: 'fixture', model: 'fixture' },
|
||||
}),
|
||||
}, { surfaceOp: 'append' })
|
||||
const call = session.append('tool/call', { turn: LONG_TURN, step, callId, name: 'bash', arguments: args })
|
||||
session.append('tool/result', {
|
||||
turn: LONG_TURN,
|
||||
step,
|
||||
message: createToolResultMessage({
|
||||
callId,
|
||||
content: [{
|
||||
type: 'text',
|
||||
text: Array.from({ length: OUTPUT_LINES }, (_, line) => `diagnostic ${String(step)} line ${String(line + 1)}`).join('\n'),
|
||||
}],
|
||||
isError: false,
|
||||
}),
|
||||
}, { surfaceOp: 'append', sourceEventSeqs: [call.seq] })
|
||||
session.append('step/end', { turn: LONG_TURN, step })
|
||||
session.append('step/start', { turn: LONG_TURN, step: step + 1 })
|
||||
await scaffold.ctx.sessions.flush(session)
|
||||
await page.locator(`[data-chat-node-key$="${callId}"]`).waitFor({ state: 'attached', timeout: 15_000 })
|
||||
}
|
||||
session.append('assistant/message', {
|
||||
stream: [],
|
||||
turn: LONG_TURN,
|
||||
step: TOOL_STEPS + 1,
|
||||
message: createAssistantMessage({
|
||||
content: [{ type: 'text', text: 'All diagnostics finished.' }],
|
||||
source: { provider: 'fixture', model: 'fixture' },
|
||||
}),
|
||||
}, { surfaceOp: 'append' })
|
||||
session.append('step/end', { turn: LONG_TURN, step: TOOL_STEPS + 1 })
|
||||
await scaffold.ctx.sessions.flush(session)
|
||||
await page.getByText('All diagnostics finished.').waitFor({ timeout: 30_000 })
|
||||
await page.evaluate(() => {
|
||||
const host = document.querySelector<HTMLElement>('[data-conversation-scroll]')
|
||||
if (host !== null) host.scrollTop = host.scrollHeight
|
||||
})
|
||||
await page.locator('[data-chat-following-tail]').waitFor({ timeout: 10_000 })
|
||||
|
||||
// The Turn ends; 15 ms later (the recorded production gap) a settled subagent wakes the next Turn.
|
||||
session.append('turn/end', { turn: LONG_TURN, reason: { kind: 'completed' } })
|
||||
await scaffold.ctx.sessions.flush(session)
|
||||
setRunning(false)
|
||||
await page.waitForTimeout(15)
|
||||
const source: SubagentSettledMessageSource = {
|
||||
kind: 'subagent-settled',
|
||||
form: 'notice',
|
||||
summary: 'Background subagent finished.',
|
||||
senderSessionId: SessionId('notice-wake-child'),
|
||||
}
|
||||
const notice = createUserMessage({
|
||||
content: [{ type: 'text', text: 'Background subagent notice-wake-child finished.' }],
|
||||
source,
|
||||
})
|
||||
session.append('agent/inbox/spliced', { target: 'next-turn', start: 0, inserted: [notice] })
|
||||
session.append('turn/start', { turn: NOTICE_TURN })
|
||||
session.append('agent/inbox/spliced', { target: 'next-turn', start: 0, removedCount: 1, inserted: [] })
|
||||
setRunning(true)
|
||||
await scaffold.ctx.sessions.flush(session)
|
||||
// The browser has applied the notice Turn's start before the gap is held and sampled.
|
||||
await page.locator(`[data-chat-turn="${String(NOTICE_TURN)}"]`).first().waitFor({ state: 'attached', timeout: 15_000 })
|
||||
await page.waitForTimeout(PRE_STEP_GAP_MS)
|
||||
const gap = await readTail(page)
|
||||
session.append('step/start', { turn: NOTICE_TURN, step: 1 })
|
||||
session.append('user/message', notice, { surfaceOp: 'append' })
|
||||
await scaffold.ctx.sessions.flush(session)
|
||||
await page.locator('[data-turn-trigger]').first().waitFor({ state: 'attached', timeout: 15_000 })
|
||||
session.append('assistant/message', {
|
||||
stream: [],
|
||||
turn: NOTICE_TURN,
|
||||
step: 1,
|
||||
message: createAssistantMessage({
|
||||
content: [{ type: 'text', text: `${REPLY} the subagent result is acknowledged.` }],
|
||||
source: { provider: 'fixture', model: 'fixture' },
|
||||
}),
|
||||
}, { surfaceOp: 'append' })
|
||||
await scaffold.ctx.sessions.flush(session)
|
||||
|
||||
expect(gap).toMatchObject({ longTurnOpen: true, spacer: 0 })
|
||||
const settled = { noticeVisible: true, replyVisible: true, longTurnOpen: true, spacer: 0 }
|
||||
await expect.poll(() => readTail(page), { timeout: 15_000 }).toMatchObject(settled)
|
||||
// The settled tail survives later frames instead of passing through on the way to a fold.
|
||||
await page.evaluate(() => new Promise<void>((resolve) => {
|
||||
requestAnimationFrame(() => { requestAnimationFrame(() => { resolve() }) })
|
||||
}))
|
||||
expect(await readTail(page)).toMatchObject(settled)
|
||||
expect(tripwire.warnings).toEqual([])
|
||||
expect(tripwire.pageErrors).toEqual([])
|
||||
} finally {
|
||||
await page.context().close()
|
||||
await scaffold.close()
|
||||
}
|
||||
}, 180_000)
|
||||
})
|
||||
@@ -17,7 +17,7 @@ import { join, sep } from 'node:path'
|
||||
import type { Browser, Locator, Page } from 'playwright'
|
||||
import { chromium } from 'playwright'
|
||||
import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
|
||||
import { SessionId, SessionLogOffset } from '@deepseek-ai/dsh-session'
|
||||
import { SessionId } from '@deepseek-ai/dsh-session'
|
||||
import { logPath } from '../../../packages/session/session-persistence-jsonl/src/format.ts'
|
||||
import {
|
||||
acknowledgeReloadConnectionLoss, assertFixtureInventory, captureStableAria, compareOrRefreshGolden,
|
||||
@@ -779,11 +779,10 @@ describe('web e2e: New Session after an outdated blank cache', () => {
|
||||
undefined, { createdAt: now - 60_000 })
|
||||
const stored = await scaffold.ctx.sessionPersistence.stat(id)
|
||||
if (stored === undefined) throw new Error('seeded Session is missing')
|
||||
// A durable log may advance after its last blank projection checkpoint.
|
||||
// An unregistered Session writes only the checkpoint, leaving the persisted log intact.
|
||||
const blank = scaffold.ctx.sessions.prepare(id, {
|
||||
eventState: 'detached', seed: [], meta: stored.header, inheritedEventCount: SessionLogOffset(0),
|
||||
})
|
||||
// A durable log may advance after its last blank projection checkpoint,
|
||||
// which then records the cut before the first turn. An unregistered
|
||||
// Session writes only the checkpoint, leaving the persisted log intact.
|
||||
const blank = scaffold.ctx.sessions.prepare(id, { meta: stored.header })
|
||||
await scaffold.ctx.sessionProjectionCache.write(blank)
|
||||
const workspace = await scaffold.ctx.workspaceRegistry.create(scaffold.workspaceCwd, 'New session regression')
|
||||
await workspace.attachSession(id)
|
||||
@@ -794,8 +793,14 @@ describe('web e2e: New Session after an outdated blank cache', () => {
|
||||
onTestFailed(() => saveFailureShot(page, 'web-e2e-new-session-stale-blank'))
|
||||
|
||||
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
|
||||
await page.getByRole('tab', { name: 'Chat', exact: true }).waitFor()
|
||||
const selected = page.locator('[role="treeitem"][aria-selected="true"]')
|
||||
// Startup asks for a new conversation with the stale blank as its reuse
|
||||
// candidate; the Host declines the started Session and creates a blank one.
|
||||
await expect.poll(() => selected.innerText()).toBe('New Session')
|
||||
await expect.poll(() => workspace.sessionIds.length).toBe(2)
|
||||
// The declined Session's projections are reloaded, so its stale blank row reappears.
|
||||
await page.getByRole('treeitem', { name: /^Use the read tool twice/ }).click()
|
||||
await page.getByRole('tab', { name: 'Chat', exact: true }).waitFor()
|
||||
await expect.poll(() => selected.innerText()).not.toBe('New Session')
|
||||
const previous = (await selected.innerText()).split('\n')[0]!
|
||||
const before = await captureStableAria(page, '[role="tree"]', scaffold.workspaceCwd)
|
||||
@@ -803,7 +808,8 @@ describe('web e2e: New Session after an outdated blank cache', () => {
|
||||
await page.getByRole('button', { name: 'New session', exact: true }).last().click()
|
||||
await expect.poll(() => selected.innerText()).toBe('New Session')
|
||||
await page.getByRole('tab', { name: 'Chat', exact: true }).waitFor({ state: 'hidden' })
|
||||
await expect.poll(() => workspace.sessionIds.length).toBe(2)
|
||||
// New Session creates a fresh Session; the blank startup created stays a member.
|
||||
await expect.poll(() => workspace.sessionIds.length).toBe(3)
|
||||
expect(workspace.sessionIds).toContain(id)
|
||||
await page.getByRole('treeitem').filter({ hasText: previous }).waitFor()
|
||||
const after = await captureStableAria(page, '[role="tree"]', scaffold.workspaceCwd)
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
// cannot see both sides of the cordis Context merges).
|
||||
"exclude": [
|
||||
"tests/collapse-timing.e2e.ts",
|
||||
"tests/notice-wake-tail.e2e.ts",
|
||||
"tests/chat-flow-layout.e2e.ts",
|
||||
"tests/layout-bottom.e2e.ts",
|
||||
"tests/shortcuts-desktop.e2e.ts",
|
||||
@@ -159,6 +160,7 @@
|
||||
"tests/idle-submission-handoff.e2e.ts",
|
||||
"tests/cold-blank-session.e2e.ts",
|
||||
"tests/blank-writer-reuse.e2e.ts",
|
||||
"tests/blank-preset-reuse.e2e.ts",
|
||||
"tests/queue-image.e2e.ts",
|
||||
"tests/skill-invocation-policy.e2e.ts",
|
||||
"tests/skill-user-invoke.e2e.ts",
|
||||
|
||||
@@ -21,8 +21,8 @@
|
||||
en: 9570ffe7a348e5ac
|
||||
zh: 2b70b61b1ff1fbb0
|
||||
/api-gateway/development-mode:
|
||||
en: ba090d76471dd663
|
||||
zh: edf362f71b73eaf0
|
||||
en: 23ae422bd65300da
|
||||
zh: 67dd9c02f4ffec53
|
||||
/api-gateway/boundaries:
|
||||
en: e6befc5f8c90f97b
|
||||
zh: 4ace4a493fd2b41f
|
||||
|
||||
+1
-1
@@ -154,7 +154,7 @@ Changing only a Remote method's implementation body without changing its contrac
|
||||
pnpm run build:lib
|
||||
```
|
||||
|
||||
The running Client watcher consumes these generated files when it rebundles. If `pnpm run build:lib:host` has already refreshed the Host contract, `pnpm run build:lib:client` can complete the Client side; a clean worktree cannot skip the Host phase. Recompiling only the frontend source cannot infer new types from Host decorators. `pnpm run typecheck` runs the Host lib phase before Client tsc, and CI and release builds use the same order.
|
||||
The running Client watcher consumes these generated files when it rebundles. If `pnpm run build:lib:host` has already refreshed the Host contract, `pnpm run build:lib:client` can complete the Client side; a clean worktree cannot skip the Host phase. Recompiling only the frontend source cannot infer new types from Host decorators. `pnpm run typecheck` generates the Host contract with the bundle-free Typert pass before Client tsc, and the CI build lanes and release builds generate it in the Host bundle phase before Client tsc.
|
||||
|
||||
## Boundaries
|
||||
|
||||
|
||||
@@ -156,7 +156,7 @@ pnpm run dev:web
|
||||
pnpm run build:lib
|
||||
```
|
||||
|
||||
运行中的 Client watcher 会在重新打包时消费这些生成文件。若已单独运行 `pnpm run build:lib:host` 刷新 Host 约定,也可再运行 `pnpm run build:lib:client` 完成 Client 侧;干净工作树不能跳过 Host 阶段。仅重新编译前端源码不能从 Host decorator 推导新类型。`pnpm run typecheck` 会执行 Host lib 阶段后再运行 Client tsc,CI 与发布构建也使用同一顺序。
|
||||
运行中的 Client watcher 会在重新打包时消费这些生成文件。若已单独运行 `pnpm run build:lib:host` 刷新 Host 约定,也可再运行 `pnpm run build:lib:client` 完成 Client 侧;干净工作树不能跳过 Host 阶段。仅重新编译前端源码不能从 Host decorator 推导新类型。`pnpm run typecheck` 先以不打包的 Typert 生成刷新 Host 约定,再运行 Client tsc;CI 的构建 lane 与发布构建则在 Client tsc 之前的 Host bundle 阶段生成它。
|
||||
|
||||
<a id="boundaries"></a>
|
||||
|
||||
|
||||
@@ -21,14 +21,14 @@
|
||||
en: 3221d1076554001f
|
||||
zh: 29f166be6a5c04d9
|
||||
/development-guide/contributor-reference/typescript-project-layout:
|
||||
en: b137fdddcc8ce2ba
|
||||
zh: d9c078ba11734a21
|
||||
en: f0582a3a145a4d93
|
||||
zh: 9cab4abec6935b3c
|
||||
/development-guide/contributor-reference/environment-variables:
|
||||
en: dba2c72ee6ffa930
|
||||
zh: b65c27fbb9129ec8
|
||||
/development-guide/contributor-reference/git-integrations:
|
||||
en: dc98eda4f4021feb
|
||||
zh: b08766708803cf10
|
||||
en: 4e782ec2ca27dd1f
|
||||
zh: 7a60e8c0d60de3c8
|
||||
/development-guide/contributor-reference/ci-gates:
|
||||
en: b64a914e41b1d285
|
||||
zh: 6c031b507c3c0e84
|
||||
|
||||
+6
-4
@@ -97,13 +97,13 @@ Choose the command by what the change needs:
|
||||
| Before declaring TypeScript work complete | `pnpm run build:check` after the latest `build:artifacts`, or `pnpm run build` |
|
||||
| Complete verification, as the required CI build lanes run it | `pnpm run build` |
|
||||
| Type checks without the Web and Desktop artifacts | `pnpm run typecheck` |
|
||||
| Lint or documentation code-block checks | `pnpm run lint` or `pnpm run doc-typecheck`; each prepares `host-libraries` itself |
|
||||
| Lint or documentation code-block checks | `pnpm run lint` or `pnpm run doc-typecheck`; each prepares `host-contracts` itself |
|
||||
|
||||
PR artifact builders run `build:artifacts`; required Linux and Windows normal builds and public `typecheck` also check the repository-wide test and script programs. CI benchmark preparation additionally uses `--noCheck` for its disposable library outputs, relying on those required builds for diagnostics; other artifact builders keep package checking ([rationale](../.agents/notes/implemented/process/2026-10-05-pr-artifact-typechecks.md)).
|
||||
|
||||
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, Client package compilation always follows the Host bundle, and `pnpm run typecheck` runs the complete Host lib phase, including the Host aggregate check, before Client tsc. `lint`, `lint:fix`, and `doc-typecheck` read the generated declarations but not the Host aggregate check, so they prepare only Host package compilation and the Host bundle (`compile-referenced-projects.ts host-libraries`).
|
||||
Typert analyzes Host types, seeded by `tsconfig.host.json`, and generates both Host reflection artifacts and the Host-for-Client Remote projection; Client tsdown does not start Typert. Host tsdown runs it as a plugin, and [`generate-typert.ts`](../scripts/generate-typert.ts) runs the same generation without bundling and writes byte-identical files. The bundle-free pass reads workspace packages only from source and fails when the Host program would load a package's `lib/` output, naming the import and the `paths` alias to add, so it can run beside Host package compilation. Client package compilation always follows one of the two passes because Client sources import the generated Remote declarations. `pnpm run typecheck` runs the `build.ts --scope typecheck` graph: Host package compilation beside the bundle-free Typert pass, then Client package compilation, with each aggregate checked in build mode (`tsc -b`) once its own face's packages compile; it skips the native addon, every bundle, Web, and the client build record. `lint`, `lint:fix`, and `doc-typecheck` read the generated declarations but not the Host aggregate check, so they prepare only Host package compilation and the bundle-free Typert pass (`compile-referenced-projects.ts host-contracts`). None of these commands writes bundles: the runnable `lib/` output stays as the last `build:artifacts` left it, so run `build:artifacts` before launching or testing built output.
|
||||
|
||||
`pnpm run build` and `build:artifacts` embed the root package version, the seven-character source commit, and a dirty marker when Git reports local changes; they also inherit other caller-supplied `DSH_CLIENT_*` values. `pnpm run build:official` is the cross-platform local equivalent of the CI and release artifact build and omits the local dirty marker. Each successful `build` or `build:artifacts` writes a gitignored record that binds the exact public values to the Vite output and dynamic client bundles; release packing and built Web tests reject a missing record or artifacts changed by a later partial build. `pnpm run dev:web` runs `build:artifacts` first (`--skip-build` reuses an existing artifact tree instead), then samples the current version and Git state once and shares that environment across every watcher stage for the session; it does not validate the complete-build record because the watcher stages rewrite its recorded artifacts.
|
||||
|
||||
@@ -136,9 +136,9 @@ DEEPSEEK_BASE_URL=https://... # optional
|
||||
|
||||
lefthook is configured in `lefthook.yml` as a fast local checkpoint:
|
||||
|
||||
- `pre-commit` verifies staged pairing records against the staged owner blobs, validates staged files with the project-free `.oxlintrc.staged.json` profile and applies Oxlint fixes with one bounded retry, regenerates `THIRD_PARTY_NOTICES.md` when a staged file is one of its inputs, checks the staged diff for whitespace errors, and runs the vendor manifest guard.
|
||||
- `pre-commit` verifies staged pairing records against the staged owner blobs, validates staged files with the project-free `.oxlintrc.staged.json` profile and applies Oxlint fixes with one bounded retry, checks the staged diff for whitespace errors, and runs the vendor manifest guard.
|
||||
- `pre-merge-commit` performs the same index-backed pairing check before Git creates an automatic merge commit.
|
||||
- `pre-push` runs `pnpm run typecheck`, which completes the Host lib phase, including generated Typert contracts, before the Client TypeScript check.
|
||||
- `pre-push` runs `pnpm run typecheck`, which generates Typert contracts without bundling before the Client TypeScript check and checks both aggregates.
|
||||
|
||||
The vendor manifest guard checks that changes under `vendor/*/src` are staged with the matching `vendor/README.md` manifest update. See `vendor/README.md` before editing vendored code.
|
||||
|
||||
@@ -146,6 +146,8 @@ Apart from the scoped staged-record verification, the hooks intentionally do not
|
||||
|
||||
Contributors can opt into the comprehensive local gate set with `pnpm run check:all`. The command is independent of the Git hooks and is not an agent instruction.
|
||||
|
||||
Outside CI (`CI` other than `true`), default worker counts follow the [local worker budget](../scripts/parallelism.ts): 12 for gate schedulers, `build`, `typecheck`, Oxlint, and publint, and 48 for Vitest forks and local coverage. `doc-sync`, `test:docs`, `hygiene`, and `check:all` run at most 8 gates at once, in CI as well. `os.availableParallelism()` reports host CPUs rather than a container's CPU quota, so uncapped defaults oversubscribe shared hosts. CI keeps the runner's CPU count. `DSH_GATE_CONCURRENCY`, `DSH_OXLINT_THREADS`, `DSH_COVERAGE_MAX_WORKERS`, and Vitest `--maxWorkers` override the defaults.
|
||||
|
||||
### CI gates
|
||||
|
||||
The keyless [CI workflow](../.github/workflows/ci.yml) groups independent gates into broad lanes and runs a smaller compatibility signal across supported Node versions. Artifact consumers wait for one build within their lane. Coverage partitions reuse file timings scoped to their platform and runner pool to balance work within the configured worker limit. Required benchmarks run separately on standard GitHub-hosted Linux; the [benchmark runner reference](../benchmarks/AGENTS.md) owns routing and the job timeout. The separate real-API workflow runs `pnpm run test:e2e` with its configured worker bound. See [scripts/run-gates.ts](../scripts/run-gates.ts) and the workflow files for the current gate and job inventory.
|
||||
|
||||
@@ -101,13 +101,13 @@ pnpm run build:web
|
||||
| 声明 TypeScript 工作完成之前 | 在最近一次 `build:artifacts` 之后运行 `pnpm run build:check`,或运行 `pnpm run build` |
|
||||
| 完整验证(与 CI 必需的构建 lane 相同) | `pnpm run build` |
|
||||
| 只做类型检查、不需要 Web 与 Desktop 产物 | `pnpm run typecheck` |
|
||||
| lint 或文档代码块检查 | `pnpm run lint` 或 `pnpm run doc-typecheck`;它们各自先准备 `host-libraries` |
|
||||
| lint 或文档代码块检查 | `pnpm run lint` 或 `pnpm run doc-typecheck`;它们各自先准备 `host-contracts` |
|
||||
|
||||
PR 产物 builder 运行 `build:artifacts`;必需的 Linux 与 Windows 普通构建以及公开 `typecheck` 还检查仓库级测试和脚本 program。CI benchmark 准备阶段还对其临时 library 输出使用 `--noCheck`,由这些必需构建负责诊断;其他产物 builder 保留包检查([理由](../.agents/notes/implemented/process/2026-10-05-pr-artifact-typechecks.zh.md))。
|
||||
|
||||
两次 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。因此 Client 包编译总在 Host bundle 之后;`pnpm run typecheck` 先执行包含 Host aggregate 检查的完整 Host lib 阶段,再运行 Client tsc。`lint`、`lint:fix` 与 `doc-typecheck` 读取生成的声明但不依赖 Host aggregate 检查,因此只准备 Host 包编译与 Host bundle(`compile-referenced-projects.ts host-libraries`)。
|
||||
Typert 以 `tsconfig.host.json` 为种子分析 Host 类型,生成 Host 反射产物及 Host-for-Client Remote 投影;Client tsdown 不启动 Typert。Host tsdown 以插件形式运行它,[`generate-typert.ts`](../scripts/generate-typert.ts) 则不打包地执行同一生成,写出逐字节相同的文件。不打包的这一轮只从源码读取工作区包;若 Host program 会载入某个包的 `lib/` 产物,它就失败并指出该 import 及应补的 `paths` 别名,因此可以与 Host 包编译并行。Client 源码 import 生成的 Remote 声明,所以 Client 包编译总在这两种生成之一之后。`pnpm run typecheck` 运行 `build.ts --scope typecheck` 图:Host 包编译与不打包的 Typert 生成并行,之后是 Client 包编译,每个 aggregate 在本 face 的包编译完成后以 build mode(`tsc -b`)检查;它跳过 native addon、所有 bundle、Web 以及 client build record。`lint`、`lint:fix` 与 `doc-typecheck` 读取生成的声明但不依赖 Host aggregate 检查,因此只准备 Host 包编译与不打包的 Typert 生成(`compile-referenced-projects.ts host-contracts`)。这些命令都不写 bundle:可运行的 `lib/` 产物保持上一次 `build:artifacts` 的状态,因此启动或测试构建产物之前先运行 `build:artifacts`。
|
||||
|
||||
`pnpm run build` 与 `build:artifacts` 会内联根包版本、七位源码 commit,并在 Git 报告本地变化时内联 dirty 标记;调用方提供的其他 `DSH_CLIENT_*` 值也会被继承。`pnpm run build:official` 是与 CI 和 release 产物构建等价的跨平台本地命令,并省略本地 dirty 标记。每次 `build` 或 `build:artifacts` 成功后都会写入一份被 gitignore 的记录,把精确公开值与 Vite 输出及动态 client bundle 绑定;release 打包和 built Web 测试会拒绝缺少记录或被后续局部构建改动的产物。`pnpm run dev:web` 会先执行 `build:artifacts`(`--skip-build` 则复用现有产物树),再读取一次当前版本和 Git 状态,并在本次会话的所有 watcher stage 之间共享该环境;它不会校验完整构建记录,因为 watcher stage 会重写记录覆盖的产物。
|
||||
|
||||
@@ -141,9 +141,9 @@ DEEPSEEK_BASE_URL=https://... # optional
|
||||
|
||||
lefthook 在 `lefthook.yml` 中配置,作为快速的本地检查点:
|
||||
|
||||
- `pre-commit` 对照暂存的配对文档 blob 校验暂存的配对记录,使用不加载项目的 `.oxlintrc.staged.json` 配置验证暂存文件,并通过一次有界重试应用 Oxlint 修复,在暂存文件属于 `THIRD_PARTY_NOTICES.md` 的输入时重新生成该文件,然后检查暂存 diff 中的空白错误,并运行 vendor manifest(元数据清单)守卫;
|
||||
- `pre-commit` 对照暂存的配对文档 blob 校验暂存的配对记录,使用不加载项目的 `.oxlintrc.staged.json` 配置验证暂存文件,并通过一次有界重试应用 Oxlint 修复,然后检查暂存 diff 中的空白错误,并运行 vendor manifest(元数据清单)守卫;
|
||||
- `pre-merge-commit` 在 Git 创建自动合并提交前执行同样以索引为准的配对检查;
|
||||
- `pre-push` 运行 `pnpm run typecheck`;该命令会先完成包含 Typert 约定生成的完整 Host lib 阶段,再运行 Client TypeScript 检查。
|
||||
- `pre-push` 运行 `pnpm run typecheck`;该命令先不打包地生成 Typert 约定,再运行 Client TypeScript 检查,并检查两个 aggregate。
|
||||
|
||||
vendor manifest 守卫检查 `vendor/*/src` 下的改动是否连同对应的 `vendor/README.md` manifest 更新一起暂存。请在编辑 vendor 代码前先阅读 `vendor/README.md`。
|
||||
|
||||
@@ -151,6 +151,8 @@ vendor manifest 守卫检查 `vendor/*/src` 下的改动是否连同对应的 `v
|
||||
|
||||
贡献者可以选择运行 `pnpm run check:all`,执行全面的本地门禁集。该命令独立于 Git 钩子,也不是对 agent 的指令。
|
||||
|
||||
在 CI 之外(`CI` 不为 `true`),默认 worker 数遵循[本地 worker 预算](../scripts/parallelism.ts):门禁调度器、`build`、`typecheck`、Oxlint 与 publint 为 12,Vitest fork 与本地覆盖率为 48。`doc-sync`、`test:docs`、`hygiene` 与 `check:all` 最多同时运行 8 个门禁,CI 中同样如此。`os.availableParallelism()` 报告的是宿主 CPU 数而不是容器的 CPU 配额,因此不设上限的默认值会在共享主机上超额订阅。CI 仍使用 runner 的 CPU 数。`DSH_GATE_CONCURRENCY`、`DSH_OXLINT_THREADS`、`DSH_COVERAGE_MAX_WORKERS` 与 Vitest 的 `--maxWorkers` 可覆盖这些默认值。
|
||||
|
||||
### CI 门禁
|
||||
|
||||
keyless [CI 工作流](../.github/workflows/ci.yml) 将独立门禁分组到若干宽粒度 lane,并在受支持的 Node 版本上运行一组较小的兼容性检查。产物消费方在各自 lane 内等待一次 build。覆盖率分区复用按平台和运行器池隔离的文件耗时,在配置的 worker 上限内均衡工作量。必需 benchmark 在标准 GitHub 托管 Linux 上独立运行;[benchmark 运行器说明](../benchmarks/AGENTS.md)拥有路由及 job 超时。单独的真实 API 工作流按其配置的 worker 上限运行 `pnpm run test:e2e`。当前门禁和 job 清单以 [scripts/run-gates.ts](../scripts/run-gates.ts) 和工作流文件为准。
|
||||
|
||||
@@ -22,11 +22,11 @@ This matrix shows which packages dispatch each harness-owned event and which pac
|
||||
| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:359`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) |
|
||||
| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:286`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), `agent-team`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` |
|
||||
| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:387`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) |
|
||||
| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:619`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:599`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:626`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:605`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:612`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:624`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:604`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:631`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:610`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:617`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `app-boot/config-reload` | `emit` | [`packages/boot/app-boot/src/index.ts:52`](../packages/boot/app-boot/src/index.ts) | [`app-boot`](../packages/boot/app-boot) (`emit`) | [`settings`](../packages/settings/settings) |
|
||||
| `approval/request` | `waterfall` | [`packages/interaction/user-approval/src/types.ts:87`](../packages/interaction/user-approval/src/types.ts) | [`user-approval`](../packages/interaction/user-approval) (`waterfall`) | [`acp`](../packages/acp/acp), `remotes` |
|
||||
| `authorization/settled` | `emit` | [`packages/credentials/authorization/src/index.ts:57`](../packages/credentials/authorization/src/index.ts) | [`authorization`](../packages/credentials/authorization) (`events.dispatch`) | - |
|
||||
|
||||
@@ -24,11 +24,11 @@
|
||||
| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:359`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) |
|
||||
| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:286`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), `agent-team`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` |
|
||||
| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:387`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) |
|
||||
| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:619`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:599`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:626`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:605`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:612`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:624`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:604`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:631`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:610`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:617`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
|
||||
| `app-boot/config-reload` | `emit` | [`packages/boot/app-boot/src/index.ts:52`](../packages/boot/app-boot/src/index.ts) | [`app-boot`](../packages/boot/app-boot) (`emit`) | [`settings`](../packages/settings/settings) |
|
||||
| `approval/request` | `waterfall` | [`packages/interaction/user-approval/src/types.ts:87`](../packages/interaction/user-approval/src/types.ts) | [`user-approval`](../packages/interaction/user-approval) (`waterfall`) | [`acp`](../packages/acp/acp), `remotes` |
|
||||
| `authorization/settled` | `emit` | [`packages/credentials/authorization/src/index.ts:57`](../packages/credentials/authorization/src/index.ts) | [`authorization`](../packages/credentials/authorization) (`events.dispatch`) | - |
|
||||
|
||||
@@ -18,8 +18,8 @@
|
||||
en: 38a55fc61b359ace
|
||||
zh: 567cae201b3a1bdf
|
||||
/glossary/loop-hierarchy:
|
||||
en: 343a7cb31b8191c2
|
||||
zh: 6831415a7fe1726a
|
||||
en: 6bf1ad7dd53f79cc
|
||||
zh: 6231e68c769fdefa
|
||||
/glossary/ralph:
|
||||
en: 5059f8a377980b9d
|
||||
zh: 39bf11c10e5c0a84
|
||||
@@ -37,6 +37,7 @@ Domain vocabulary for DeepSeek Harness uses one canonical term per concept. Term
|
||||
- **turn** — one drain of admitted input in a session, ending after the model and its tools stop or a terminal policy intervenes. <a id="turn"></a>
|
||||
- **step** — one model request plus the tool executions caused by its response; a turn contains zero or more steps. <a id="step"></a>
|
||||
- **round** — an outer policy iteration containing a turn, such as a [goal round](#goal-round) or one fresh-agent Ralph attempt. Round counters belong to that policy and do not count every turn in a session. <a id="round"></a>
|
||||
- **exchange** — consecutive [turns](#turn) from a turn whose first [step](#step) admits human input until the next such turn; turns woken by notices, such as settled subagents, goal rounds, or schedules, stay in the preceding exchange. Chat's next-message folding keeps the latest exchange expanded. <a id="exchange"></a>
|
||||
|
||||
## Ralph
|
||||
|
||||
|
||||
@@ -37,6 +37,7 @@ DeepSeek Harness 的领域词汇为每个概念规定一个规范术语。各术
|
||||
- **轮次**:会话中一次对已接纳输入的排空过程,在模型及其工具停止工作或终止策略介入后结束。<a id="turn"></a>
|
||||
- **步骤**:一次模型请求,以及由模型响应引发的工具执行;一个轮次包含零个或多个步骤。<a id="step"></a>
|
||||
- **Round**:承载一个轮次的外层策略迭代,例如一个 [Goal Round](#goal-round) 或一次使用全新 agent 的 Ralph 尝试。Round 计数器归该策略所有,并不统计会话中的每个轮次。<a id="round"></a>
|
||||
- **交互段**:连续的[轮次](#turn),从首个[步骤](#step)接纳真人输入的轮次起,到下一个这样的轮次为止;由通知(子 agent 完成、Goal Round、定时任务等)唤醒的轮次归入前面的交互段。Chat 的「下次发送时收起」保持最新交互段展开。<a id="exchange"></a>
|
||||
|
||||
## Ralph
|
||||
|
||||
|
||||
@@ -127,6 +127,7 @@
|
||||
| event log | 事件日志 | | | |
|
||||
| event stream | 事件流 | | | |
|
||||
| event-sourced | 事件溯源 | | | 沿用 DDD 社区通行译法 |
|
||||
| exchange | 交互段 | | 回合、交换 | Chat 中从真人输入开启的轮次起、到下一个这样的轮次为止的连续轮次;见术语表 |
|
||||
| Executive summary | 摘要 | | | 事故复盘标题用语 |
|
||||
| executor | 执行器 | | | |
|
||||
| expected output | 预期输出 | | 金标 | 指 snapshot 比较产物;翻译语料的人工校准样例不在此列 |
|
||||
|
||||
@@ -1299,8 +1299,8 @@
|
||||
en: 386989934d1bb62e
|
||||
zh: 69b8bc182a5acbd3
|
||||
/session-persistence-event-catalog/resolved-persistence-types/string:
|
||||
en: 90d3fd7202322ca4
|
||||
zh: 88cce532aed9f6d4
|
||||
en: 52f664fd6203444e
|
||||
zh: dbebfaccbc666386
|
||||
/session-persistence-event-catalog/resolved-persistence-types/string~2:
|
||||
en: 0089620bf4638263
|
||||
zh: 1922bef1713094bb
|
||||
@@ -1782,8 +1782,8 @@
|
||||
en: bbcefadaa064365a
|
||||
zh: 0285b8b877d6193d
|
||||
/session-persistence-event-catalog/resolved-persistence-types/kind-user:
|
||||
en: cb5d3fbab4debac6
|
||||
zh: 72add55254356149
|
||||
en: d23abbfb20eb4fc0
|
||||
zh: 65207e79db74e2fe
|
||||
/session-persistence-event-catalog/resolved-persistence-types/kind-user-approval:
|
||||
en: a52d2dfbaf844127
|
||||
zh: 4c5306ca40f20873
|
||||
|
||||
@@ -5382,7 +5382,7 @@ Array of `number`.
|
||||
|
||||
SHA-256: `4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b`
|
||||
|
||||
Sources: [`packages/api/session-controller/src/types.ts:403`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:20`](../packages/core/session/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:21`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:33`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:9`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:42`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts)
|
||||
Sources: [`packages/api/session-controller/src/types.ts:408`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:20`](../packages/core/session/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:21`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:33`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:9`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:42`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts)
|
||||
|
||||
`string`
|
||||
|
||||
@@ -7341,7 +7341,7 @@ Sources: [`packages/core/tools/src/index.ts:42`](../packages/core/tools/src/inde
|
||||
|
||||
SHA-256: `6a4f72e2e179e17b922f2a9392c0e1c8f8c707f32494372454850a3eb184a6e7`
|
||||
|
||||
Sources: [`packages/api/session-controller/src/types.ts:408`](../packages/api/session-controller/src/types.ts)
|
||||
Sources: [`packages/api/session-controller/src/types.ts:413`](../packages/api/session-controller/src/types.ts)
|
||||
|
||||
| Property | Presence | Type |
|
||||
|---|---|---|
|
||||
|
||||
@@ -5384,7 +5384,7 @@ SHA-256: `5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78`
|
||||
|
||||
SHA-256: `4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b`
|
||||
|
||||
来源:[`packages/api/session-controller/src/types.ts:403`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:20`](../packages/core/session/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:21`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:33`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:9`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:42`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts)
|
||||
来源:[`packages/api/session-controller/src/types.ts:408`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:20`](../packages/core/session/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:21`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:33`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:9`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:42`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts)
|
||||
|
||||
`string`
|
||||
|
||||
@@ -7343,7 +7343,7 @@ SHA-256: `8fcb0b44a575e998665c053643d1ab04c82f39253ebd190ac0c975b78e40b543`
|
||||
|
||||
SHA-256: `6a4f72e2e179e17b922f2a9392c0e1c8f8c707f32494372454850a3eb184a6e7`
|
||||
|
||||
来源:[`packages/api/session-controller/src/types.ts:408`](../packages/api/session-controller/src/types.ts)
|
||||
来源:[`packages/api/session-controller/src/types.ts:413`](../packages/api/session-controller/src/types.ts)
|
||||
|
||||
| 属性 | 存在性 | 类型 |
|
||||
|---|---|---|
|
||||
|
||||
Generated
+2
-2
@@ -23137,7 +23137,7 @@
|
||||
"packages/workflow/workflow/src/types.ts#WorkflowRunId"
|
||||
],
|
||||
"sources": [
|
||||
"packages/api/session-controller/src/types.ts:403",
|
||||
"packages/api/session-controller/src/types.ts:408",
|
||||
"packages/attachment/attachment/src/brand.ts:6",
|
||||
"packages/compaction/compaction/src/brand.ts:4",
|
||||
"packages/core/session/src/types.ts:20",
|
||||
@@ -23582,7 +23582,7 @@
|
||||
"digest": "6a4f72e2e179e17b922f2a9392c0e1c8f8c707f32494372454850a3eb184a6e7",
|
||||
"names": [],
|
||||
"sources": [
|
||||
"packages/api/session-controller/src/types.ts:408"
|
||||
"packages/api/session-controller/src/types.ts:413"
|
||||
]
|
||||
},
|
||||
{
|
||||
|
||||
@@ -563,7 +563,9 @@ serviceFor<K extends string & keyof Context>(agent: { ctx: Context }, name: K):
|
||||
*/
|
||||
async recompose(ctx: Context, id: string): Promise<AgentPreset>
|
||||
|
||||
/** Select a preset before a session starts its first turn.
|
||||
/** Select a preset before a session starts its first turn. A Session whose
|
||||
* log records the preset and whose Agent runs its current revision keeps its
|
||||
* composition; nothing is logged or announced.
|
||||
* @param agent Target Agent.
|
||||
* @param agentPreset Requested identity.
|
||||
* @returns Committed preset identity.
|
||||
|
||||
@@ -575,7 +575,9 @@ serviceFor<K extends string & keyof Context>(agent: { ctx: Context }, name: K):
|
||||
*/
|
||||
async recompose(ctx: Context, id: string): Promise<AgentPreset>
|
||||
|
||||
/** Select a preset before a session starts its first turn.
|
||||
/** Select a preset before a session starts its first turn. A Session whose
|
||||
* log records the preset and whose Agent runs its current revision keeps its
|
||||
* composition; nothing is logged or announced.
|
||||
* @param agent Target Agent.
|
||||
* @param agentPreset Requested identity.
|
||||
* @returns Committed preset identity.
|
||||
|
||||
@@ -856,9 +856,9 @@ inspect( sessionId: SessionId, signal?: AbortSignal, ): Promise<SessionInspectio
|
||||
@Remote('search') search(request: SessionSearchRequest, signal: AbortSignal): Promise<SessionSearchValue>
|
||||
|
||||
/**
|
||||
* Create or idempotently adopt one ordinary Session.
|
||||
* @param request - requested identity, location, and Agent preset.
|
||||
* @returns the Session identity and resolved preset when configured.
|
||||
* Create one ordinary Session for a new conversation, reusing the named blank Session while it is reusable.
|
||||
* @param request - optional blank Session to reuse, location, and Agent preset.
|
||||
* @returns the created or reused Session identity and its preset when configured.
|
||||
*/
|
||||
@Remote('create') create(request: SessionCreateRequest): Promise<SessionCreateValue>
|
||||
|
||||
|
||||
@@ -860,9 +860,9 @@ inspect( sessionId: SessionId, signal?: AbortSignal, ): Promise<SessionInspectio
|
||||
@Remote('search') search(request: SessionSearchRequest, signal: AbortSignal): Promise<SessionSearchValue>
|
||||
|
||||
/**
|
||||
* Create or idempotently adopt one ordinary Session.
|
||||
* @param request - requested identity, location, and Agent preset.
|
||||
* @returns the Session identity and resolved preset when configured.
|
||||
* Create one ordinary Session for a new conversation, reusing the named blank Session while it is reusable.
|
||||
* @param request - optional blank Session to reuse, location, and Agent preset.
|
||||
* @returns the created or reused Session identity and its preset when configured.
|
||||
*/
|
||||
@Remote('create') create(request: SessionCreateRequest): Promise<SessionCreateValue>
|
||||
|
||||
|
||||
@@ -21,16 +21,6 @@ pre-commit:
|
||||
run: node_modules/.bin/tsx scripts/run-oxlint.ts --config .oxlintrc.staged.json --fix --no-error-on-unmatched-pattern {staged_files}
|
||||
stage_fixed: true
|
||||
|
||||
# Regenerate rather than reject: a dependency edit that forgot the notices
|
||||
# would otherwise fail the test lane long after the commit. The glob matches
|
||||
# every input the generator reads, including the generator itself and the
|
||||
# build-time pin source. Deleting a manifest cannot trigger this job —
|
||||
# lefthook only inspects files present on disk — so that one case still
|
||||
# falls through to the freshness assertion in the test lane.
|
||||
- name: third-party notices (staged)
|
||||
glob: '{package.json,*/package.json,*/*/package.json,*/*/*/package.json,*/*/*/*/package.json,pnpm-workspace.yaml,*/*/pnpm-workspace.yaml,pnpm-lock.yaml,vendor/README.md,python/*/pyproject.toml,scripts/primary-runtime/lock.json,scripts/gen-third-party-notices.ts,scripts/browser-bundled-externals.ts,scripts/build-exe-for-python-sdk.ts,tsconfig.base*.json,packages/*/*/src/**/*,packages/*/*/tsdown.config.ts,packages/client/tsdown.client.ts,apps/*/src/**/*,apps/*/vite.config.ts}'
|
||||
run: node_modules/.bin/tsx scripts/gen-third-party-notices.ts && git add THIRD_PARTY_NOTICES.md
|
||||
|
||||
- name: whitespace (staged)
|
||||
run: git diff --cached --check
|
||||
|
||||
|
||||
+4
-4
@@ -50,11 +50,11 @@
|
||||
"upload:latest:win:x64": "pnpm --filter @deepseek-ai/dsh-desktop run upload:latest:win:x64",
|
||||
"clean": "tsx scripts/clean.ts",
|
||||
"change-scope": "tsx scripts/change-scope.ts",
|
||||
"typecheck": "npm run build:lib:host && npm run typecheck:contracts-ready",
|
||||
"typecheck": "tsx scripts/build.ts --scope typecheck",
|
||||
"typecheck:contracts-ready": "tsc -b tsconfig.client.json",
|
||||
"lint": "tsx scripts/compile-referenced-projects.ts host-libraries && npm run lint:contracts-ready",
|
||||
"lint": "tsx scripts/compile-referenced-projects.ts host-contracts && npm run lint:contracts-ready",
|
||||
"lint:contracts-ready": "tsx scripts/run-oxlint.ts .",
|
||||
"lint:fix": "tsx scripts/compile-referenced-projects.ts host-libraries && npm run lint:fix:contracts-ready",
|
||||
"lint:fix": "tsx scripts/compile-referenced-projects.ts host-contracts && npm run lint:fix:contracts-ready",
|
||||
"lint:fix:contracts-ready": "tsx scripts/run-oxlint.ts --config .oxlintrc.staged.json packages/typert/generator/tests/fixtures/type-model --fix && tsx scripts/run-oxlint.ts . --fix",
|
||||
"duplication": "jscpd --config .jscpd.json packages scripts",
|
||||
"test": "pnpm run build:native-system && vitest run",
|
||||
@@ -101,7 +101,7 @@
|
||||
"check:ci:windows-observational-ready": "tsx scripts/run-gates.ts ci-windows-observational-ready",
|
||||
"check:node-compat": "tsx scripts/run-gates.ts node-compat",
|
||||
"publint": "tsx scripts/publint-all.ts",
|
||||
"doc-typecheck": "tsx scripts/compile-referenced-projects.ts host-libraries && npm run doc-typecheck:contracts-ready",
|
||||
"doc-typecheck": "tsx scripts/compile-referenced-projects.ts host-contracts && npm run doc-typecheck:contracts-ready",
|
||||
"doc-typecheck:contracts-ready": "tsx scripts/doc-typecheck.ts",
|
||||
"verify-md-wrap": "tsx scripts/verify-md-wrap.ts",
|
||||
"verify-md-links": "tsx scripts/verify-md-links.ts",
|
||||
|
||||
@@ -15,8 +15,8 @@
|
||||
en: 1fdf707322fb6996
|
||||
zh: 0204f7e9d4aa3cce
|
||||
/session-controller/use-this-package:
|
||||
en: d26a58a8f2406cd5
|
||||
zh: 82135eceb9adb628
|
||||
en: d8c0e2b2e45fa75d
|
||||
zh: 025b50be4204580c
|
||||
/session-controller/client-references:
|
||||
en: 41bdda1ac32df558
|
||||
zh: aa5d0e325924066b
|
||||
|
||||
@@ -39,7 +39,7 @@ Host list generation yields between complete rows only when its configured work
|
||||
|
||||
Client list rows and resident Sessions use the current `sessionListMetadata` projection to reject stale blank-session hints; recency is the later of the summary timestamp and the projected last user prompt. When SessionManager creates an instance before its list row arrives, it reconciles blankness with metadata already retained for that Session. An opened conversation is therefore not reused by New Session even when an older list response still marks it blank.
|
||||
|
||||
Explicit-id `session.create` adopts a live Session or resumes a persisted Session while retaining its writer lock. Writer contention returns `session/writer-held`; callers may try another blank without suppressing unrelated failures. `session.list` includes persisted blanks using cached metadata, without opening cold log bodies.
|
||||
`session.create` returns a Session for a new conversation, and its response names the Session actually used. A named `sessionId` is reused while it is blank (no turn has started), belongs to the requested directory, is an unarchived member of the requested Workspace, and is not written by another owner; a live Session is reused in place, and a persisted one is resumed while retaining its writer lock. The reused Session runs the requested `agentPreset`, or the configured default when the request names none: its recorded preset is not resolved, and a change is logged as `agent-preset/selected` before the Agent is published. A named Session that has started, fails the Workspace placement, or is written by another owner stays unchanged, and a new Session is created instead. A `sessionId` with no stored Session becomes the new Session's identity. A named Session in another directory fails with `session/conflict`, and one owned by subagent routing with `session/agent-busy`; both checks precede preset resolution. Creations naming one identity run in arrival order, including their preset resolution, and each response reports the preset its own request left the Session running. `session.list` includes persisted blanks using cached metadata, without opening cold log bodies.
|
||||
|
||||
Client list refreshes retain unchanged row objects and reuse the items array when order and values match. Each row's `retainedBy` contains positive local reference-source counts; Host metadata refreshes cannot overwrite them. Cache membership checks use a per-refresh ID set, so reconciliation grows linearly with the current list and retained cache sizes. Host summary updates replace running and Agent availability; local create/fork responses only fill missing metadata on existing rows. Removed ordinary Sessions retain projection stores only when their catalogs contain children.
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@ Host 仅在配置的工作时间片耗尽时,于完整条目之间让出事件
|
||||
|
||||
Client 列表行和驻留 Session 使用当前 `sessionListMetadata` 投影纠正过期的空白会话提示;最近活动时间取摘要时间戳与投影中最后一次用户提示词时间的较晚值。当 SessionManager 在列表行到达前创建实例时,会使用已保留的该 Session 元数据对账空白状态。因此,即使旧列表响应仍将已有对话标为空白,新会话操作也不会复用已经打开过的对话。
|
||||
|
||||
显式 ID 的 `session.create` 会收养活动 Session,或恢复持久化 Session 并持续持有其写锁。写锁争用返回 `session/writer-held`;调用方可以尝试其他空白会话,同时保留其他失败。`session.list` 根据缓存元数据列出持久化空白会话,不打开冷日志正文。
|
||||
`session.create` 返回一个用于新对话的 Session,响应指明实际使用的 Session。请求指明的 `sessionId` 在满足以下条件时被复用:仍为空白(尚未开始任何轮次)、属于请求的目录、是请求的工作区中未归档的成员,且未被其他写者占用;活动 Session 原地复用,持久化 Session 被恢复并持续持有其写锁。被复用的 Session 运行请求的 `agentPreset`,请求未指明时运行配置的默认 preset:不解析它记录的 preset,变更在 Agent 发布前记录为 `agent-preset/selected`。指明的 Session 若已开始、不满足工作区归属,或被其他写者占用,则保持不变,改为新建 Session。没有对应已存储 Session 的 `sessionId` 成为新 Session 的标识。指明其他目录中的 Session 返回 `session/conflict`,指明由 subagent 路由拥有的 Session 返回 `session/agent-busy`;这两项检查先于 preset 解析。指明同一标识的创建请求按到达顺序执行,preset 解析也包含在内,每个响应报告其自身请求完成时该 Session 运行的 preset。`session.list` 根据缓存元数据列出持久化空白会话,不打开冷日志正文。
|
||||
|
||||
Client 列表刷新保留未变化的行对象,并在顺序和值均相同时复用条目数组。每行的 `retainedBy` 包含正数的本地引用来源计数,Host 元数据刷新不能覆盖它们。缓存成员检查使用每次刷新构建的 ID 集合,因此对账成本随当前列表和保留缓存的规模线性增长。 Host 摘要更新会替换运行状态与 Agent 可用性;本地 create/fork 响应只补充已有行缺失的元数据。普通 Session 被移除后,仅在目录仍有子项时保留其投影 store。
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
/** Agent activation, composition, and model-selection policy owned by API Session. */
|
||||
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { mkdir } from 'node:fs/promises'
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import { installModelSelection } from '@deepseek-ai/dsh-agent'
|
||||
@@ -8,11 +9,12 @@ import type {
|
||||
} from '@deepseek-ai/dsh-agent'
|
||||
import type {} from '@deepseek-ai/dsh-agent-default-model'
|
||||
import type {} from '@deepseek-ai/dsh-agent-preset-registry'
|
||||
import { brandString } from '@deepseek-ai/dsh-brand'
|
||||
import { ReasoningEffortId } from '@deepseek-ai/dsh-llm'
|
||||
import type { Session, SessionId } from '@deepseek-ai/dsh-session'
|
||||
import type { SessionInspection } from '@deepseek-ai/dsh-session-persistence'
|
||||
import { SessionQueryError, type SessionObservation } from '@deepseek-ai/dsh-session-query'
|
||||
import { RemoteError } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import { RemoteError, remoteErrorOf } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import type {} from '@deepseek-ai/dsh-typert-registry'
|
||||
import type { ModelSelection } from './types.ts'
|
||||
|
||||
@@ -42,21 +44,49 @@ export class ApiSessionCwdConflict extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
/** Explicit-id creation attempted to adopt a Session under another preset. */
|
||||
/** Reuse of a Session named an Agent preset while the deployment composes no preset roster. */
|
||||
export class ApiSessionPresetConflict extends Error {
|
||||
constructor(
|
||||
readonly sessionId: SessionId,
|
||||
readonly requestedPreset: string,
|
||||
readonly existingPreset: string | undefined,
|
||||
) {
|
||||
super(
|
||||
existingPreset === undefined
|
||||
? `session "${sessionId}" records no agent preset and cannot be adopted under "${requestedPreset}"`
|
||||
: `session "${sessionId}" runs agent preset "${existingPreset}", not "${requestedPreset}"`,
|
||||
)
|
||||
super(`the deployment composes no agent preset roster, so session "${sessionId}" cannot run preset "${requestedPreset}"`)
|
||||
}
|
||||
}
|
||||
|
||||
/** A blank Session chosen for reuse started a turn before this Host acquired its writer. */
|
||||
class ApiSessionStartedSinceObserved extends Error {}
|
||||
|
||||
/** Placement and Agent preset for one Session created for a new conversation. */
|
||||
export interface ApiSessionCreateRequest {
|
||||
/** Blank Session to reuse, or the identity of a new Session when none is stored under it. */
|
||||
readonly sessionId?: SessionId
|
||||
/** Directory the Session owns. */
|
||||
readonly cwd: string
|
||||
/** Preset the Session runs; the configured default when omitted. */
|
||||
readonly agentPreset?: string
|
||||
/**
|
||||
* Placement rule the caller owns, such as Workspace membership and archive state.
|
||||
* @param sessionId - existing Session named by the request.
|
||||
* @returns whether that Session may be reused.
|
||||
*/
|
||||
readonly reusable: (sessionId: SessionId) => boolean
|
||||
}
|
||||
|
||||
/** The Session one creation request created or reused. */
|
||||
export interface ApiSessionCreated {
|
||||
/** Live Agent of the Session. */
|
||||
readonly agent: Agent
|
||||
/** Preset the Session ran when the request finished, before a later request for the same identity; absent without a roster. */
|
||||
readonly agentPreset: string | undefined
|
||||
}
|
||||
|
||||
/** Resolved preset and pre-publication Agent setup for one create or resume. */
|
||||
interface ApiSessionComposition {
|
||||
readonly agentPreset?: string
|
||||
readonly setup: AgentSetup
|
||||
}
|
||||
|
||||
/** Failures produced while resolving one ordinary Session identity to its live Agent. */
|
||||
export type ApiSessionAgentError = RemoteError<'session/not-found' | 'session/agent-busy' | 'session/writer-held' | 'gateway/internal'>
|
||||
|
||||
@@ -139,7 +169,7 @@ export async function inspectApiSession(
|
||||
/** Owns every operation that may create, resume, or configure a Web Agent. */
|
||||
export class ApiSessionAgentController {
|
||||
private readonly resumes = new Map<SessionId, Promise<Agent>>()
|
||||
private readonly creations = new Map<SessionId, Promise<Agent>>()
|
||||
private readonly claims = new Map<SessionId, Promise<void>>()
|
||||
private readonly selections = new WeakMap<Agent, InstalledSelection>()
|
||||
private readonly imageAdmissionChains = new WeakMap<Agent, Promise<void>>()
|
||||
|
||||
@@ -229,50 +259,26 @@ export class ApiSessionAgentController {
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve one requested identity, creating or resuming it once.
|
||||
* @param sessionId - requested Session identity.
|
||||
* @param cwd - directory the Session must own.
|
||||
* @param checkPersistedIdentity - whether to inspect a cold identity before creation.
|
||||
* @param presetId - optional Agent preset the Session must own.
|
||||
* @returns the matching live ordinary Agent.
|
||||
* Create a Session for a new conversation, reusing the named blank Session
|
||||
* while it is still reusable. A reused Session runs the requested preset, or
|
||||
* the configured default when the request names none; the preset it recorded
|
||||
* is not resolved, and a change is logged as `agent-preset/selected` before
|
||||
* the Agent is published. A named Session that has started a turn, fails the
|
||||
* caller's placement rule, or is written by another owner stays unchanged,
|
||||
* and a new Session is created instead. Requests naming one identity run in
|
||||
* arrival order, including their preset resolution, and check the named
|
||||
* Session's directory and ownership before resolving the preset.
|
||||
* @param request - optional Session to reuse, directory, preset, and placement rule.
|
||||
* @returns the reused or created Session and the preset it ran when this request finished.
|
||||
* @throws ApiSessionCwdConflict when the named Session belongs to another directory.
|
||||
* @throws ApiSessionSubagentOwnership when subagent routing owns the named Session.
|
||||
* @throws RemoteError `agent-preset/not-found` or `agent-preset/invalid` for the requested or default preset.
|
||||
* @throws ApiSessionPresetConflict when no roster is composed and the request names a preset for a reused Session.
|
||||
*/
|
||||
async ensureSession(
|
||||
sessionId: SessionId,
|
||||
cwd: string,
|
||||
checkPersistedIdentity: boolean,
|
||||
presetId?: string,
|
||||
): Promise<Agent> {
|
||||
let creation = this.creations.get(sessionId)
|
||||
if (creation === undefined) {
|
||||
creation = this.createOrAdopt(sessionId, cwd, checkPersistedIdentity, presetId)
|
||||
.catch((error: unknown) => {
|
||||
const live = this.ctx.agents.get(sessionId)
|
||||
if (live !== undefined) {
|
||||
if (hasApiSessionSubagentOwner(this.ctx, live.session, live)) {
|
||||
throw new ApiSessionSubagentOwnership(sessionId)
|
||||
}
|
||||
return live
|
||||
}
|
||||
const attached = this.ctx.sessions.get(sessionId)
|
||||
if (attached !== undefined && hasApiSessionSubagentOwner(this.ctx, attached, undefined)) {
|
||||
throw new ApiSessionSubagentOwnership(sessionId)
|
||||
}
|
||||
throw error
|
||||
})
|
||||
.finally(() => { this.creations.delete(sessionId) })
|
||||
this.creations.set(sessionId, creation)
|
||||
}
|
||||
const agent = await creation
|
||||
if (hasApiSessionSubagentOwner(this.ctx, agent.session, agent)) {
|
||||
throw new ApiSessionSubagentOwnership(sessionId)
|
||||
}
|
||||
if (presetId !== undefined) {
|
||||
this.assertPresetUnchanged(sessionId, presetId, this.presetForSession(agent.session))
|
||||
}
|
||||
if (agent.session.header.cwd !== cwd) {
|
||||
throw new ApiSessionCwdConflict(sessionId, cwd, agent.session.header.cwd)
|
||||
}
|
||||
return agent
|
||||
async createSession(request: ApiSessionCreateRequest): Promise<ApiSessionCreated> {
|
||||
const named = request.sessionId
|
||||
if (named === undefined) return this.created(await this.createMinted(request.cwd, await this.composeAgent(request.agentPreset)))
|
||||
return this.inOrder(named, async () => this.created(await this.claim(named, request)))
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -378,10 +384,7 @@ export class ApiSessionAgentController {
|
||||
* @param presetId - requested preset or the configured default when omitted.
|
||||
* @returns the resolved preset identity and Agent setup callback.
|
||||
*/
|
||||
async composeAgent(presetId: string | undefined): Promise<{
|
||||
readonly agentPreset?: string
|
||||
readonly setup: AgentSetup
|
||||
}> {
|
||||
async composeAgent(presetId: string | undefined): Promise<ApiSessionComposition> {
|
||||
const presets = this.ctx.get('agentPresets')
|
||||
if (presets === undefined) {
|
||||
return { setup: (_agentCtx, agent) => { this.installSelection(agent) } }
|
||||
@@ -441,48 +444,128 @@ export class ApiSessionAgentController {
|
||||
})).agent
|
||||
}
|
||||
|
||||
private async createOrAdopt(
|
||||
sessionId: SessionId,
|
||||
cwd: string,
|
||||
checkPersistedIdentity: boolean,
|
||||
presetId: string | undefined,
|
||||
): Promise<Agent> {
|
||||
private async inOrder<Value>(sessionId: SessionId, operation: () => Promise<Value>): Promise<Value> {
|
||||
const result = (this.claims.get(sessionId) ?? Promise.resolve()).then(operation)
|
||||
const settled = result.then(() => undefined, () => undefined)
|
||||
this.claims.set(sessionId, settled)
|
||||
try {
|
||||
return await result
|
||||
} finally {
|
||||
if (this.claims.get(sessionId) === settled) this.claims.delete(sessionId)
|
||||
}
|
||||
}
|
||||
|
||||
/** @returns the reused Session, a new Session under `sessionId` when none is stored, or a new Session under a minted identity. */
|
||||
private async claim(sessionId: SessionId, request: ApiSessionCreateRequest): Promise<Agent> {
|
||||
const attached = this.ctx.sessions.get(sessionId)
|
||||
const live = this.ctx.agents.get(sessionId)
|
||||
if (attached !== undefined && hasApiSessionSubagentOwner(this.ctx, attached, live)) {
|
||||
throw new ApiSessionSubagentOwnership(sessionId)
|
||||
}
|
||||
if (live !== undefined) return live
|
||||
|
||||
if (checkPersistedIdentity) {
|
||||
try {
|
||||
using observation = await this.ctx.sessionQuery.observeSession(sessionId)
|
||||
if (hasApiSessionSubagentOwner(this.ctx, { header: observation.header }, undefined)) {
|
||||
throw new ApiSessionSubagentOwnership(sessionId)
|
||||
}
|
||||
if (observation.header.cwd !== cwd) {
|
||||
throw new ApiSessionCwdConflict(sessionId, cwd, observation.header.cwd)
|
||||
}
|
||||
const storedPreset = this.presetForObservation(observation)
|
||||
this.assertPresetUnchanged(sessionId, presetId, storedPreset)
|
||||
const composition = await this.composeAgent(storedPreset)
|
||||
return (await this.ctx.agents.resume({
|
||||
resumeSessionId: sessionId,
|
||||
agentOptions: this.agentOptions(),
|
||||
setup: composition.setup,
|
||||
})).agent
|
||||
} catch (error: unknown) {
|
||||
if (!(error instanceof SessionQueryError)
|
||||
|| error.code !== 'SESSION_QUERY_SESSION_NOT_FOUND') throw error
|
||||
if (live !== undefined) {
|
||||
if (live.session.header.cwd !== request.cwd) {
|
||||
throw new ApiSessionCwdConflict(live.id, request.cwd, live.session.header.cwd)
|
||||
}
|
||||
const composition = await this.composeAgent(request.agentPreset)
|
||||
return await this.reuseLive(live, request, composition) ?? this.createMinted(request.cwd, composition)
|
||||
}
|
||||
let observation: SessionObservation
|
||||
try {
|
||||
observation = await this.ctx.sessionQuery.observeSession(sessionId)
|
||||
} catch (error: unknown) {
|
||||
if (!(error instanceof SessionQueryError) || error.code !== 'SESSION_QUERY_SESSION_NOT_FOUND') throw error
|
||||
return this.createAgent(sessionId, request.cwd, await this.composeAgent(request.agentPreset))
|
||||
}
|
||||
let reusable: boolean
|
||||
{
|
||||
using observed = observation
|
||||
if (hasApiSessionSubagentOwner(this.ctx, { header: observed.header }, undefined)) {
|
||||
throw new ApiSessionSubagentOwnership(sessionId)
|
||||
}
|
||||
if (observed.header.cwd !== request.cwd) {
|
||||
throw new ApiSessionCwdConflict(sessionId, request.cwd, observed.header.cwd)
|
||||
}
|
||||
reusable = request.reusable(sessionId) && !observed.events.some(event => event.type === 'turn/start')
|
||||
}
|
||||
const composition = await this.composeAgent(request.agentPreset)
|
||||
if (!reusable) return this.createMinted(request.cwd, composition)
|
||||
this.assertPresetApplicable(sessionId, request.agentPreset)
|
||||
try {
|
||||
return (await this.ctx.agents.resume({
|
||||
resumeSessionId: sessionId,
|
||||
agentOptions: this.agentOptions(),
|
||||
setup: this.reuseSetup(composition),
|
||||
})).agent
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof ApiSessionStartedSinceObserved) return this.createMinted(request.cwd, composition)
|
||||
if (!(error instanceof Error) || error.name !== 'SessionAlreadyOwnedError') throw error
|
||||
// Another resume in this process may hold the writer for the Agent it published.
|
||||
return this.ctx.agents.get(sessionId) === undefined
|
||||
? this.createMinted(request.cwd, composition)
|
||||
: this.claim(sessionId, request)
|
||||
}
|
||||
}
|
||||
|
||||
/** @returns the live blank Session under the requested preset, or undefined when it cannot be reused. */
|
||||
private async reuseLive(
|
||||
live: Agent,
|
||||
request: ApiSessionCreateRequest,
|
||||
composition: ApiSessionComposition,
|
||||
): Promise<Agent | undefined> {
|
||||
if (!request.reusable(live.id) || !this.isBlank(live.session)) return undefined
|
||||
this.assertPresetApplicable(live.id, request.agentPreset)
|
||||
const current = this.presetForSession(live.session)
|
||||
const presets = this.ctx.get('agentPresets')
|
||||
const target = composition.agentPreset
|
||||
if (presets === undefined || target === undefined || target === current) return live
|
||||
try {
|
||||
await presets.select(live, target)
|
||||
} catch (error: unknown) {
|
||||
if (remoteErrorOf(error)?.code !== 'agent-preset/locked') throw error
|
||||
return undefined
|
||||
}
|
||||
return live
|
||||
}
|
||||
|
||||
/** Setup that re-checks blankness under the acquired writer, then records a preset change before publication. */
|
||||
private reuseSetup(composition: ApiSessionComposition): AgentSetup {
|
||||
return async (agentCtx, agent) => {
|
||||
if (!this.isBlank(agent.session)) throw new ApiSessionStartedSinceObserved()
|
||||
const commit = await composition.setup(agentCtx, agent)
|
||||
const target = composition.agentPreset
|
||||
if (target !== undefined && this.presetForSession(agent.session) !== target) {
|
||||
agent.session.append('agent-preset/selected', { agentPreset: target })
|
||||
}
|
||||
return commit
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether no turn has started, by the predicate the preset registry's `select` enforces. */
|
||||
private isBlank(session: Session): boolean {
|
||||
const boundary = this.ctx.sessionProjections.stateOf(session, 'turnBoundary')
|
||||
return boundary === undefined || (boundary.openTurnStartSeq === null && boundary.lastTurn === 0)
|
||||
}
|
||||
|
||||
/** Without a roster, reuse cannot apply a named preset. */
|
||||
private assertPresetApplicable(sessionId: SessionId, requested: string | undefined): void {
|
||||
if (requested === undefined || this.ctx.get('agentPresets') !== undefined) return
|
||||
throw new ApiSessionPresetConflict(sessionId, requested)
|
||||
}
|
||||
|
||||
private created(agent: Agent): ApiSessionCreated {
|
||||
return { agent, agentPreset: this.presetForSession(agent.session) }
|
||||
}
|
||||
|
||||
private createMinted(cwd: string, composition: ApiSessionComposition): Promise<Agent> {
|
||||
return this.createAgent(brandString<SessionId>(`session-${randomUUID()}`), cwd, composition)
|
||||
}
|
||||
|
||||
private async createAgent(sessionId: SessionId, cwd: string, composition: ApiSessionComposition): Promise<Agent> {
|
||||
try {
|
||||
await mkdir(cwd, { recursive: true })
|
||||
} catch (error: unknown) {
|
||||
throw new Error(`failed to ensure project directory "${cwd}": ${String(error)}`, { cause: error })
|
||||
}
|
||||
const composition = await this.composeAgent(presetId)
|
||||
return (await this.ctx.agents.create({
|
||||
sessionId,
|
||||
agentOptions: this.agentOptions(),
|
||||
@@ -514,15 +597,6 @@ export class ApiSessionAgentController {
|
||||
}
|
||||
return observation.projections.values.agentPreset ?? undefined
|
||||
}
|
||||
|
||||
private assertPresetUnchanged(
|
||||
sessionId: SessionId,
|
||||
requested: string | undefined,
|
||||
existing: string | undefined,
|
||||
): void {
|
||||
if (requested === undefined || requested === existing) return
|
||||
throw new ApiSessionPresetConflict(sessionId, requested, existing)
|
||||
}
|
||||
}
|
||||
|
||||
function agentModelSelection(selection: ModelSelection): AgentModelSelection {
|
||||
|
||||
@@ -79,14 +79,17 @@ export interface ISessions {
|
||||
*/
|
||||
readonly searchResultLimit: number
|
||||
/**
|
||||
* Create or adopt a Session on the Host.
|
||||
* @param opts - target workspace, directory, and optional preallocated identity.
|
||||
* @returns the catalogued identity; retain it before borrowing its binding.
|
||||
* Create a Session for a new conversation on the Host. The Host reuses the
|
||||
* named blank Session while it is reusable and otherwise creates another; the
|
||||
* Session runs the named preset, or the Host default when none is named.
|
||||
* @param opts - target workspace or directory, an optional blank Session to reuse, and an optional Agent preset.
|
||||
* @returns the catalogued identity the Host created or reused; retain it before borrowing its binding.
|
||||
*/
|
||||
create(opts?: {
|
||||
workspaceId?: WorkspaceId
|
||||
cwd?: string
|
||||
sessionId?: SessionId
|
||||
agentPreset?: string
|
||||
}): Promise<SessionId>
|
||||
/**
|
||||
* Resolve an already discovered direct-parent address without opening it.
|
||||
|
||||
@@ -502,17 +502,21 @@ export class SessionManager {
|
||||
* Contract session.create; on success merge into summaries immediately (no
|
||||
* wait for the next refresh). A created session is blank by definition
|
||||
* (entity birth precedes the first message).
|
||||
* @param opts - target workspace or working directory, plus an optional caller-owned id.
|
||||
* @returns the create result.
|
||||
* @param opts - target workspace or working directory, an optional blank Session to reuse, and an optional Agent preset.
|
||||
* @returns the create result, naming the Session the Host created or reused.
|
||||
*/
|
||||
async create(
|
||||
opts: {
|
||||
workspaceId?: WorkspaceId
|
||||
cwd?: string
|
||||
sessionId?: SessionId
|
||||
agentPreset?: string
|
||||
} = {},
|
||||
): Promise<RemoteResult<{ sessionId: SessionId }>> {
|
||||
const shared = opts.sessionId === undefined ? {} : { sessionId: opts.sessionId }
|
||||
const shared = {
|
||||
...(opts.sessionId === undefined ? {} : { sessionId: opts.sessionId }),
|
||||
...(opts.agentPreset === undefined ? {} : { agentPreset: opts.agentPreset }),
|
||||
}
|
||||
const payload = opts.workspaceId !== undefined
|
||||
? { workspaceId: opts.workspaceId, ...shared }
|
||||
: { ...(opts.cwd === undefined ? {} : { cwd: opts.cwd }), ...shared }
|
||||
|
||||
@@ -427,11 +427,16 @@ export class ClientSessions implements ISessions {
|
||||
/**
|
||||
* Create a Host Session and publish its catalog row before resolving.
|
||||
* Callers retain the returned identity before borrowing its binding.
|
||||
* @param opts - target workspace or directory and an optional preallocated id.
|
||||
* @returns the new session id.
|
||||
* @param opts - target workspace or directory, an optional blank Session to reuse, and an optional Agent preset.
|
||||
* @returns the created or reused session id.
|
||||
* @throws {SessionCreateError} with the requested id.
|
||||
*/
|
||||
async create(opts: { workspaceId?: WorkspaceId; cwd?: string; sessionId?: SessionId } = {}): Promise<SessionId> {
|
||||
async create(opts: {
|
||||
workspaceId?: WorkspaceId
|
||||
cwd?: string
|
||||
sessionId?: SessionId
|
||||
agentPreset?: string
|
||||
} = {}): Promise<SessionId> {
|
||||
const result = await this.manager.create(opts)
|
||||
if (!result.ok) throw new SessionCreateError(result.error, opts.sessionId)
|
||||
this.projectList()
|
||||
|
||||
@@ -33,6 +33,7 @@ import {
|
||||
apiSessionSubagentOwnershipError,
|
||||
hasApiSessionSubagentOwner,
|
||||
inspectApiSession,
|
||||
type ApiSessionCreated,
|
||||
} from './agent.ts'
|
||||
import type {
|
||||
SessionAttachmentRequest,
|
||||
@@ -98,15 +99,15 @@ export class SessionCommandController {
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Create or idempotently adopt one ordinary Session.
|
||||
* @param request - requested identity, location, and Agent preset.
|
||||
* @returns the Session identity and resolved preset when configured.
|
||||
* Create one ordinary Session for a new conversation, reusing the named
|
||||
* blank Session while it is an unarchived member of the requested Workspace.
|
||||
* @param request - optional blank Session to reuse, location, and Agent preset.
|
||||
* @returns the created or reused Session identity and its preset when configured.
|
||||
*/
|
||||
async create(request: SessionCreateRequest): Promise<SessionCreateValue> {
|
||||
if (request.workspaceId !== undefined && request.cwd !== undefined) {
|
||||
throw new RemoteError('gateway/bad-request', 'session.create accepts workspaceId or cwd, not both', {})
|
||||
}
|
||||
const sessionId = request.sessionId ?? brandString<SessionId>(`session-${randomUUID()}`)
|
||||
let workspace: Workspace | undefined
|
||||
if (request.workspaceId !== undefined) {
|
||||
workspace = this.ctx.workspaceRegistry.get(request.workspaceId)
|
||||
@@ -117,17 +118,19 @@ export class SessionCommandController {
|
||||
}
|
||||
}
|
||||
const cwd = workspace?.path ?? request.cwd ?? this.defaultCwd
|
||||
let adopted: Agent
|
||||
let created: ApiSessionCreated
|
||||
try {
|
||||
adopted = await this.agents.ensureSession(
|
||||
sessionId,
|
||||
created = await this.agents.createSession({
|
||||
...(request.sessionId === undefined ? {} : { sessionId: request.sessionId }),
|
||||
cwd,
|
||||
request.sessionId !== undefined,
|
||||
request.agentPreset,
|
||||
)
|
||||
...(request.agentPreset === undefined ? {} : { agentPreset: request.agentPreset }),
|
||||
reusable: sessionId => !this.ctx.workspaceRegistry.archivedSessionIds.includes(sessionId)
|
||||
&& (workspace === undefined || workspace.sessionIds.includes(sessionId)),
|
||||
})
|
||||
} catch (error) {
|
||||
this.rejectCreation(sessionId, error)
|
||||
this.rejectCreation(error)
|
||||
}
|
||||
const sessionId = created.agent.id
|
||||
if (workspace !== undefined) {
|
||||
try {
|
||||
await workspace.attachSession(sessionId)
|
||||
@@ -139,8 +142,7 @@ export class SessionCommandController {
|
||||
)
|
||||
}
|
||||
}
|
||||
const agentPreset = this.agents.presetForSession(adopted.session)
|
||||
return { sessionId, ...(agentPreset === undefined ? {} : { agentPreset }) }
|
||||
return { sessionId, ...(created.agentPreset === undefined ? {} : { agentPreset: created.agentPreset }) }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -530,16 +532,12 @@ export class SessionCommandController {
|
||||
return found.agent
|
||||
}
|
||||
|
||||
private rejectCreation(sessionId: SessionId, error: unknown): never {
|
||||
private rejectCreation(error: unknown): never {
|
||||
if (remoteErrorOf(error) !== undefined) throw error
|
||||
if (error instanceof Error && error.name === 'SessionAlreadyOwnedError') {
|
||||
throw new RemoteError('session/writer-held', error.message, { sessionId })
|
||||
}
|
||||
if (error instanceof ApiSessionPresetConflict) {
|
||||
throw new RemoteError('agent-preset/conflict', error.message, {
|
||||
sessionId: error.sessionId,
|
||||
requestedPreset: error.requestedPreset,
|
||||
...(error.existingPreset === undefined ? {} : { existingPreset: error.existingPreset }),
|
||||
})
|
||||
}
|
||||
if (error instanceof ApiSessionCwdConflict) {
|
||||
@@ -552,7 +550,7 @@ export class SessionCommandController {
|
||||
if (error instanceof ApiSessionSubagentOwnership) {
|
||||
throw apiSessionSubagentOwnershipError(error.sessionId)
|
||||
}
|
||||
throw new RemoteError('gateway/internal', `failed to create session "${sessionId}": ${String(error)}`, {})
|
||||
throw new RemoteError('gateway/internal', `failed to create session: ${String(error)}`, {})
|
||||
}
|
||||
|
||||
private async readSessionState(sessionId: SessionId): Promise<SessionReadState> {
|
||||
|
||||
@@ -273,9 +273,9 @@ export class SessionController extends TypertRemoteService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Create or idempotently adopt one ordinary Session.
|
||||
* @param request - requested identity, location, and Agent preset.
|
||||
* @returns the Session identity and resolved preset when configured.
|
||||
* Create one ordinary Session for a new conversation, reusing the named blank Session while it is reusable.
|
||||
* @param request - optional blank Session to reuse, location, and Agent preset.
|
||||
* @returns the created or reused Session identity and its preset when configured.
|
||||
*/
|
||||
@Remote('create')
|
||||
create(request: SessionCreateRequest): Promise<SessionCreateValue> {
|
||||
|
||||
@@ -219,7 +219,6 @@ declare module '@deepseek-ai/dsh-typert-protocol' {
|
||||
'agent-preset/conflict': {
|
||||
readonly sessionId: SessionId
|
||||
readonly requestedPreset: string
|
||||
readonly existingPreset?: string
|
||||
}
|
||||
'session/attachment-invalid': { readonly reason: string }
|
||||
'session/queue-item-not-found': { readonly itemId: MessageId }
|
||||
@@ -284,17 +283,23 @@ export interface SessionSearchValue {
|
||||
readonly hasMore: boolean
|
||||
}
|
||||
|
||||
/** Session creation or explicit-id adoption request. */
|
||||
/** Request for a Session for a new conversation. */
|
||||
export interface SessionCreateRequest {
|
||||
/** Workspace the Session joins; exclusive with `cwd`. */
|
||||
readonly workspaceId?: WorkspaceId
|
||||
/** Directory the Session owns when no Workspace is named. */
|
||||
readonly cwd?: string
|
||||
/** Blank Session to reuse while it is reusable, or the identity of a new Session when none is stored under it. */
|
||||
readonly sessionId?: SessionId
|
||||
/** Preset the Session runs, replacing a reused Session's recorded preset; the configured default when omitted. */
|
||||
readonly agentPreset?: string
|
||||
}
|
||||
|
||||
/** Session creation response value. */
|
||||
export interface SessionCreateValue {
|
||||
/** The created or reused Session, which may differ from the requested `sessionId`. */
|
||||
readonly sessionId: SessionId
|
||||
/** Preset the Session runs, when the deployment composes a preset roster. */
|
||||
readonly agentPreset?: string
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ import AgentRegistry from '@deepseek-ai/dsh-agent'
|
||||
import type { Agent } from '@deepseek-ai/dsh-agent'
|
||||
import { agentPresetProjectionDefinition } from '@deepseek-ai/dsh-agent-preset-registry'
|
||||
import SessionStore, { SESSION_FORMAT_VERSION, SessionLogOffset, SessionId } from '@deepseek-ai/dsh-session'
|
||||
import type { SessionEvent, SessionHeader } from '@deepseek-ai/dsh-session'
|
||||
import type { SessionHeader } from '@deepseek-ai/dsh-session'
|
||||
import { SessionAlreadyOwnedError } from '@deepseek-ai/dsh-session-persistence'
|
||||
import type { SessionObservation } from '@deepseek-ai/dsh-session-query'
|
||||
import TypertRegistry from '@deepseek-ai/dsh-typert-registry'
|
||||
@@ -15,7 +15,6 @@ import {
|
||||
ApiSessionAgentController,
|
||||
ApiSessionCwdConflict,
|
||||
ApiSessionNotFound,
|
||||
ApiSessionSubagentOwnership,
|
||||
inspectApiSession,
|
||||
} from '../src/agent.ts'
|
||||
import { installModelSelectionProjection } from '../src/model-selection-projection.ts'
|
||||
@@ -329,123 +328,8 @@ describe('ApiSession model selection', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('ApiSession create or adoption', () => {
|
||||
it('shares one in-flight creation between concurrent callers', async () => {
|
||||
const { ctx, agents } = await harness()
|
||||
const cwd = mkdtempSync(join(tmpdir(), 'dsh-session-controller-concurrent-'))
|
||||
tempDirs.push(cwd)
|
||||
const meta = header('concurrent-create', cwd)
|
||||
const created = unpublishedAgent(ctx, meta)
|
||||
let release!: () => void
|
||||
const gate = new Promise<void>((resolve) => { release = resolve })
|
||||
const create = vi.spyOn(ctx.agents, 'create').mockImplementation(async () => {
|
||||
await gate
|
||||
return { agent: created, dispose: () => Promise.resolve() }
|
||||
})
|
||||
|
||||
const first = agents.ensureSession(meta.id, cwd, false)
|
||||
const second = agents.ensureSession(meta.id, cwd, false)
|
||||
release()
|
||||
|
||||
await expect(Promise.all([first, second])).resolves.toEqual([created, created])
|
||||
expect(create).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('accepts a raced ordinary creation and rejects a raced attached child', async () => {
|
||||
const ordinary = await harness()
|
||||
const cwd = mkdtempSync(join(tmpdir(), 'dsh-session-controller-create-'))
|
||||
tempDirs.push(cwd)
|
||||
const ordinaryMeta = header('create-race', cwd)
|
||||
const winner = agent(ordinary.ctx, ordinaryMeta)
|
||||
vi.spyOn(ordinary.ctx.agents, 'create').mockImplementation(async () => {
|
||||
await ordinary.ctx.agents.register(winner)
|
||||
throw new Error('raced creation')
|
||||
})
|
||||
await expect(ordinary.agents.ensureSession(ordinaryMeta.id, cwd, false))
|
||||
.resolves.toBe(winner)
|
||||
|
||||
const child = await harness()
|
||||
const childCwd = mkdtempSync(join(tmpdir(), 'dsh-session-controller-child-'))
|
||||
tempDirs.push(childCwd)
|
||||
const childId = SessionId('create-child-race')
|
||||
vi.spyOn(child.ctx.agents, 'create').mockImplementation(async () => {
|
||||
child.ctx.sessions.create(childId, {
|
||||
meta: { cwd: childCwd, parentSession: SessionId('parent'), origin: 'subagent' },
|
||||
})
|
||||
throw new Error('raced child creation')
|
||||
})
|
||||
await expect(child.agents.ensureSession(childId, childCwd, false))
|
||||
.rejects.toBeInstanceOf(ApiSessionSubagentOwnership)
|
||||
})
|
||||
|
||||
it('validates ownership and cwd on the Agent returned by creation', async () => {
|
||||
const child = await harness()
|
||||
const childCwd = mkdtempSync(join(tmpdir(), 'dsh-session-controller-returned-child-'))
|
||||
tempDirs.push(childCwd)
|
||||
const childMeta = {
|
||||
...header('returned-child', childCwd),
|
||||
parentSession: SessionId('parent'),
|
||||
origin: 'subagent' as const,
|
||||
}
|
||||
const childAgent = unpublishedAgent(child.ctx, childMeta)
|
||||
vi.spyOn(child.ctx.agents, 'create').mockResolvedValue({
|
||||
agent: childAgent,
|
||||
dispose: () => Promise.resolve(),
|
||||
})
|
||||
await expect(child.agents.ensureSession(childMeta.id, childCwd, false))
|
||||
.rejects.toBeInstanceOf(ApiSessionSubagentOwnership)
|
||||
|
||||
const wrong = await harness()
|
||||
const requestedCwd = mkdtempSync(join(tmpdir(), 'dsh-session-controller-wrong-cwd-'))
|
||||
tempDirs.push(requestedCwd)
|
||||
const wrongAgent = unpublishedAgent(wrong.ctx, header('wrong-returned-cwd', '/other'))
|
||||
vi.spyOn(wrong.ctx.agents, 'create').mockResolvedValue({
|
||||
agent: wrongAgent,
|
||||
dispose: () => Promise.resolve(),
|
||||
})
|
||||
await expect(wrong.agents.ensureSession(wrongAgent.id, requestedCwd, false))
|
||||
.rejects.toBeInstanceOf(ApiSessionCwdConflict)
|
||||
})
|
||||
|
||||
it('resumes a matching persisted identity and preserves its selected preset', async () => {
|
||||
const { ctx, agents } = await harness()
|
||||
const meta = { ...header('stored'), agentPreset: 'minimal' }
|
||||
const events = [{
|
||||
type: 'agent-preset/selected',
|
||||
seq: 0,
|
||||
time: 1,
|
||||
data: { agentPreset: 'minimal' },
|
||||
}] as SessionEvent[]
|
||||
providePersistence(ctx, {
|
||||
list: () => Promise.resolve([meta]),
|
||||
inspect: () => Promise.resolve({ meta, events }),
|
||||
})
|
||||
ctx.provide('agentPresets', {
|
||||
resolve: (id?: string) => Promise.resolve({ id: id ?? 'minimal' }),
|
||||
mount: () => Promise.resolve(),
|
||||
} as never)
|
||||
const resumed = {
|
||||
id: meta.id,
|
||||
session: {
|
||||
id: meta.id,
|
||||
header: meta,
|
||||
snapshotEvents: () => events,
|
||||
eventAt: (seq: number) => events[seq],
|
||||
seq: events.length,
|
||||
},
|
||||
status: 'idle',
|
||||
ctx,
|
||||
} as unknown as Agent
|
||||
const resume = vi.spyOn(ctx.agents, 'resume').mockResolvedValue({
|
||||
agent: resumed,
|
||||
dispose: () => Promise.resolve(),
|
||||
})
|
||||
|
||||
await expect(agents.ensureSession(meta.id, '/workspace', true, 'minimal')).resolves.toBe(resumed)
|
||||
expect(resume).toHaveBeenCalledWith(expect.objectContaining({ resumeSessionId: meta.id }))
|
||||
})
|
||||
|
||||
it('rejects an ownership race before resume and a persisted cwd conflict', async () => {
|
||||
describe('ApiSession creation', () => {
|
||||
it('rejects a resume that subagent routing adopts before publication', async () => {
|
||||
const child = await harness()
|
||||
const childMeta = header('resume-child-race')
|
||||
providePersistence(child.ctx, {
|
||||
@@ -464,15 +348,6 @@ describe('ApiSession create or adoption', () => {
|
||||
await expect(child.agents.resolveAgent(childMeta.id)).resolves.toMatchObject({
|
||||
error: { code: 'session/agent-busy' },
|
||||
})
|
||||
|
||||
const conflict = await harness()
|
||||
const stored = header('stored-cwd-conflict', '/stored')
|
||||
providePersistence(conflict.ctx, {
|
||||
list: () => Promise.resolve([stored]),
|
||||
inspect: () => Promise.resolve({ meta: stored, events: [] }),
|
||||
})
|
||||
await expect(conflict.agents.ensureSession(stored.id, '/requested', true))
|
||||
.rejects.toBeInstanceOf(ApiSessionCwdConflict)
|
||||
})
|
||||
|
||||
it('surfaces directory creation failure', async () => {
|
||||
@@ -481,7 +356,7 @@ describe('ApiSession create or adoption', () => {
|
||||
tempDirs.push(parent)
|
||||
const file = join(parent, 'file')
|
||||
writeFileSync(file, 'not a directory')
|
||||
await expect(agents.ensureSession(SessionId('mkdir-failure'), join(file, 'child'), false))
|
||||
await expect(agents.createSession({ cwd: join(file, 'child'), reusable: () => true }))
|
||||
.rejects.toThrow('failed to ensure project directory')
|
||||
})
|
||||
})
|
||||
@@ -5,11 +5,14 @@ import type {} from '@deepseek-ai/dsh-agent-preset-registry'
|
||||
import { createUserMessage } from '@deepseek-ai/dsh-llm'
|
||||
import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
|
||||
import { RemoteError } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import TypertRegistry from '@deepseek-ai/dsh-typert-registry'
|
||||
import type { Workspace, WorkspaceId } from '@deepseek-ai/dsh-workspace'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
ApiSessionAgentController,
|
||||
ApiSessionCwdConflict,
|
||||
type ApiSessionCreated,
|
||||
type ApiSessionCreateRequest,
|
||||
} from '../src/agent.ts'
|
||||
import { SessionCommandController } from '../src/commands.ts'
|
||||
import { installSessionReadTestServices, testSessionPersistence } from './test-remote.ts'
|
||||
@@ -18,18 +21,31 @@ async function expectFailure(operation: Promise<unknown>, code: string): Promise
|
||||
await expect(operation).rejects.toMatchObject({ code })
|
||||
}
|
||||
|
||||
function controllerAgents(overrides: object = {}): ApiSessionAgentController {
|
||||
return {
|
||||
ensureSession: () => Promise.resolve(),
|
||||
composeAgent: () => Promise.resolve({ setup: () => {} }),
|
||||
presetForSession: () => undefined,
|
||||
presetForObservation: () => undefined,
|
||||
...overrides,
|
||||
} as unknown as ApiSessionAgentController
|
||||
/** The Agent controller with a fixed Agent composition, and optionally a fixed creation outcome. */
|
||||
function controllerAgents(
|
||||
ctx: Context,
|
||||
fixed: {
|
||||
readonly composeAgent?: ApiSessionAgentController['composeAgent']
|
||||
readonly createSession?: ApiSessionAgentController['createSession']
|
||||
} = {},
|
||||
): ApiSessionAgentController {
|
||||
const agents = new ApiSessionAgentController(ctx)
|
||||
vi.spyOn(agents, 'composeAgent').mockImplementation(fixed.composeAgent ?? (() => Promise.resolve({ setup: () => {} })))
|
||||
if (fixed.createSession !== undefined) vi.spyOn(agents, 'createSession').mockImplementation(fixed.createSession)
|
||||
return agents
|
||||
}
|
||||
|
||||
/** A creation outcome that publishes `sessionId` in `cwd` as a stand-in Agent. */
|
||||
function publishedSession(ctx: Context, sessionId: SessionId) {
|
||||
return (request: ApiSessionCreateRequest): Promise<ApiSessionCreated> => {
|
||||
const session = ctx.sessions.create(sessionId, { meta: { cwd: request.cwd } })
|
||||
return Promise.resolve({ agent: { id: session.id, session, status: 'idle', ctx } as Agent, agentPreset: undefined })
|
||||
}
|
||||
}
|
||||
|
||||
async function baseContext(): Promise<Context> {
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(TypertRegistry)
|
||||
await ctx.plugin(SessionStore)
|
||||
await ctx.plugin(AgentRegistry)
|
||||
installSessionReadTestServices(ctx)
|
||||
@@ -41,29 +57,19 @@ async function baseContext(): Promise<Context> {
|
||||
}
|
||||
|
||||
describe('Session creation failures', () => {
|
||||
it('mints an identity with the default cwd when no explicit target is supplied', async () => {
|
||||
it('creates in the default cwd without a named identity when no explicit target is supplied', async () => {
|
||||
const ctx = await baseContext()
|
||||
ctx.provide('workspaceRegistry', { get: () => undefined, list: () => [] } as never)
|
||||
const ensureSession = vi.fn((sessionId: SessionId, cwd: string) => {
|
||||
const session = ctx.sessions.create(sessionId, { meta: { cwd } })
|
||||
return Promise.resolve({ id: sessionId, session } as Agent)
|
||||
})
|
||||
const controller = new SessionCommandController(
|
||||
ctx,
|
||||
controllerAgents({ ensureSession }),
|
||||
'/default-workspace',
|
||||
)
|
||||
ctx.provide('workspaceRegistry', { get: () => undefined, list: () => [], archivedSessionIds: [] } as never)
|
||||
const createSession = vi.fn(publishedSession(ctx, SessionId('session-minted')))
|
||||
const controller = new SessionCommandController(ctx, controllerAgents(ctx, { createSession }), '/default-workspace')
|
||||
|
||||
const created = await controller.create({})
|
||||
|
||||
expect(created.sessionId).toMatch(/^session-/)
|
||||
expect(created).not.toHaveProperty('agentPreset')
|
||||
expect(ensureSession).toHaveBeenCalledWith(
|
||||
created.sessionId,
|
||||
'/default-workspace',
|
||||
false,
|
||||
undefined,
|
||||
)
|
||||
expect(created).toEqual({ sessionId: 'session-minted' })
|
||||
expect(createSession).toHaveBeenCalledOnce()
|
||||
const request = createSession.mock.calls[0]?.[0]
|
||||
expect(request?.cwd).toBe('/default-workspace')
|
||||
expect(Object.keys(request ?? {}).sort()).toEqual(['cwd', 'reusable'])
|
||||
await ctx.fiber.dispose()
|
||||
})
|
||||
|
||||
@@ -72,7 +78,7 @@ describe('Session creation failures', () => {
|
||||
missing.provide('workspaceRegistry', { get: () => undefined, list: () => [] } as never)
|
||||
const missingController = new SessionCommandController(
|
||||
missing,
|
||||
controllerAgents(),
|
||||
controllerAgents(missing),
|
||||
'/default',
|
||||
)
|
||||
await expectFailure(missingController.create({
|
||||
@@ -92,7 +98,7 @@ describe('Session creation failures', () => {
|
||||
} as never)
|
||||
const failedController = new SessionCommandController(
|
||||
failed,
|
||||
controllerAgents(),
|
||||
controllerAgents(failed, { createSession: publishedSession(failed, SessionId('workspace-session')) }),
|
||||
'/default',
|
||||
)
|
||||
await expectFailure(failedController.create({
|
||||
@@ -119,10 +125,6 @@ describe('Session creation failures', () => {
|
||||
error: new ApiSessionCwdConflict(SessionId('wrong-cwd'), '/requested', '/stored'),
|
||||
code: 'session/conflict',
|
||||
},
|
||||
{
|
||||
error: Object.assign(new Error('writer already held'), { name: 'SessionAlreadyOwnedError' }),
|
||||
code: 'session/writer-held',
|
||||
},
|
||||
{
|
||||
error: new Error('factory unavailable'),
|
||||
code: 'gateway/internal',
|
||||
@@ -132,7 +134,7 @@ describe('Session creation failures', () => {
|
||||
ctx.provide('workspaceRegistry', { get: () => undefined, list: () => [] } as never)
|
||||
const controller = new SessionCommandController(
|
||||
ctx,
|
||||
controllerAgents({ ensureSession: () => Promise.reject(error) }),
|
||||
controllerAgents(ctx, { createSession: () => Promise.reject(error) }),
|
||||
'/default',
|
||||
)
|
||||
|
||||
@@ -144,7 +146,7 @@ describe('Session creation failures', () => {
|
||||
|
||||
it('rejects contradictory create targets', async () => {
|
||||
const ctx = await baseContext()
|
||||
const controller = new SessionCommandController(ctx, controllerAgents(), '/default')
|
||||
const controller = new SessionCommandController(ctx, controllerAgents(ctx), '/default')
|
||||
|
||||
await expectFailure(controller.create({
|
||||
workspaceId: 'workspace-1' as WorkspaceId,
|
||||
@@ -184,7 +186,7 @@ describe('Session fork failures', () => {
|
||||
const withoutPersistence = await baseContext()
|
||||
withoutPersistence.provide('workspaceRegistry', { list: () => [] } as never)
|
||||
const unavailableController = new SessionCommandController(
|
||||
withoutPersistence, controllerAgents(), '/default',
|
||||
withoutPersistence, controllerAgents(withoutPersistence), '/default',
|
||||
)
|
||||
await expectFailure(unavailableController.fork({
|
||||
sessionId: SessionId('missing'),
|
||||
@@ -197,7 +199,7 @@ describe('Session fork failures', () => {
|
||||
list: () => Promise.resolve([]),
|
||||
inspect: vi.fn(),
|
||||
}) as never)
|
||||
const missingController = new SessionCommandController(missing, controllerAgents(), '/default')
|
||||
const missingController = new SessionCommandController(missing, controllerAgents(missing), '/default')
|
||||
await expectFailure(missingController.fork({
|
||||
sessionId: SessionId('missing'),
|
||||
}), 'session/not-found')
|
||||
@@ -208,7 +210,7 @@ describe('Session fork failures', () => {
|
||||
const ctx = await baseContext()
|
||||
ctx.provide('workspaceRegistry', { list: () => [] } as never)
|
||||
vi.spyOn(ctx.sessionQuery, 'observeSession').mockRejectedValue(new Error('storage offline'))
|
||||
const controller = new SessionCommandController(ctx, controllerAgents(), '/default')
|
||||
const controller = new SessionCommandController(ctx, controllerAgents(ctx), '/default')
|
||||
|
||||
await expectFailure(controller.fork({ sessionId: SessionId('unreadable') }), 'gateway/internal')
|
||||
await ctx.fiber.dispose()
|
||||
@@ -218,7 +220,7 @@ describe('Session fork failures', () => {
|
||||
const ctx = await baseContext()
|
||||
ctx.provide('workspaceRegistry', { list: () => [] } as never)
|
||||
const source = ctx.sessions.create(SessionId('empty-source'))
|
||||
const controller = new SessionCommandController(ctx, controllerAgents(), '/default')
|
||||
const controller = new SessionCommandController(ctx, controllerAgents(ctx), '/default')
|
||||
|
||||
await expectFailure(controller.fork({ sessionId: source.id }), 'session/fork-unavailable')
|
||||
await expect(controller.fork({ sessionId: source.id, atSeq: 0 })).rejects.toMatchObject({
|
||||
@@ -237,7 +239,7 @@ describe('Session fork failures', () => {
|
||||
parentSession: SessionId('parent'),
|
||||
origin: 'subagent',
|
||||
})
|
||||
const lineageController = new SessionCommandController(lineage, controllerAgents(), '/default')
|
||||
const lineageController = new SessionCommandController(lineage, controllerAgents(lineage), '/default')
|
||||
await expectFailure(lineageController.fork({ sessionId: child.id }), 'gateway/internal')
|
||||
await lineage.fiber.dispose()
|
||||
|
||||
@@ -245,7 +247,7 @@ describe('Session fork failures', () => {
|
||||
creation.provide('workspaceRegistry', { list: () => [] } as never)
|
||||
const source = completedSession(creation, 'creation-source', '/workspace')
|
||||
vi.spyOn(creation.agents, 'create').mockRejectedValue(new Error('factory failed'))
|
||||
const creationController = new SessionCommandController(creation, controllerAgents(), '/default')
|
||||
const creationController = new SessionCommandController(creation, controllerAgents(creation), '/default')
|
||||
await expectFailure(creationController.fork({ sessionId: source.id }), 'gateway/internal')
|
||||
await creation.fiber.dispose()
|
||||
})
|
||||
@@ -262,7 +264,7 @@ describe('Session fork failures', () => {
|
||||
const create = vi.spyOn(ctx.agents, 'create').mockImplementation(
|
||||
(options: CreateAgentOptions) => Promise.resolve(resolvedHandle(ctx, options.sessionId)),
|
||||
)
|
||||
const controller = new SessionCommandController(ctx, controllerAgents(), '/default')
|
||||
const controller = new SessionCommandController(ctx, controllerAgents(ctx), '/default')
|
||||
|
||||
await expectFailure(controller.fork({ sessionId: source.id }), 'session/workspace-attach-failed')
|
||||
const options = create.mock.calls[0]?.[0]
|
||||
@@ -279,7 +281,7 @@ describe('Session fork failures', () => {
|
||||
const create = vi.spyOn(ctx.agents, 'create').mockImplementation(
|
||||
(options: CreateAgentOptions) => Promise.resolve(resolvedHandle(ctx, options.sessionId)),
|
||||
)
|
||||
const controller = new SessionCommandController(ctx, controllerAgents({
|
||||
const controller = new SessionCommandController(ctx, controllerAgents(ctx, {
|
||||
composeAgent: () => Promise.resolve({ agentPreset: 'minimal', setup: () => {} }),
|
||||
}), '/default')
|
||||
|
||||
|
||||
@@ -1194,6 +1194,17 @@ describe('remaining branches', () => {
|
||||
expect(await manager.create()).toMatchObject({ ok: false })
|
||||
})
|
||||
|
||||
it('create forwards the requested Agent preset and catalogs the identity the Host returns', async ({ mock, remote }) => {
|
||||
remote.session.create.mockResolvedValue(ok({ sessionId: S2, agentPreset: 'minimal' }))
|
||||
const manager = makeManager(mock, remote)
|
||||
|
||||
const result = await manager.create({ workspaceId: 'w1' as never, sessionId: S1, agentPreset: 'minimal' })
|
||||
|
||||
expect(remote.session.create).toHaveBeenCalledExactlyOnceWith({ workspaceId: 'w1', sessionId: S1, agentPreset: 'minimal' })
|
||||
expect(result).toMatchObject({ ok: true, value: { sessionId: S2 } })
|
||||
expect(manager.getListSnapshot().items.map(item => item.sessionId)).toEqual([S2])
|
||||
})
|
||||
|
||||
it.for(['create', 'fork'] as const)('preserves pushed running state when a %s response arrives later', async (operation, { mock, remote }) => {
|
||||
const response = Promise.withResolvers<Awaited<ReturnType<typeof remote.session.create>>>()
|
||||
remote.session[operation].mockImplementation(() => response.promise)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/** Session creation and adoption rules for Agent preset identity. */
|
||||
/** Session creation, blank-Session reuse, and Agent preset identity through `session.create`. */
|
||||
|
||||
import { mkdtempSync, realpathSync, rmSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
@@ -6,12 +6,14 @@ import { join } from 'node:path'
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import AgentRegistry from '@deepseek-ai/dsh-agent'
|
||||
import type { Agent, AgentFactory } from '@deepseek-ai/dsh-agent'
|
||||
import { turnBoundaryProjectionDefinition } from '@deepseek-ai/dsh-agent-loop'
|
||||
import { agentPresetProjectionDefinition } from '@deepseek-ai/dsh-agent-preset-registry'
|
||||
import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
|
||||
import type { Session } from '@deepseek-ai/dsh-session'
|
||||
import SessionStore, { SESSION_FORMAT_VERSION, SessionId, SessionSeq } from '@deepseek-ai/dsh-session'
|
||||
import type { Session, SessionEvent, SessionHeader } from '@deepseek-ai/dsh-session'
|
||||
import { RemoteError } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { createSessionTestRemote } from './test-remote.ts'
|
||||
import type { WorkspaceId } from '@deepseek-ai/dsh-workspace'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createSessionTestRemote, testSessionPersistence } from './test-remote.ts'
|
||||
|
||||
/** Booted contexts and their temp roots, torn down after each test. */
|
||||
const contexts: Context[] = []
|
||||
@@ -25,53 +27,137 @@ function stubAgent(session: Session): Agent {
|
||||
return { id: session.id, session, status: 'idle' } as unknown as Agent
|
||||
}
|
||||
|
||||
function roster(ids: readonly string[]): unknown {
|
||||
const presetOf = (id: string): object => ({
|
||||
id,
|
||||
trust: 'system',
|
||||
})
|
||||
return {
|
||||
defaultId: ids[0],
|
||||
resolve: (id?: string) => {
|
||||
const wanted = id ?? ids[0] ?? ''
|
||||
if (!ids.includes(wanted)) {
|
||||
return Promise.reject(new RemoteError(
|
||||
'agent-preset/not-found',
|
||||
`agent-presets: preset "${wanted}" not found (available: ${ids.join(', ') || 'none'})`,
|
||||
{ agentPreset: wanted, available: ids },
|
||||
))
|
||||
}
|
||||
return Promise.resolve(presetOf(wanted))
|
||||
},
|
||||
mount: (_ctx: Context, id?: string) => Promise.resolve(presetOf(id ?? ids[0] ?? '')),
|
||||
}
|
||||
/** A stored Session the persistence double serves until an Agent resumes it. */
|
||||
interface StoredSession {
|
||||
readonly header: SessionHeader
|
||||
readonly events: readonly SessionEvent[]
|
||||
}
|
||||
|
||||
async function harness(presets?: readonly string[]) {
|
||||
interface HarnessOptions {
|
||||
/** Declared presets; the first is the default. Omitted, no roster is composed. */
|
||||
readonly presets?: readonly string[]
|
||||
/** Stored Sessions keyed by id. */
|
||||
readonly stored?: ReadonlyMap<SessionId, StoredSession>
|
||||
/** Stored Sessions whose writer another owner holds. */
|
||||
readonly held?: ReadonlySet<SessionId>
|
||||
/** Stored Sessions another resume in this process publishes while this one waits for the writer. */
|
||||
readonly publishedByOtherResume?: ReadonlySet<SessionId>
|
||||
/** Stored Sessions whose storage fails to open for writing. */
|
||||
readonly unreadable?: ReadonlySet<SessionId>
|
||||
/** Events a resume finds beyond the stored log, as when another Host wrote after the observation. */
|
||||
readonly writtenSinceObservation?: ReadonlyMap<SessionId, readonly SessionEvent[]>
|
||||
/** Live Sessions whose preset switch the roster refuses as already started. */
|
||||
readonly locked?: ReadonlySet<SessionId>
|
||||
/** Declared presets whose activation failed. */
|
||||
readonly broken?: ReadonlySet<string>
|
||||
/** Requested presets whose resolution waits for the paired promise. */
|
||||
readonly resolving?: ReadonlyMap<string, Promise<void>>
|
||||
/** Workspace placement served to `workspaceId` requests. */
|
||||
readonly workspace?: { readonly members: readonly SessionId[]; readonly archived: readonly SessionId[] }
|
||||
}
|
||||
|
||||
const WORKSPACE = 'workspace-1' as WorkspaceId
|
||||
|
||||
async function harness(options: HarnessOptions = {}) {
|
||||
const cwd = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-session-preset-')))
|
||||
tempDirs.push(cwd)
|
||||
const ctx = new Context()
|
||||
contexts.push(ctx)
|
||||
await ctx.plugin(SessionStore)
|
||||
await ctx.plugin(AgentRegistry)
|
||||
const presets = options.presets
|
||||
const selections: { sessionId: SessionId; agentPreset: string }[] = []
|
||||
const resumed: SessionId[] = []
|
||||
if (presets !== undefined) {
|
||||
ctx.provide('agentPresets', roster(presets) as never)
|
||||
const known = (id?: string): string => {
|
||||
const wanted = id ?? presets[0] ?? ''
|
||||
if (!presets.includes(wanted)) {
|
||||
throw new RemoteError('agent-preset/not-found', `Unknown agent preset: ${wanted}`, {
|
||||
agentPreset: wanted, available: [...presets],
|
||||
})
|
||||
}
|
||||
return wanted
|
||||
}
|
||||
const usable = (id?: string): string => {
|
||||
const wanted = known(id)
|
||||
if (options.broken?.has(wanted) === true) {
|
||||
throw new RemoteError('agent-preset/invalid', 'activation failed', { agentPreset: wanted, reason: 'activation failed' })
|
||||
}
|
||||
return wanted
|
||||
}
|
||||
ctx.provide('agentPresets', {
|
||||
defaultId: presets[0],
|
||||
resolve: (id?: string) => Promise.resolve(id === undefined ? undefined : options.resolving?.get(id))
|
||||
.then(() => ({ id: known(id) })),
|
||||
mount: (_ctx: Context, id?: string) => Promise.resolve().then(() => ({ id: usable(id) })),
|
||||
select: async (agent: Agent, agentPreset: string) => {
|
||||
usable(agentPreset)
|
||||
if (options.locked?.has(agent.id) === true) {
|
||||
throw new RemoteError('agent-preset/locked', 'This session has already started', {
|
||||
sessionId: agent.id, agentPreset,
|
||||
})
|
||||
}
|
||||
selections.push({ sessionId: agent.id, agentPreset })
|
||||
agent.session.append('agent-preset/selected', { agentPreset })
|
||||
return agentPreset
|
||||
},
|
||||
} as never)
|
||||
}
|
||||
|
||||
const factory: AgentFactory = {
|
||||
async createAgent(_ownerCtx, options) {
|
||||
const session = ctx.sessions.create(
|
||||
options.sessionId,
|
||||
options.meta === undefined ? {} : { meta: options.meta },
|
||||
)
|
||||
const agent = stubAgent(session)
|
||||
;(agent as { ctx?: Context }).ctx = ctx
|
||||
await options.setup?.(ctx, agent)
|
||||
const unregister = await ctx.agents.register(agent)
|
||||
return { agent, dispose: async () => { await unregister() } }
|
||||
const stored = options.stored ?? new Map<SessionId, StoredSession>()
|
||||
ctx.provide('sessionPersistence', testSessionPersistence(ctx, {
|
||||
list: () => Promise.resolve([...stored.values()].map(record => record.header)),
|
||||
inspect: (id: SessionId) => {
|
||||
const record = stored.get(id)
|
||||
return Promise.resolve(record === undefined ? undefined : { meta: record.header, events: [...record.events] })
|
||||
},
|
||||
async resume() {
|
||||
throw new Error('test harness has no persisted sessions')
|
||||
}) as never)
|
||||
const { members, archived } = options.workspace ?? { members: [], archived: [] }
|
||||
const workspace = { id: WORKSPACE, path: cwd, sessionIds: members, attachSession: () => Promise.resolve() }
|
||||
ctx.provide('workspaceRegistry', {
|
||||
get: (id: WorkspaceId) => id === WORKSPACE ? workspace : undefined,
|
||||
list: () => [workspace],
|
||||
archivedSessionIds: archived,
|
||||
} as never)
|
||||
|
||||
/** Run setup on the unpublished Session, then publish it and its Agent, as the Agent factory does. */
|
||||
const publish = async (
|
||||
session: Session,
|
||||
setup: Parameters<AgentFactory['createAgent']>[1]['setup'],
|
||||
): Promise<{ agent: Agent; dispose: () => Promise<void> }> => {
|
||||
const agent = stubAgent(session)
|
||||
;(agent as { ctx?: Context }).ctx = ctx
|
||||
await setup?.(ctx, agent)
|
||||
ctx.effect(function* () {
|
||||
yield ctx.sessions.enter(session)
|
||||
ctx.sessions.announce(session)
|
||||
}, 'test: published Session')
|
||||
const unregister = await ctx.agents.register(agent)
|
||||
return { agent, dispose: async () => { await unregister() } }
|
||||
}
|
||||
const factory: AgentFactory = {
|
||||
async createAgent(_ownerCtx, create) {
|
||||
const session = ctx.sessions.prepare(create.sessionId, create.meta === undefined ? {} : { meta: create.meta })
|
||||
return publish(session, create.setup)
|
||||
},
|
||||
async resume(_ownerCtx, resume) {
|
||||
const id = resume.resumeSessionId
|
||||
if (options.held?.has(id) === true) {
|
||||
throw Object.assign(new Error(`session "${id}" is written by another owner`), { name: 'SessionAlreadyOwnedError' })
|
||||
}
|
||||
const record = stored.get(id)
|
||||
if (record === undefined || options.unreadable?.has(id) === true) {
|
||||
throw new Error(`test persistence cannot open Session "${id}" for writing`)
|
||||
}
|
||||
if (options.publishedByOtherResume?.has(id) === true) {
|
||||
await publish(ctx.sessions.prepare(id, { meta: record.header, seed: [...record.events] }), undefined)
|
||||
throw Object.assign(new Error(`session "${id}" is written by this process`), { name: 'SessionAlreadyOwnedError' })
|
||||
}
|
||||
resumed.push(id)
|
||||
const session = ctx.sessions.prepare(id, {
|
||||
meta: record.header,
|
||||
seed: [...record.events, ...options.writtenSinceObservation?.get(id) ?? []],
|
||||
})
|
||||
return publish(session, resume.setup)
|
||||
},
|
||||
}
|
||||
ctx.agents.setFactory(factory)
|
||||
@@ -79,13 +165,43 @@ async function harness(presets?: readonly string[]) {
|
||||
defaultModelSelection: () => ({ provider: 'test', model: 'test-model' }),
|
||||
cwd,
|
||||
})
|
||||
ctx.sessionProjections.register(turnBoundaryProjectionDefinition)
|
||||
if (presets !== undefined) ctx.sessionProjections.register(agentPresetProjectionDefinition)
|
||||
return { ctx, remote }
|
||||
const presetOf = (id: SessionId): string | null | undefined => {
|
||||
const session = ctx.sessions.get(id)
|
||||
return session === undefined ? undefined : ctx.sessionProjections.stateOf(session, 'agentPreset')
|
||||
}
|
||||
const selectedEvents = (id: SessionId): unknown[] => {
|
||||
const session = ctx.sessions.get(id)
|
||||
return session === undefined ? [] : session.snapshotEvents()
|
||||
.filter(event => event.type === 'agent-preset/selected')
|
||||
.map(event => event.data)
|
||||
}
|
||||
return { ctx, remote, cwd, selections, resumed, presetOf, selectedEvents }
|
||||
}
|
||||
|
||||
function storedHeader(id: SessionId, cwd: string, extra: Partial<SessionHeader> = {}): SessionHeader {
|
||||
return { version: SESSION_FORMAT_VERSION, id, createdAt: 1, isSeeded: false, cwd, ...extra }
|
||||
}
|
||||
|
||||
function modelSelection(seq: number): SessionEvent {
|
||||
return { type: 'model/selection', seq: SessionSeq(seq), time: 1, data: { provider: 'test', model: 'test-model' } }
|
||||
}
|
||||
|
||||
function presetSelection(seq: number, agentPreset: string): SessionEvent {
|
||||
return { type: 'agent-preset/selected', seq: SessionSeq(seq), time: 1, data: { agentPreset } }
|
||||
}
|
||||
|
||||
function completedTurn(seq: number): SessionEvent[] {
|
||||
return [
|
||||
{ type: 'turn/start', seq: SessionSeq(seq), time: 1, data: { turn: 1 } },
|
||||
{ type: 'turn/end', seq: SessionSeq(seq + 1), time: 2, data: { turn: 1, reason: { kind: 'completed' } } },
|
||||
]
|
||||
}
|
||||
|
||||
describe('session.create Agent preset identity', () => {
|
||||
it('records the requested preset on the Session header', async () => {
|
||||
const { ctx, remote } = await harness(['standard', 'minimal'])
|
||||
const { ctx, remote } = await harness({ presets: ['standard', 'minimal'] })
|
||||
|
||||
const created = await remote.create({ sessionId: SessionId('s1'), agentPreset: 'minimal' })
|
||||
|
||||
@@ -94,7 +210,7 @@ describe('session.create Agent preset identity', () => {
|
||||
})
|
||||
|
||||
it('records the roster default when the caller names no preset', async () => {
|
||||
const { ctx, remote } = await harness(['standard', 'minimal'])
|
||||
const { ctx, remote } = await harness({ presets: ['standard', 'minimal'] })
|
||||
|
||||
await remote.create({ sessionId: SessionId('s2') })
|
||||
|
||||
@@ -102,55 +218,13 @@ describe('session.create Agent preset identity', () => {
|
||||
})
|
||||
|
||||
it('rejects an unknown preset', async () => {
|
||||
const { remote } = await harness(['standard'])
|
||||
const { remote } = await harness({ presets: ['standard'] })
|
||||
|
||||
const response = await remote.create({ sessionId: SessionId('s3'), agentPreset: 'nope' })
|
||||
|
||||
expect(response).toMatchObject({ ok: false, error: { code: 'agent-preset/not-found' } })
|
||||
})
|
||||
|
||||
it('refuses to adopt a live Session under a different preset', async () => {
|
||||
const { remote } = await harness(['standard', 'minimal'])
|
||||
await remote.create({ sessionId: SessionId('s4'), agentPreset: 'minimal' })
|
||||
|
||||
const response = await remote.create({ sessionId: SessionId('s4'), agentPreset: 'standard' })
|
||||
|
||||
expect(response).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
code: 'agent-preset/conflict',
|
||||
details: {
|
||||
sessionId: 's4',
|
||||
requestedPreset: 'standard',
|
||||
existingPreset: 'minimal',
|
||||
},
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('adopts a live Session under the preset selected in its log', async () => {
|
||||
const { ctx, remote } = await harness(['standard', 'minimal'])
|
||||
await remote.create({ sessionId: SessionId('s4b'), agentPreset: 'standard' })
|
||||
ctx.sessions.get(SessionId('s4b'))?.append('agent-preset/selected', { agentPreset: 'minimal' })
|
||||
|
||||
const adopted = await remote.create({ sessionId: SessionId('s4b'), agentPreset: 'minimal' })
|
||||
const stale = await remote.create({ sessionId: SessionId('s4b'), agentPreset: 'standard' })
|
||||
|
||||
expect(adopted).toMatchObject({ ok: true, value: { agentPreset: 'minimal' } })
|
||||
expect(stale).toMatchObject({
|
||||
ok: false,
|
||||
error: { details: { existingPreset: 'minimal' } },
|
||||
})
|
||||
})
|
||||
|
||||
it('adopts a live Session unchanged when the caller names no preset', async () => {
|
||||
const { remote } = await harness(['standard', 'minimal'])
|
||||
await remote.create({ sessionId: SessionId('s5'), agentPreset: 'minimal' })
|
||||
|
||||
await expect(remote.create({ sessionId: SessionId('s5') }))
|
||||
.resolves.toMatchObject({ ok: true })
|
||||
})
|
||||
|
||||
it('leaves the header preset-less when no roster is composed', async () => {
|
||||
const { ctx, remote } = await harness()
|
||||
|
||||
@@ -158,6 +232,195 @@ describe('session.create Agent preset identity', () => {
|
||||
|
||||
expect(ctx.sessions.get(SessionId('s6'))?.header.agentPreset).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('session.create reuse of a live blank Session', () => {
|
||||
it('recomposes a blank Session under the default when the caller names no preset', async () => {
|
||||
const { remote, selections, presetOf } = await harness({ presets: ['standard', 'minimal'] })
|
||||
await remote.create({ sessionId: SessionId('draft'), agentPreset: 'minimal' })
|
||||
|
||||
const reused = await remote.create({ sessionId: SessionId('draft') })
|
||||
|
||||
expect(reused).toMatchObject({ ok: true, value: { sessionId: 'draft', agentPreset: 'standard' } })
|
||||
expect(selections).toEqual([{ sessionId: 'draft', agentPreset: 'standard' }])
|
||||
expect(presetOf(SessionId('draft'))).toBe('standard')
|
||||
})
|
||||
|
||||
it('recomposes a blank Session under the named preset', async () => {
|
||||
const { remote, selections } = await harness({ presets: ['standard', 'minimal'] })
|
||||
await remote.create({ sessionId: SessionId('draft') })
|
||||
|
||||
const reused = await remote.create({ sessionId: SessionId('draft'), agentPreset: 'minimal' })
|
||||
|
||||
expect(reused).toMatchObject({ ok: true, value: { sessionId: 'draft', agentPreset: 'minimal' } })
|
||||
expect(selections).toEqual([{ sessionId: 'draft', agentPreset: 'minimal' }])
|
||||
})
|
||||
|
||||
it('keeps a blank Session that already runs the requested preset', async () => {
|
||||
const { ctx, remote, selections } = await harness({ presets: ['standard', 'minimal'] })
|
||||
await remote.create({ sessionId: SessionId('draft') })
|
||||
ctx.sessions.get(SessionId('draft'))?.append('agent-preset/selected', { agentPreset: 'minimal' })
|
||||
|
||||
const reused = await remote.create({ sessionId: SessionId('draft'), agentPreset: 'minimal' })
|
||||
|
||||
expect(reused).toMatchObject({ ok: true, value: { sessionId: 'draft', agentPreset: 'minimal' } })
|
||||
expect(selections).toEqual([])
|
||||
})
|
||||
|
||||
it('validates the requested preset before touching the blank Session', async () => {
|
||||
const { remote, selections, presetOf } = await harness({ presets: ['standard', 'minimal'] })
|
||||
await remote.create({ sessionId: SessionId('draft'), agentPreset: 'minimal' })
|
||||
|
||||
const response = await remote.create({ sessionId: SessionId('draft'), agentPreset: 'deleted' })
|
||||
|
||||
expect(response).toMatchObject({ ok: false, error: { code: 'agent-preset/not-found' } })
|
||||
expect(selections).toEqual([])
|
||||
expect(presetOf(SessionId('draft'))).toBe('minimal')
|
||||
})
|
||||
|
||||
it('keeps the blank Session unchanged when the requested preset fails to activate', async () => {
|
||||
const { remote, selections, presetOf } = await harness({
|
||||
presets: ['standard', 'broken'],
|
||||
broken: new Set(['broken']),
|
||||
})
|
||||
await remote.create({ sessionId: SessionId('draft') })
|
||||
|
||||
const response = await remote.create({ sessionId: SessionId('draft'), agentPreset: 'broken' })
|
||||
|
||||
expect(response).toMatchObject({ ok: false, error: { code: 'agent-preset/invalid' } })
|
||||
expect(selections).toEqual([])
|
||||
expect(presetOf(SessionId('draft'))).toBe('standard')
|
||||
})
|
||||
|
||||
it('creates a new Session instead of reusing one that has started', async () => {
|
||||
const { ctx, remote, selections, presetOf } = await harness({ presets: ['standard', 'minimal'] })
|
||||
await remote.create({ sessionId: SessionId('talk'), agentPreset: 'minimal' })
|
||||
const talk = ctx.sessions.get(SessionId('talk'))
|
||||
talk?.append('turn/start', { turn: 1 })
|
||||
talk?.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
|
||||
|
||||
const created = await remote.create({ sessionId: SessionId('talk') })
|
||||
|
||||
if (!created.ok) throw new Error(`create failed: ${created.error.message}`)
|
||||
expect(created.value.sessionId).not.toBe('talk')
|
||||
expect(created.value.agentPreset).toBe('standard')
|
||||
expect(selections).toEqual([])
|
||||
expect(presetOf(SessionId('talk'))).toBe('minimal')
|
||||
})
|
||||
|
||||
it('creates a new Session when a turn starts before the preset switch', async () => {
|
||||
const { remote } = await harness({
|
||||
presets: ['standard', 'minimal'],
|
||||
locked: new Set([SessionId('racing')]),
|
||||
})
|
||||
await remote.create({ sessionId: SessionId('racing'), agentPreset: 'minimal' })
|
||||
|
||||
const created = await remote.create({ sessionId: SessionId('racing') })
|
||||
|
||||
if (!created.ok) throw new Error(`create failed: ${created.error.message}`)
|
||||
expect(created.value.sessionId).not.toBe('racing')
|
||||
})
|
||||
|
||||
it('serializes concurrent reuse of one Session in request order', async () => {
|
||||
const { remote, selections, presetOf } = await harness({ presets: ['standard', 'minimal'] })
|
||||
await remote.create({ sessionId: SessionId('draft') })
|
||||
|
||||
const [first, second] = await Promise.all([
|
||||
remote.create({ sessionId: SessionId('draft'), agentPreset: 'minimal' }),
|
||||
remote.create({ sessionId: SessionId('draft') }),
|
||||
])
|
||||
|
||||
expect(first).toMatchObject({ ok: true, value: { sessionId: 'draft' } })
|
||||
expect(second).toMatchObject({ ok: true, value: { sessionId: 'draft', agentPreset: 'standard' } })
|
||||
expect(selections).toEqual([
|
||||
{ sessionId: 'draft', agentPreset: 'minimal' },
|
||||
{ sessionId: 'draft', agentPreset: 'standard' },
|
||||
])
|
||||
expect(presetOf(SessionId('draft'))).toBe('standard')
|
||||
})
|
||||
|
||||
it('claims one Session in arrival order when an earlier preset resolves later', async () => {
|
||||
const minimal = Promise.withResolvers<undefined>()
|
||||
const { remote, selections, presetOf } = await harness({
|
||||
presets: ['standard', 'minimal'], resolving: new Map([['minimal', minimal.promise]]),
|
||||
})
|
||||
await remote.create({ sessionId: SessionId('draft') })
|
||||
|
||||
const first = remote.create({ sessionId: SessionId('draft'), agentPreset: 'minimal' })
|
||||
const second = remote.create({ sessionId: SessionId('draft') })
|
||||
await new Promise(resolve => setTimeout(resolve, 0))
|
||||
minimal.resolve(undefined)
|
||||
|
||||
expect(await first).toMatchObject({ ok: true, value: { sessionId: 'draft', agentPreset: 'minimal' } })
|
||||
expect(await second).toMatchObject({ ok: true, value: { sessionId: 'draft', agentPreset: 'standard' } })
|
||||
expect(selections).toEqual([
|
||||
{ sessionId: 'draft', agentPreset: 'minimal' },
|
||||
{ sessionId: 'draft', agentPreset: 'standard' },
|
||||
])
|
||||
expect(presetOf(SessionId('draft'))).toBe('standard')
|
||||
})
|
||||
|
||||
it('shares one creation between concurrent callers of a new identity', async () => {
|
||||
const { ctx, remote } = await harness({ presets: ['standard'] })
|
||||
|
||||
const results = await Promise.all([
|
||||
remote.create({ sessionId: SessionId('fresh') }),
|
||||
remote.create({ sessionId: SessionId('fresh') }),
|
||||
])
|
||||
|
||||
expect(results).toMatchObject([
|
||||
{ ok: true, value: { sessionId: 'fresh' } },
|
||||
{ ok: true, value: { sessionId: 'fresh' } },
|
||||
])
|
||||
expect(ctx.agents.list().map(agent => agent.id)).toEqual(['fresh'])
|
||||
})
|
||||
|
||||
it('refuses a Session in another directory', async () => {
|
||||
const { ctx, remote } = await harness({ presets: ['standard'] })
|
||||
const elsewhere = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-session-preset-elsewhere-')))
|
||||
tempDirs.push(elsewhere)
|
||||
await remote.create({ sessionId: SessionId('other'), cwd: elsewhere })
|
||||
|
||||
const response = await remote.create({ sessionId: SessionId('other') })
|
||||
|
||||
expect(response).toMatchObject({
|
||||
ok: false,
|
||||
error: { code: 'session/conflict', details: { sessionId: 'other', existingCwd: elsewhere } },
|
||||
})
|
||||
expect(ctx.agents.list().map(agent => agent.id)).toEqual(['other'])
|
||||
})
|
||||
|
||||
it('refuses a Session in another directory before resolving the requested preset', async () => {
|
||||
const { remote } = await harness({ presets: ['standard'] })
|
||||
const elsewhere = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-session-preset-elsewhere-')))
|
||||
tempDirs.push(elsewhere)
|
||||
await remote.create({ sessionId: SessionId('other'), cwd: elsewhere })
|
||||
|
||||
const response = await remote.create({ sessionId: SessionId('other'), agentPreset: 'nope' })
|
||||
|
||||
expect(response).toMatchObject({ ok: false, error: { code: 'session/conflict', details: { sessionId: 'other' } } })
|
||||
})
|
||||
|
||||
it('leaves a subagent identity to subagent routing', async () => {
|
||||
const { ctx, remote, cwd } = await harness({ presets: ['standard'] })
|
||||
ctx.sessions.create(SessionId('child'), {
|
||||
meta: { cwd, parentSession: SessionId('parent'), origin: 'subagent' },
|
||||
})
|
||||
|
||||
const response = await remote.create({ sessionId: SessionId('child') })
|
||||
|
||||
expect(response).toMatchObject({ ok: false, error: { code: 'session/agent-busy' } })
|
||||
})
|
||||
|
||||
it('reuses a preset-less blank Session unchanged when no roster is composed', async () => {
|
||||
const { ctx, remote } = await harness()
|
||||
await remote.create({ sessionId: SessionId('s5') })
|
||||
|
||||
const reused = await remote.create({ sessionId: SessionId('s5') })
|
||||
|
||||
expect(reused).toMatchObject({ ok: true, value: { sessionId: 's5' } })
|
||||
expect(ctx.sessions.get(SessionId('s5'))?.header.agentPreset).toBeUndefined()
|
||||
})
|
||||
|
||||
it('explains why a preset-less Session cannot be adopted under one', async () => {
|
||||
const { remote } = await harness()
|
||||
@@ -177,6 +440,235 @@ describe('session.create Agent preset identity', () => {
|
||||
})
|
||||
if (response.ok) throw new Error('unreachable')
|
||||
expect('existingPreset' in response.error.details).toBe(false)
|
||||
expect(response.error.message).toContain('records no agent preset')
|
||||
expect(response.error.message).toBe('the deployment composes no agent preset roster, so session "s7" cannot run preset "standard"')
|
||||
})
|
||||
})
|
||||
|
||||
describe('session.create reuse of a stored blank Session', () => {
|
||||
it('resumes a blank Session whose recorded preset is no longer declared under the default', async () => {
|
||||
const draft = SessionId('stale-draft')
|
||||
const cwd = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-session-preset-stored-')))
|
||||
tempDirs.push(cwd)
|
||||
const { remote, resumed, presetOf, selectedEvents } = await harness({
|
||||
presets: ['standard', 'minimal'],
|
||||
stored: new Map([[draft, { header: storedHeader(draft, cwd, { agentPreset: 'liangshen' }), events: [modelSelection(0)] }]]),
|
||||
})
|
||||
|
||||
const reused = await remote.create({ sessionId: draft, cwd })
|
||||
|
||||
expect(reused).toMatchObject({ ok: true, value: { sessionId: 'stale-draft', agentPreset: 'standard' } })
|
||||
expect(resumed).toEqual(['stale-draft'])
|
||||
expect(presetOf(draft)).toBe('standard')
|
||||
expect(selectedEvents(draft)).toEqual([{ agentPreset: 'standard' }])
|
||||
})
|
||||
|
||||
it('resumes a blank Session under the default even when its previous choice is still declared', async () => {
|
||||
const draft = SessionId('picked-draft')
|
||||
const cwd = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-session-preset-stored-')))
|
||||
tempDirs.push(cwd)
|
||||
const { remote, presetOf, selectedEvents } = await harness({
|
||||
presets: ['standard', 'minimal'],
|
||||
stored: new Map([[draft, { header: storedHeader(draft, cwd, { agentPreset: 'standard' }), events: [presetSelection(0, 'minimal')] }]]),
|
||||
})
|
||||
|
||||
const reused = await remote.create({ sessionId: draft, cwd })
|
||||
|
||||
expect(reused).toMatchObject({ ok: true, value: { sessionId: 'picked-draft', agentPreset: 'standard' } })
|
||||
expect(presetOf(draft)).toBe('standard')
|
||||
expect(selectedEvents(draft)).toEqual([{ agentPreset: 'minimal' }, { agentPreset: 'standard' }])
|
||||
})
|
||||
|
||||
it('resumes a blank Session under its recorded preset when the caller names it', async () => {
|
||||
const draft = SessionId('restored-draft')
|
||||
const cwd = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-session-preset-stored-')))
|
||||
tempDirs.push(cwd)
|
||||
const { remote, presetOf, selectedEvents } = await harness({
|
||||
presets: ['standard', 'minimal'],
|
||||
stored: new Map([[draft, { header: storedHeader(draft, cwd, { agentPreset: 'standard' }), events: [presetSelection(0, 'minimal')] }]]),
|
||||
})
|
||||
|
||||
const reused = await remote.create({ sessionId: draft, cwd, agentPreset: 'minimal' })
|
||||
|
||||
expect(reused).toMatchObject({ ok: true, value: { sessionId: 'restored-draft', agentPreset: 'minimal' } })
|
||||
expect(presetOf(draft)).toBe('minimal')
|
||||
expect(selectedEvents(draft)).toEqual([{ agentPreset: 'minimal' }])
|
||||
})
|
||||
|
||||
it('rejects a named preset that is no longer declared without resuming the Session', async () => {
|
||||
const draft = SessionId('stale-draft')
|
||||
const cwd = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-session-preset-stored-')))
|
||||
tempDirs.push(cwd)
|
||||
const { ctx, remote, resumed } = await harness({
|
||||
presets: ['standard'],
|
||||
stored: new Map([[draft, { header: storedHeader(draft, cwd, { agentPreset: 'liangshen' }), events: [modelSelection(0)] }]]),
|
||||
})
|
||||
|
||||
const response = await remote.create({ sessionId: draft, cwd, agentPreset: 'liangshen' })
|
||||
|
||||
expect(response).toMatchObject({
|
||||
ok: false,
|
||||
error: { code: 'agent-preset/not-found', details: { agentPreset: 'liangshen', available: ['standard'] } },
|
||||
})
|
||||
expect(resumed).toEqual([])
|
||||
expect(ctx.agents.list()).toEqual([])
|
||||
})
|
||||
|
||||
it('creates a new Session instead of resuming one that has started', async () => {
|
||||
const talk = SessionId('stored-talk')
|
||||
const cwd = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-session-preset-stored-')))
|
||||
tempDirs.push(cwd)
|
||||
const { remote, resumed } = await harness({
|
||||
presets: ['standard'],
|
||||
stored: new Map([[talk, { header: storedHeader(talk, cwd, { agentPreset: 'liangshen' }), events: completedTurn(0) }]]),
|
||||
})
|
||||
|
||||
const created = await remote.create({ sessionId: talk, cwd })
|
||||
|
||||
if (!created.ok) throw new Error(`create failed: ${created.error.message}`)
|
||||
expect(created.value.sessionId).not.toBe('stored-talk')
|
||||
expect(created.value.agentPreset).toBe('standard')
|
||||
expect(resumed).toEqual([])
|
||||
})
|
||||
|
||||
it('creates a new Session when another owner holds the blank Session', async () => {
|
||||
const draft = SessionId('held-draft')
|
||||
const cwd = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-session-preset-stored-')))
|
||||
tempDirs.push(cwd)
|
||||
const { ctx, remote } = await harness({
|
||||
presets: ['standard'],
|
||||
stored: new Map([[draft, { header: storedHeader(draft, cwd, { agentPreset: 'standard' }), events: [modelSelection(0)] }]]),
|
||||
held: new Set([draft]),
|
||||
})
|
||||
|
||||
const created = await remote.create({ sessionId: draft, cwd })
|
||||
|
||||
if (!created.ok) throw new Error(`create failed: ${created.error.message}`)
|
||||
expect(created.value.sessionId).not.toBe('held-draft')
|
||||
expect(ctx.sessions.get(draft)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('reuses the Agent another resume published while holding the writer', async () => {
|
||||
const draft = SessionId('contended-draft')
|
||||
const cwd = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-session-preset-stored-')))
|
||||
tempDirs.push(cwd)
|
||||
const { remote, selections, presetOf } = await harness({
|
||||
presets: ['standard', 'minimal'],
|
||||
stored: new Map([[draft, { header: storedHeader(draft, cwd, { agentPreset: 'minimal' }), events: [modelSelection(0)] }]]),
|
||||
publishedByOtherResume: new Set([draft]),
|
||||
})
|
||||
|
||||
const reused = await remote.create({ sessionId: draft, cwd })
|
||||
|
||||
expect(reused).toMatchObject({ ok: true, value: { sessionId: 'contended-draft', agentPreset: 'standard' } })
|
||||
expect(selections).toEqual([{ sessionId: 'contended-draft', agentPreset: 'standard' }])
|
||||
expect(presetOf(draft)).toBe('standard')
|
||||
})
|
||||
|
||||
it('reports an unreadable Session instead of creating another one', async () => {
|
||||
const { ctx, remote } = await harness({ presets: ['standard'] })
|
||||
vi.spyOn(ctx.sessionQuery, 'observeSession').mockRejectedValue(new Error('storage offline'))
|
||||
|
||||
const response = await remote.create({ sessionId: SessionId('unreadable') })
|
||||
|
||||
expect(response).toMatchObject({ ok: false, error: { code: 'gateway/internal' } })
|
||||
expect(ctx.agents.list()).toEqual([])
|
||||
})
|
||||
|
||||
it('reports a storage failure instead of creating another Session', async () => {
|
||||
const draft = SessionId('unreadable-draft')
|
||||
const cwd = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-session-preset-stored-')))
|
||||
tempDirs.push(cwd)
|
||||
const { ctx, remote } = await harness({
|
||||
presets: ['standard'],
|
||||
stored: new Map([[draft, { header: storedHeader(draft, cwd, { agentPreset: 'standard' }), events: [modelSelection(0)] }]]),
|
||||
unreadable: new Set([draft]),
|
||||
})
|
||||
|
||||
const response = await remote.create({ sessionId: draft, cwd })
|
||||
|
||||
expect(response).toMatchObject({ ok: false, error: { code: 'gateway/internal' } })
|
||||
expect(ctx.agents.list()).toEqual([])
|
||||
})
|
||||
|
||||
it('creates a new Session when the blank Session started after it was observed', async () => {
|
||||
const draft = SessionId('overtaken-draft')
|
||||
const cwd = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-session-preset-stored-')))
|
||||
tempDirs.push(cwd)
|
||||
const { ctx, remote, resumed } = await harness({
|
||||
presets: ['standard', 'minimal'],
|
||||
stored: new Map([[draft, { header: storedHeader(draft, cwd, { agentPreset: 'minimal' }), events: [modelSelection(0)] }]]),
|
||||
writtenSinceObservation: new Map([[draft, completedTurn(1)]]),
|
||||
})
|
||||
|
||||
const created = await remote.create({ sessionId: draft, cwd })
|
||||
|
||||
if (!created.ok) throw new Error(`create failed: ${created.error.message}`)
|
||||
expect(created.value.sessionId).not.toBe('overtaken-draft')
|
||||
expect(resumed).toEqual(['overtaken-draft'])
|
||||
expect(ctx.sessions.get(draft)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('refuses a stored Session in another directory', async () => {
|
||||
const other = SessionId('stored-other')
|
||||
const cwd = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-session-preset-stored-')))
|
||||
tempDirs.push(cwd)
|
||||
const { remote, resumed } = await harness({
|
||||
presets: ['standard'],
|
||||
stored: new Map([[other, { header: storedHeader(other, '/elsewhere'), events: [modelSelection(0)] }]]),
|
||||
})
|
||||
|
||||
const response = await remote.create({ sessionId: other, cwd })
|
||||
|
||||
expect(response).toMatchObject({
|
||||
ok: false,
|
||||
error: { code: 'session/conflict', details: { sessionId: 'stored-other', existingCwd: '/elsewhere' } },
|
||||
})
|
||||
expect(resumed).toEqual([])
|
||||
})
|
||||
|
||||
it('leaves a stored subagent identity to subagent routing', async () => {
|
||||
const child = SessionId('stored-child')
|
||||
const cwd = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-session-preset-stored-')))
|
||||
tempDirs.push(cwd)
|
||||
const { remote, resumed } = await harness({
|
||||
presets: ['standard'],
|
||||
stored: new Map([[child, {
|
||||
header: storedHeader(child, cwd, { parentSession: SessionId('parent'), origin: 'subagent' }),
|
||||
events: [modelSelection(0)],
|
||||
}]]),
|
||||
})
|
||||
|
||||
const response = await remote.create({ sessionId: child, cwd })
|
||||
|
||||
expect(response).toMatchObject({ ok: false, error: { code: 'session/agent-busy' } })
|
||||
expect(resumed).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('session.create Workspace placement', () => {
|
||||
it('reuses a blank member of the requested Workspace', async () => {
|
||||
const draft = SessionId('member-draft')
|
||||
const { remote } = await harness({ presets: ['standard'], workspace: { members: [draft], archived: [] } })
|
||||
await remote.create({ sessionId: draft })
|
||||
|
||||
const reused = await remote.create({ sessionId: draft, workspaceId: WORKSPACE })
|
||||
|
||||
expect(reused).toMatchObject({ ok: true, value: { sessionId: 'member-draft' } })
|
||||
})
|
||||
|
||||
it.each([
|
||||
{ name: 'outside the Workspace', members: [], archived: [] },
|
||||
{ name: 'archived', members: [SessionId('placed-draft')], archived: [SessionId('placed-draft')] },
|
||||
])('creates a new Session instead of reusing a blank Session $name', async ({ members, archived }) => {
|
||||
const draft = SessionId('placed-draft')
|
||||
const { remote, selections, presetOf } = await harness({ presets: ['standard', 'minimal'], workspace: { members, archived } })
|
||||
await remote.create({ sessionId: draft, agentPreset: 'minimal' })
|
||||
|
||||
const created = await remote.create({ sessionId: draft, workspaceId: WORKSPACE })
|
||||
|
||||
if (!created.ok) throw new Error(`create failed: ${created.error.message}`)
|
||||
expect(created.value.sessionId).not.toBe('placed-draft')
|
||||
expect(selections).toEqual([])
|
||||
expect(presetOf(draft)).toBe('minimal')
|
||||
})
|
||||
})
|
||||
@@ -18,8 +18,8 @@
|
||||
en: a21296842d6e18da
|
||||
zh: 75f3a6a79691884f
|
||||
/deepseek-ai-dsh-client-ui-agent-preset/understand-the-implementation:
|
||||
en: b3221ef8bc6d8096
|
||||
zh: 68cb05566249da10
|
||||
en: a90bf7539dbce636
|
||||
zh: d77c1fecac2c6a4b
|
||||
/deepseek-ai-dsh-client-ui-agent-preset/further-exploration:
|
||||
en: bbae8d79844bc481
|
||||
zh: 4302107fd1f460e6
|
||||
|
||||
@@ -45,7 +45,7 @@ Entering Creator selects `cordis` for the receiving blank Session without changi
|
||||
|
||||
`agentPresets/list` supplies the roster and marks the current default, and `agentPresets/read` one declaration's YAML for the viewer; default changes write the `agent-preset-registry` settings namespace. The picker, blank-session synchronization and read-only session label use recorded preset identities. Connection resets and settings updates refresh the roster.
|
||||
|
||||
`CreatePluginMenuItem` contributes to `plugins.add.actions` using the shared roster store. Its selection calls the owner's `onDismiss()` before the same `startCreatorDraft` callback exposed to Settings as `creatorDraft`. That callback stages `cordis` through `AgentPresetSeatController` and opens the task through `uiWorkspace.startSession` with explicit draft preservation; it can reuse a blank Session and applies the staged choice when a Session binding becomes available. The choice is consumed once applied. Both Coding Tools states use the same picker and selection store, and `AgentPresetSeat` renders refusals through the shared `Toast` component.
|
||||
`CreatePluginMenuItem` contributes to `plugins.add.actions` using the shared roster store. Its selection calls the owner's `onDismiss()` before the same `startCreatorDraft` callback exposed to Settings as `creatorDraft`. That callback stages `cordis` through `AgentPresetSeatController` and opens the task through `uiWorkspace.startSession` with explicit draft preservation and `agentPreset: 'cordis'`, so the Host composes the reused blank or new Session under Creator; without a target Workspace, the staged choice applies when a Session binding becomes available. The choice is consumed once applied. Both Coding Tools states use the same picker and selection store, and `AgentPresetSeat` renders refusals through the shared `Toast` component.
|
||||
|
||||
</details>
|
||||
|
||||
|
||||
@@ -45,7 +45,7 @@ kind: "package-reference"
|
||||
|
||||
`agentPresets/list` 提供列表并标记当前默认值,`agentPresets/read` 为查看器提供一条声明的 YAML;默认值的修改写入 `agent-preset-registry` settings 命名空间。选择器、空白会话同步和只读会话标签使用记录的 preset 标识。连接重置和设置更新会刷新列表。
|
||||
|
||||
`CreatePluginMenuItem` 使用共享的预设列表 store,向 `plugins.add.actions` 贡献菜单项。选择时先调用页面传入的 `onDismiss()`,再调用与设置页 `creatorDraft` 相同的 `startCreatorDraft` 回调。该回调通过 `AgentPresetSeatController` 暂存 `cordis`,再通过显式保留草稿的 `uiWorkspace.startSession` 调用打开任务;它可以复用空白 Session,并在 Session 绑定可用时应用暂存选择。暂存选择应用后即清除。代码工作工具开启或关闭时均使用同一个选择器和选择 store,`AgentPresetSeat` 通过共享的 `Toast` 组件显示拒绝原因。
|
||||
`CreatePluginMenuItem` 使用共享的预设列表 store,向 `plugins.add.actions` 贡献菜单项。选择时先调用页面传入的 `onDismiss()`,再调用与设置页 `creatorDraft` 相同的 `startCreatorDraft` 回调。该回调通过 `AgentPresetSeatController` 暂存 `cordis`,再通过显式保留草稿并传入 `agentPreset: 'cordis'` 的 `uiWorkspace.startSession` 调用打开任务,由 Host 以创造模式组合被复用的空白 Session 或新 Session;没有目标工作区时,暂存选择在 Session 绑定可用时应用。暂存选择应用后即清除。代码工作工具开启或关闭时均使用同一个选择器和选择 store,`AgentPresetSeat` 通过共享的 `Toast` 组件显示拒绝原因。
|
||||
|
||||
</details>
|
||||
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
* the roster (selection, the new-task default, a read-only view of each
|
||||
* declared composition, and the way into Creator mode).
|
||||
*
|
||||
* A running session keeps the composition it began with (the host refuses to
|
||||
* adopt an existing session under a different preset). That is what splits
|
||||
* A running session keeps the composition it began with (the host switches a
|
||||
* session's preset only before its first turn). That is what splits
|
||||
* the choice from the display: the hero chip is before-the-fact, while the
|
||||
* header only reports what a session already runs. The default preset is
|
||||
* edited where the roster is visible — the settings section's "make default"
|
||||
@@ -198,10 +198,10 @@ export function apply(ctx: ClientContext): void {
|
||||
})
|
||||
|
||||
const startCreatorDraft = () => {
|
||||
// The Host composes the reused draft or new Session; the stage only drives the chip's display and introduction.
|
||||
const seat = mainBlankSeat() ?? unboundSeat
|
||||
seat.stage('cordis', true)
|
||||
scope.uiWorkspace.startSession(undefined, { clearPreviousDraft: false })
|
||||
void seat.apply()
|
||||
scope.uiWorkspace.startSession(undefined, { clearPreviousDraft: false, agentPreset: 'cordis' })
|
||||
}
|
||||
|
||||
scope.effect(() => {
|
||||
|
||||
@@ -3,8 +3,10 @@
|
||||
*
|
||||
* The new-session screen has no session, so a pick is staged rather than
|
||||
* applied. It reaches a session when one becomes current and is still blank —
|
||||
* whether the workspace connect created it or reused an existing blank one,
|
||||
* which is why staging cannot simply ride along on `sessions.create`.
|
||||
* whether the workspace connect created it or reused an existing blank one. A
|
||||
* flow that knows its preset before it starts (the settings section's creator
|
||||
* entry) passes it to session creation instead, and its stage only drives the
|
||||
* chip's display.
|
||||
*
|
||||
* The stage is forgotten once applied. The next new session starts from the
|
||||
* Host-effective default again.
|
||||
|
||||
@@ -212,7 +212,7 @@ function declareConversation(slots: SlotRegistry): () => void {
|
||||
|
||||
/** A Workspace UI double recording new-session starts. */
|
||||
function uiWorkspaceDouble() {
|
||||
const starts: unknown[] = []
|
||||
const starts: { workspaceId: unknown; options: unknown }[] = []
|
||||
return {
|
||||
starts,
|
||||
startSession: (workspaceId?: unknown, options?: unknown) => { starts.push({ workspaceId, options }) },
|
||||
@@ -1066,7 +1066,7 @@ describe('ui-agent-preset apply', () => {
|
||||
// new-session flow began.
|
||||
expect(section.startCreatorDraft).toBeDefined()
|
||||
expect(seat.hooks.agentPresetSeat.getSnapshot().current).toBe('cordis')
|
||||
expect(uiWorkspace.starts).toHaveLength(1)
|
||||
expect(uiWorkspace.starts).toEqual([{ workspaceId: undefined, options: { clearPreviousDraft: false, agentPreset: 'cordis' } }])
|
||||
|
||||
// A cross-screen stage carries the introduce cue; the chip acknowledges
|
||||
// it once, and a repeat acknowledgement leaves the snapshot untouched.
|
||||
@@ -1079,15 +1079,16 @@ describe('ui-agent-preset apply', () => {
|
||||
conversation()
|
||||
})
|
||||
|
||||
it('applies the creator preset to an existing blank main Session', async () => {
|
||||
it('lets the new-session flow compose the creator preset on a blank main Session', async () => {
|
||||
const { ctx, slots, calls } = await bench()
|
||||
declareRoot(slots)
|
||||
const conversation = declareConversation(slots)
|
||||
ctx.provide('conversation', {} as never)
|
||||
const sessions = sessionsDouble(ctx, {
|
||||
const state = {
|
||||
current: 's1',
|
||||
byId: { s1: { id: 's1', blank: true, projectionValues: { agentPreset: 'standard' } } },
|
||||
})
|
||||
}
|
||||
const sessions = sessionsDouble(ctx, state)
|
||||
ctx.provide('sessions', sessions as never)
|
||||
const uiWorkspace = uiWorkspaceDouble()
|
||||
ctx.provide('uiWorkspace', uiWorkspace as never)
|
||||
@@ -1100,10 +1101,13 @@ describe('ui-agent-preset apply', () => {
|
||||
await seat.load()
|
||||
await section.load()
|
||||
section.startCreatorDraft?.()
|
||||
expect(uiWorkspace.starts).toEqual([{ workspaceId: undefined, options: { clearPreviousDraft: false, agentPreset: 'cordis' } }])
|
||||
|
||||
await vi.waitFor(() => { expect(calls).toContain('select:cordis') })
|
||||
expect(seat.hooks.agentPresetSeat.getSnapshot().current).toBe('cordis')
|
||||
expect(uiWorkspace.starts).toEqual([{ workspaceId: undefined, options: { clearPreviousDraft: false } }])
|
||||
// The Host composes the reused Session; the chip only follows its projection.
|
||||
state.byId.s1 = { id: 's1', blank: true, projectionValues: { agentPreset: 'cordis' } }
|
||||
sessions.notify()
|
||||
await vi.waitFor(() => { expect(seat.hooks.agentPresetSeat.getSnapshot().current).toBe('cordis') })
|
||||
expect(calls).not.toContain('select:cordis')
|
||||
conversation()
|
||||
})
|
||||
|
||||
|
||||
@@ -33,8 +33,8 @@
|
||||
en: 4cd7c81d70d2f365
|
||||
zh: 18eca6d16e44b6c2
|
||||
/deepseek-ai-dsh-client-ui-chat/grouped-rendering:
|
||||
en: 106438891c5175ce
|
||||
zh: 34dd30092f34f49b
|
||||
en: bc8d1d786c9affea
|
||||
zh: 3139f0228527a174
|
||||
/deepseek-ai-dsh-client-ui-chat/scroll-ownership:
|
||||
en: 3f4e6c161b4583bb
|
||||
zh: e4265bb2bce8eb1c
|
||||
|
||||
@@ -103,7 +103,7 @@ Chat registers its process Group Definition through `uiConversation.groups`. Rea
|
||||
|
||||
`groupPart` selects reasoning or response in the Assistant renderer without copying Node payloads. A Tool node owns its preparing, dispatched, and result stages under one callId. Each part has a distinct DOM anchor for reading-position restoration; Turn navigation addresses the original Node key and lands on its first visible part. Group sources, member parents, and keys survive display-mode changes and newly loaded prefixes that extend an intact group. The source Node Store remains the only Node-data owner, and a replaced Builder rebinds keyed subscriptions without remounting seats. Mode changes retain size observers and reuse the Turn-state selector.
|
||||
|
||||
The Chat Builder publishes `bottomSource` per Node: true for visible Nodes belonging to the last Turn in the loaded timeline, not just the final row. Advancing the bottom Turn notifies only Nodes in the old and new bottom Turns. Groups read their first member's position. Pending-input deduplication and collapse decisions remain in the Chat view, outside the Builder.
|
||||
The Chat Builder publishes `bottomSource` per Node: true for visible Nodes belonging to the latest loaded exchange, not just the final row. Nodes declare their group-tree position through `groupTree`; a Turn holding an `exchange` Node opens an exchange, and the exchange lasts until the next opening Turn. Moving the exchange start notifies only Nodes in Turns that entered or left it. Groups read their first member's position. Pending-input deduplication and collapse decisions remain in the Chat view, outside the Builder.
|
||||
|
||||
Live tool deltas share reasoning's frame-batched publication; durable calls and results publish immediately. Native and nested results retain event presentation metadata, so historical file and command labels use the operation’s location. Repeated deltas retain the Tool node when observed argument answers, the anchor, location, and visibility are unchanged. The Definition supplies the same lazy argument reader to tool rows and group detail, without tool-specific registration.
|
||||
|
||||
|
||||
@@ -103,7 +103,7 @@ Chat 通过 `uiConversation.groups` 注册过程 Group Definition。React 通过
|
||||
|
||||
`groupPart` 在 Assistant 渲染器中选择推理或回复,不复制 Node 载荷。同一个 callId 的准备、派发与结果阶段由 Tool 节点自己拥有。每个部分有独立的 DOM 锚点用于恢复阅读位置;轮次导航使用原 Node key,落到它的第一个可见部分。展示模式切换以及为完整旧组补入更早成员时,保留组来源、成员父级及 key。原 Node Store 仍是唯一节点数据所有者,替换 Builder 时重新绑定按键订阅,不重挂载容器。模式变化保留尺寸观察器,并复用整轮状态选择器。
|
||||
|
||||
Chat Builder 按节点发布 `bottomSource`:节点可见且属于已加载时间线的最后一轮时为 true,而不只是列表最后一行。底部轮次推进时,只有旧、新底部轮次的节点收到位置变化通知。Group 读取其首个成员的位置。待发送消息去重与收起判断仍由 Chat 视图处理,不进入 Builder。
|
||||
Chat Builder 按节点发布 `bottomSource`:节点可见且属于已加载的最新交互段时为 true,而不只是列表最后一行。节点通过 `groupTree` 声明自己在分组树中的位置;含 `exchange` 节点的轮次开启一个交互段,交互段持续到下一个开启轮次。交互段起点移动时,只有进入或离开该交互段的轮次中的节点收到通知。Group 读取其首个成员的位置。待发送消息去重与收起判断仍由 Chat 视图处理,不进入 Builder。
|
||||
|
||||
实时工具 delta 与推理共用按帧合并的发布节奏;持久调用和结果立即发布。原生与嵌套结果保留事件中的展示元数据,使历史文件与命令标签使用执行时的位置。当已读取参数的答案、锚点、位置及可见性均未变化时,重复 delta 保持 Tool 节点不变。Definition 向工具行和分组详情提供同一个懒计算参数读器,无需按工具注册。
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import type {
|
||||
ConversationLocation, ConversationViewNode, ModelRetryNode, RunningToolCall,
|
||||
ToolCallBlock,
|
||||
} from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
import type { ChatGroupTree } from './group-tree.ts'
|
||||
|
||||
/** Final Chat render unit produced by a Chat business Definition. */
|
||||
export interface ChatConversationViewNode extends ConversationViewNode {
|
||||
@@ -10,6 +11,13 @@ export interface ChatConversationViewNode extends ConversationViewNode {
|
||||
readonly anchorSeq: number
|
||||
readonly location: ConversationLocation
|
||||
readonly visibility: 'visible' | 'hidden'
|
||||
/**
|
||||
* Group-tree position, visible or hidden. An `exchange` Node's Turn and every
|
||||
* later Turn before the next opening Turn form one exchange; the latest
|
||||
* loaded exchange starts at the last loaded opening Turn, or at the first
|
||||
* loaded Turn when none is loaded.
|
||||
*/
|
||||
readonly groupTree?: ChatGroupTree | undefined
|
||||
}
|
||||
|
||||
/** Merge-extensible payload registry keyed by final Chat renderer kind. */
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { ChatConversationViewNode } from './chat-nodes.ts'
|
||||
|
||||
/**
|
||||
* Chat group-tree positions from the outermost grouping inward; a Node at a
|
||||
* position also stands outside every inner grouping.
|
||||
* - `exchange`: the Node's Turn opens an exchange, the run of Turns that lasts
|
||||
* until the next opening Turn.
|
||||
* - `turn`: the Node stays in its Turn outside the Turn's process disclosure.
|
||||
* - `process`: the Node stays in the process disclosure outside step runs.
|
||||
*
|
||||
* Only `exchange` is read today; process disclosure and step runs still select
|
||||
* independent Nodes by kind (`TURN_PROCESS_INDEPENDENT_KINDS`, the process-group
|
||||
* `INDEPENDENT` set), so no Definition publishes `turn` or `process` yet.
|
||||
*/
|
||||
export type ChatGroupTree = 'exchange' | 'turn' | 'process'
|
||||
|
||||
const DEPTH: Readonly<Record<ChatGroupTree, number>> = { exchange: 0, turn: 1, process: 2 }
|
||||
|
||||
/**
|
||||
* Test whether a Node stands at a group-tree position or outside it.
|
||||
* @param node - Chat Node.
|
||||
* @param position - group-tree position to compare against.
|
||||
* @returns whether the Node's position is `position` or an outer one.
|
||||
*/
|
||||
export function isAtOrOutside(node: Pick<ChatConversationViewNode, 'groupTree'>, position: ChatGroupTree): boolean {
|
||||
return node.groupTree !== undefined && DEPTH[node.groupTree] <= DEPTH[position]
|
||||
}
|
||||
Loaded 100 of 225 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user